[Zrouter-src-freebsd] ZRouter.org: push to FreeBSD HEAD tree

zrouter-src-freebsd at zrouter.org zrouter-src-freebsd at zrouter.org
Tue Dec 6 18:33:49 UTC 2011


details:   http://zrouter.org/hg/FreeBSD/head//rev/4aee9df9e1ae
changeset: 238:4aee9df9e1ae
user:      ray at terran.dlink.ua
date:      Tue Dec 06 20:26:16 2011 +0200
description:
FreeBSD HEAD @svn 228310r.

diffstat:

 head/Makefile.inc1                                                      |    35 +-
 head/ObsoleteFiles.inc                                                  |    15 +-
 head/UPDATING                                                           |     6 +-
 head/bin/sh/eval.c                                                      |    25 +-
 head/bin/test/test.c                                                    |    12 +-
 head/cddl/contrib/opensolaris/cmd/zdb/zdb.8                             |   128 +-
 head/cddl/contrib/opensolaris/cmd/zfs/zfs.8                             |  5914 ++++-----
 head/cddl/contrib/opensolaris/cmd/zfs/zfs_main.c                        |   491 +-
 head/cddl/contrib/opensolaris/cmd/zpool/zpool.8                         |  3431 ++--
 head/cddl/contrib/opensolaris/cmd/zpool/zpool_main.c                    |   113 +-
 head/cddl/contrib/opensolaris/cmd/zstreamdump/zstreamdump.1             |   108 +-
 head/cddl/contrib/opensolaris/cmd/ztest/ztest.c                         |    36 +-
 head/cddl/contrib/opensolaris/lib/libzfs/common/libzfs.h                |    57 +-
 head/cddl/contrib/opensolaris/lib/libzfs/common/libzfs_dataset.c        |   482 +-
 head/cddl/contrib/opensolaris/lib/libzfs/common/libzfs_graph.c          |   653 -
 head/cddl/contrib/opensolaris/lib/libzfs/common/libzfs_impl.h           |     4 +-
 head/cddl/contrib/opensolaris/lib/libzfs/common/libzfs_import.c         |    18 +-
 head/cddl/contrib/opensolaris/lib/libzfs/common/libzfs_iter.c           |   462 +
 head/cddl/contrib/opensolaris/lib/libzfs/common/libzfs_pool.c           |    45 +-
 head/cddl/contrib/opensolaris/lib/libzfs/common/libzfs_sendrecv.c       |   605 +-
 head/cddl/contrib/opensolaris/lib/libzfs/common/libzfs_util.c           |     5 +-
 head/cddl/lib/drti/Makefile                                             |     4 +-
 head/cddl/lib/libzfs/Makefile                                           |     4 +-
 head/contrib/gperf/AUTHORS                                              |     2 +-
 head/contrib/gperf/COPYING                                              |     2 +-
 head/contrib/gperf/ChangeLog                                            |  1643 ++
 head/contrib/gperf/FREEBSD-Xlist                                        |     6 +-
 head/contrib/gperf/INSTALL                                              |     4 +-
 head/contrib/gperf/Makefile.devel                                       |    32 +-
 head/contrib/gperf/Makefile.in                                          |    12 +-
 head/contrib/gperf/NEWS                                                 |    70 +
 head/contrib/gperf/README                                               |     7 +-
 head/contrib/gperf/acconfig.h                                           |     4 -
 head/contrib/gperf/aclocal.m4                                           |     2 -
 head/contrib/gperf/configure                                            |  3034 ++++-
 head/contrib/gperf/configure.ac                                         |    55 +
 head/contrib/gperf/configure.in                                         |    46 -
 head/contrib/gperf/doc/Makefile.in                                      |    44 +-
 head/contrib/gperf/doc/configure                                        |  2801 +++-
 head/contrib/gperf/doc/configure.ac                                     |    37 +
 head/contrib/gperf/doc/configure.in                                     |    35 -
 head/contrib/gperf/doc/gperf.1                                          |   103 +-
 head/contrib/gperf/doc/gperf.texi                                       |   811 +-
 head/contrib/gperf/doc/help2man                                         |    34 +-
 head/contrib/gperf/doc/texinfo.tex                                      |  5999 ----------
 head/contrib/gperf/lib/Makefile.in                                      |    19 +-
 head/contrib/gperf/lib/configure                                        |  4998 ++++++-
 head/contrib/gperf/lib/configure.ac                                     |    45 +
 head/contrib/gperf/lib/configure.in                                     |    43 -
 head/contrib/gperf/lib/getline.cc                                       |   119 +
 head/contrib/gperf/lib/getline.h                                        |    41 +
 head/contrib/gperf/lib/hash.cc                                          |     8 +-
 head/contrib/gperf/lib/hash.h                                           |     6 +-
 head/contrib/gperf/src/Makefile.in                                      |    85 +-
 head/contrib/gperf/src/bool-array.cc                                    |    46 +-
 head/contrib/gperf/src/bool-array.h                                     |    83 +-
 head/contrib/gperf/src/bool-array.icc                                   |    97 +-
 head/contrib/gperf/src/config.h.in                                      |    27 +-
 head/contrib/gperf/src/config.h_vms                                     |    20 +
 head/contrib/gperf/src/configure                                        |  5371 +++++++-
 head/contrib/gperf/src/configure.ac                                     |    68 +
 head/contrib/gperf/src/configure.in                                     |    71 -
 head/contrib/gperf/src/gen-perf.cc                                      |   359 -
 head/contrib/gperf/src/gen-perf.h                                       |    50 -
 head/contrib/gperf/src/hash-table.cc                                    |   206 +-
 head/contrib/gperf/src/hash-table.h                                     |    69 +-
 head/contrib/gperf/src/input.cc                                         |  1005 +
 head/contrib/gperf/src/input.h                                          |    69 +
 head/contrib/gperf/src/iterator.cc                                      |    87 -
 head/contrib/gperf/src/iterator.h                                       |    51 -
 head/contrib/gperf/src/key-list.cc                                      |  2182 ---
 head/contrib/gperf/src/key-list.h                                       |    96 -
 head/contrib/gperf/src/keyword-list.cc                                  |   175 +
 head/contrib/gperf/src/keyword-list.h                                   |    85 +
 head/contrib/gperf/src/keyword-list.icc                                 |    53 +
 head/contrib/gperf/src/keyword.cc                                       |   161 +
 head/contrib/gperf/src/keyword.h                                        |   116 +
 head/contrib/gperf/src/keyword.icc                                      |    42 +
 head/contrib/gperf/src/list-node.cc                                     |   102 -
 head/contrib/gperf/src/list-node.h                                      |    46 -
 head/contrib/gperf/src/main.cc                                          |   199 +-
 head/contrib/gperf/src/new.cc                                           |    87 -
 head/contrib/gperf/src/options.cc                                       |  1124 +-
 head/contrib/gperf/src/options.h                                        |   376 +-
 head/contrib/gperf/src/options.icc                                      |   192 +-
 head/contrib/gperf/src/output.cc                                        |  2100 +++
 head/contrib/gperf/src/output.h                                         |   154 +
 head/contrib/gperf/src/positions.cc                                     |   177 +
 head/contrib/gperf/src/positions.h                                      |   175 +
 head/contrib/gperf/src/positions.icc                                    |   285 +
 head/contrib/gperf/src/read-line.cc                                     |    97 -
 head/contrib/gperf/src/read-line.h                                      |    53 -
 head/contrib/gperf/src/read-line.icc                                    |    47 -
 head/contrib/gperf/src/search.cc                                        |  1684 ++
 head/contrib/gperf/src/search.h                                         |   165 +
 head/contrib/gperf/src/trace.cc                                         |    35 -
 head/contrib/gperf/src/trace.h                                          |    40 -
 head/contrib/gperf/src/vectors.cc                                       |    25 -
 head/contrib/gperf/src/vectors.h                                        |    37 -
 head/contrib/gperf/src/version.cc                                       |    36 +-
 head/contrib/gperf/src/version.h                                        |    30 +-
 head/contrib/gperf/tests/Makefile.in                                    |   232 -
 head/contrib/gperf/tests/ada-pred.exp                                   |    54 -
 head/contrib/gperf/tests/ada-res.exp                                    |    63 -
 head/contrib/gperf/tests/ada.gperf                                      |    63 -
 head/contrib/gperf/tests/adadefs.gperf                                  |    54 -
 head/contrib/gperf/tests/c++.gperf                                      |    47 -
 head/contrib/gperf/tests/c-parse.gperf                                  |    56 -
 head/contrib/gperf/tests/c.exp                                          |    32 -
 head/contrib/gperf/tests/c.gperf                                        |    32 -
 head/contrib/gperf/tests/configure                                      |  1214 --
 head/contrib/gperf/tests/configure.in                                   |    45 -
 head/contrib/gperf/tests/gpc.gperf                                      |    48 -
 head/contrib/gperf/tests/gplus.gperf                                    |    76 -
 head/contrib/gperf/tests/irc.gperf                                      |    63 -
 head/contrib/gperf/tests/jscript.gperf                                  |    73 -
 head/contrib/gperf/tests/jstest1.gperf                                  |   142 -
 head/contrib/gperf/tests/jstest2.gperf                                  |   147 -
 head/contrib/gperf/tests/jstest3.gperf                                  |   147 -
 head/contrib/gperf/tests/makeinfo.gperf                                 |   116 -
 head/contrib/gperf/tests/modula.exp                                     |   106 -
 head/contrib/gperf/tests/modula2.gperf                                  |    40 -
 head/contrib/gperf/tests/modula3.gperf                                  |   106 -
 head/contrib/gperf/tests/pascal.exp                                     |    36 -
 head/contrib/gperf/tests/pascal.gperf                                   |    36 -
 head/contrib/gperf/tests/test-1.exp                                     |   153 -
 head/contrib/gperf/tests/test-2.exp                                     |   202 -
 head/contrib/gperf/tests/test-3.exp                                     |   186 -
 head/contrib/gperf/tests/test-4.exp                                     |   162 -
 head/contrib/gperf/tests/test-5.exp                                     |   124 -
 head/contrib/gperf/tests/test-6.exp                                     |   119 -
 head/contrib/gperf/tests/test-7.exp                                     |    32 -
 head/contrib/gperf/tests/test.c                                         |    26 -
 head/contrib/gperf/tests/validate                                       |    54 -
 head/contrib/libcxxrt/FREEBSD-upgrade                                   |     6 +
 head/contrib/libcxxrt/LICENSE                                           |    14 +
 head/contrib/libcxxrt/abi_namespace.h                                   |     5 +
 head/contrib/libcxxrt/auxhelper.cc                                      |    41 +
 head/contrib/libcxxrt/cxxabi.h                                          |   219 +
 head/contrib/libcxxrt/dwarf_eh.h                                        |   454 +
 head/contrib/libcxxrt/dynamic_cast.cc                                   |   133 +
 head/contrib/libcxxrt/exception.cc                                      |  1483 ++
 head/contrib/libcxxrt/guard.cc                                          |   134 +
 head/contrib/libcxxrt/libelftc_dem_gnu3.c                               |  3473 +++++
 head/contrib/libcxxrt/memory.cc                                         |   115 +
 head/contrib/libcxxrt/stdexcept.cc                                      |    60 +
 head/contrib/libcxxrt/stdexcept.h                                       |    61 +
 head/contrib/libcxxrt/terminate.cc                                      |    14 +
 head/contrib/libcxxrt/typeinfo                                          |    26 +
 head/contrib/libcxxrt/typeinfo.cc                                       |    83 +
 head/contrib/libcxxrt/typeinfo.h                                        |   200 +
 head/contrib/libcxxrt/unwind-arm.h                                      |   201 +
 head/contrib/libcxxrt/unwind-itanium.h                                  |   170 +
 head/contrib/libcxxrt/unwind.h                                          |    18 +
 head/etc/devd/apple.conf                                                |    12 +-
 head/etc/mtree/BSD.include.dist                                         |     6 +-
 head/etc/rc.d/kld                                                       |     4 +-
 head/gnu/lib/Makefile                                                   |     5 +-
 head/gnu/lib/libodialog/CHANGES                                         |     9 -
 head/gnu/lib/libodialog/COPYING                                         |   339 -
 head/gnu/lib/libodialog/Makefile                                        |    24 -
 head/gnu/lib/libodialog/README                                          |     8 -
 head/gnu/lib/libodialog/TESTS/Makefile                                  |    20 -
 head/gnu/lib/libodialog/TESTS/check1.c                                  |    83 -
 head/gnu/lib/libodialog/TESTS/check2.c                                  |   105 -
 head/gnu/lib/libodialog/TESTS/check3.c                                  |    92 -
 head/gnu/lib/libodialog/TESTS/dselect.c                                 |    41 -
 head/gnu/lib/libodialog/TESTS/fselect.c                                 |    44 -
 head/gnu/lib/libodialog/TESTS/ftree1.c                                  |    45 -
 head/gnu/lib/libodialog/TESTS/ftree1.test                               |    73 -
 head/gnu/lib/libodialog/TESTS/ftree2.c                                  |    47 -
 head/gnu/lib/libodialog/TESTS/ftree2.test                               |    73 -
 head/gnu/lib/libodialog/TESTS/gauge.c                                   |    41 -
 head/gnu/lib/libodialog/TESTS/input1.c                                  |    45 -
 head/gnu/lib/libodialog/TESTS/input2.c                                  |    47 -
 head/gnu/lib/libodialog/TESTS/menu1.c                                   |    96 -
 head/gnu/lib/libodialog/TESTS/menu2.c                                   |    96 -
 head/gnu/lib/libodialog/TESTS/menu3.c                                   |   107 -
 head/gnu/lib/libodialog/TESTS/msg.c                                     |    42 -
 head/gnu/lib/libodialog/TESTS/prgbox.c                                  |    41 -
 head/gnu/lib/libodialog/TESTS/radio1.c                                  |    71 -
 head/gnu/lib/libodialog/TESTS/radio2.c                                  |    89 -
 head/gnu/lib/libodialog/TESTS/radio3.c                                  |    98 -
 head/gnu/lib/libodialog/TESTS/text.c                                    |    41 -
 head/gnu/lib/libodialog/TESTS/tree.c                                    |   111 -
 head/gnu/lib/libodialog/TESTS/yesno.c                                   |    45 -
 head/gnu/lib/libodialog/TODO                                            |    36 -
 head/gnu/lib/libodialog/checklist.c                                     |   661 -
 head/gnu/lib/libodialog/colors.h                                        |   219 -
 head/gnu/lib/libodialog/dialog.3                                        |   842 -
 head/gnu/lib/libodialog/dialog.h                                        |   211 -
 head/gnu/lib/libodialog/dialog.priv.h                                   |   183 -
 head/gnu/lib/libodialog/dir.c                                           |   549 -
 head/gnu/lib/libodialog/dir.h                                           |    38 -
 head/gnu/lib/libodialog/fselect.c                                       |   402 -
 head/gnu/lib/libodialog/gauge.c                                         |    79 -
 head/gnu/lib/libodialog/help.c                                          |   194 -
 head/gnu/lib/libodialog/inputbox.c                                      |   190 -
 head/gnu/lib/libodialog/kernel.c                                        |   536 -
 head/gnu/lib/libodialog/lineedit.c                                      |   213 -
 head/gnu/lib/libodialog/menubox.c                                       |   469 -
 head/gnu/lib/libodialog/msgbox.c                                        |   346 -
 head/gnu/lib/libodialog/notify.c                                        |    53 -
 head/gnu/lib/libodialog/prgbox.c                                        |   152 -
 head/gnu/lib/libodialog/radiolist.c                                     |   628 -
 head/gnu/lib/libodialog/raw_popen.c                                     |   161 -
 head/gnu/lib/libodialog/rc.c                                            |   375 -
 head/gnu/lib/libodialog/rc.h                                            |   222 -
 head/gnu/lib/libodialog/textbox.c                                       |   699 -
 head/gnu/lib/libodialog/tree.c                                          |  1133 -
 head/gnu/lib/libodialog/ui_objects.c                                    |   829 -
 head/gnu/lib/libodialog/ui_objects.h                                    |   114 -
 head/gnu/lib/libodialog/yesno.c                                         |   169 -
 head/gnu/usr.bin/dialog/Makefile                                        |     4 +-
 head/gnu/usr.bin/gperf/Makefile                                         |    17 +-
 head/gnu/usr.bin/gperf/config.h                                         |    31 +-
 head/kerberos5/Makefile.inc                                             |     6 +-
 head/kerberos5/lib/libhdb/Makefile                                      |     8 +-
 head/kerberos5/usr.bin/kadmin/Makefile                                  |     6 +-
 head/kerberos5/usr.sbin/ktutil/Makefile                                 |     6 +-
 head/lib/Makefile                                                       |    11 +-
 head/lib/libc++/Makefile                                                |   155 +
 head/lib/libc/gen/_pthread_stubs.c                                      |    14 +-
 head/lib/libc/gen/syslog.c                                              |     8 +-
 head/lib/libc/locale/duplocale.3                                        |    22 +-
 head/lib/libc/locale/freelocale.3                                       |    14 +-
 head/lib/libc/locale/localeconv.3                                       |     9 +-
 head/lib/libc/locale/newlocale.3                                        |    35 +-
 head/lib/libc/locale/querylocale.3                                      |     8 +-
 head/lib/libc/locale/uselocale.3                                        |    17 +-
 head/lib/libc/locale/wctype.c                                           |    73 +-
 head/lib/libc/locale/xlocale.3                                          |    75 +-
 head/lib/libc/string/strcasecmp.c                                       |    31 +-
 head/lib/libc/string/strcmp.c                                           |     5 +-
 head/lib/libc/string/strcoll.c                                          |    14 +-
 head/lib/libc/string/strncmp.c                                          |     6 +-
 head/lib/libc/sys/cap_enter.2                                           |     5 +-
 head/lib/libc/sys/cap_new.2                                             |     3 +-
 head/lib/libcxxrt/Makefile                                              |    25 +
 head/lib/libedit/edit/readline/Makefile                                 |     3 +-
 head/lib/libedit/edit/readline/readline.h                               |     3 +-
 head/lib/libpam/modules/Makefile.inc                                    |    13 +-
 head/lib/libpam/modules/pam_unix/Makefile                               |     6 +-
 head/lib/libusb/libusb10.c                                              |    14 +-
 head/release/doc/en_US.ISO8859-1/hardware/article.sgml                  |    15 +-
 head/rescue/rescue/Makefile                                             |     6 +-
 head/sbin/camcontrol/Makefile                                           |     4 +-
 head/sbin/camcontrol/camcontrol.8                                       |    59 +-
 head/sbin/camcontrol/camcontrol.c                                       |    47 +-
 head/sbin/camcontrol/camcontrol.h                                       |     7 +-
 head/sbin/camcontrol/fwdownload.c                                       |   389 +
 head/sbin/camcontrol/util.c                                             |    30 +-
 head/sbin/dhclient/clparse.c                                            |     4 +-
 head/sbin/dhclient/dhclient-script                                      |     6 +-
 head/sbin/dhclient/dhclient.c                                           |     3 +-
 head/sbin/dhclient/dhcp-options.5                                       |     6 +-
 head/sbin/dhclient/dhcp.h                                               |     3 +-
 head/sbin/dhclient/options.c                                            |   168 +-
 head/sbin/dhclient/tables.c                                             |     7 +-
 head/sbin/switchctl/switchctl.c                                         |    43 +
 head/sbin/sysctl/sysctl.c                                               |     4 +-
 head/secure/lib/libcrypto/Makefile                                      |     3 +-
 head/share/man/man4/Makefile                                            |     8 +-
 head/share/man/man4/ahci.4                                              |    13 +-
 head/share/man/man4/amd.4                                               |    78 -
 head/share/man/man4/bge.4                                               |    10 +-
 head/share/man/man4/capsicum.4                                          |   120 +
 head/share/man/man4/ffclock.4                                           |   128 +
 head/share/man/man4/netmap.4                                            |     3 +-
 head/share/man/man5/src.conf.5                                          |    28 +-
 head/share/misc/committers-src.dot                                      |     4 +-
 head/share/mk/bsd.lib.mk                                                |    61 +-
 head/share/mk/bsd.libnames.mk                                           |     5 +-
 head/share/mk/bsd.own.mk                                                |    17 +-
 head/share/mk/bsd.prog.mk                                               |    21 +-
 head/share/mk/sys.mk                                                    |    84 +-
 head/sys/amd64/conf/NOTES                                               |     4 +-
 head/sys/arm/mv/common.c                                                |    10 +-
 head/sys/arm/mv/mv_machdep.c                                            |    10 +-
 head/sys/boot/i386/zfsboot/zfsboot.c                                    |     6 +-
 head/sys/boot/zfs/zfsimpl.c                                             |     5 +-
 head/sys/cam/cam_xpt.c                                                  |    14 +-
 head/sys/cddl/contrib/opensolaris/common/zfs/zfs_prop.c                 |    18 +-
 head/sys/cddl/contrib/opensolaris/common/zfs/zfs_prop.h                 |     2 +
 head/sys/cddl/contrib/opensolaris/common/zfs/zpool_prop.c               |     4 +
 head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/arc.c               |    10 +-
 head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/bpobj.c             |     7 +-
 head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/dmu_send.c          |   106 +-
 head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/dsl_dataset.c       |   338 +-
 head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/dsl_deadlist.c      |    30 +-
 head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/dsl_deleg.c         |    11 +-
 head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/dsl_pool.c          |     4 +
 head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/spa.c               |    91 +-
 head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/spa_config.c        |     6 +
 head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/spa_history.c       |     7 +-
 head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/spa_misc.c          |    16 +-
 head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/dmu.h           |     7 +-
 head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/dsl_dataset.h   |     5 +
 head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/dsl_deleg.h     |     4 +-
 head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/spa.h           |     3 +
 head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/spa_impl.h      |     5 +-
 head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/vdev.c              |     3 +
 head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zap_micro.c         |     3 +-
 head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_ioctl.c         |   246 +-
 head/sys/cddl/contrib/opensolaris/uts/common/sys/fs/zfs.h               |    14 +-
 head/sys/cddl/contrib/opensolaris/uts/common/sys/sysevent/eventdefs.h   |     2 +
 head/sys/compat/linprocfs/linprocfs.c                                   |     4 +-
 head/sys/conf/NOTES                                                     |     5 +-
 head/sys/conf/files                                                     |    50 +-
 head/sys/conf/files.amd64                                               |    33 +-
 head/sys/conf/files.sparc64                                             |     3 +-
 head/sys/conf/kern.mk                                                   |     9 +-
 head/sys/conf/kern.post.mk                                              |     8 +-
 head/sys/conf/kern.pre.mk                                               |    12 +-
 head/sys/conf/kmod.mk                                                   |    11 +-
 head/sys/conf/makeLINT.mk                                               |     4 +-
 head/sys/conf/newvers.sh                                                |     3 +-
 head/sys/conf/options                                                   |     5 +-
 head/sys/contrib/dev/acpica/acpica_prep.sh                              |    26 +-
 head/sys/contrib/dev/acpica/changes.txt                                 |   353 +-
 head/sys/contrib/dev/acpica/common/adisasm.c                            |     1 +
 head/sys/contrib/dev/acpica/common/adwalk.c                             |     4 +
 head/sys/contrib/dev/acpica/common/dmrestag.c                           |   193 +-
 head/sys/contrib/dev/acpica/common/dmtable.c                            |    94 +-
 head/sys/contrib/dev/acpica/common/dmtbdump.c                           |   584 +-
 head/sys/contrib/dev/acpica/common/dmtbinfo.c                           |   422 +-
 head/sys/contrib/dev/acpica/compiler/aslanalyze.c                       |    57 +-
 head/sys/contrib/dev/acpica/compiler/aslcodegen.c                       |     9 +-
 head/sys/contrib/dev/acpica/compiler/aslcompile.c                       |     2 +
 head/sys/contrib/dev/acpica/compiler/aslcompiler.h                      |    49 +-
 head/sys/contrib/dev/acpica/compiler/aslcompiler.l                      |   479 +-
 head/sys/contrib/dev/acpica/compiler/aslcompiler.y                      |  1043 +-
 head/sys/contrib/dev/acpica/compiler/asldefine.h                        |    22 +-
 head/sys/contrib/dev/acpica/compiler/aslerror.c                         |    21 +-
 head/sys/contrib/dev/acpica/compiler/aslfiles.c                         |     6 +-
 head/sys/contrib/dev/acpica/compiler/aslglobal.h                        |     1 +
 head/sys/contrib/dev/acpica/compiler/asllisting.c                       |    10 +-
 head/sys/contrib/dev/acpica/compiler/aslload.c                          |    20 +-
 head/sys/contrib/dev/acpica/compiler/asllookup.c                        |   129 +-
 head/sys/contrib/dev/acpica/compiler/aslmain.c                          |   121 +-
 head/sys/contrib/dev/acpica/compiler/aslmap.c                           |    77 +-
 head/sys/contrib/dev/acpica/compiler/aslmessages.h                      |   163 +-
 head/sys/contrib/dev/acpica/compiler/aslopcodes.c                       |   131 +-
 head/sys/contrib/dev/acpica/compiler/asloperands.c                      |     8 +-
 head/sys/contrib/dev/acpica/compiler/aslpredef.c                        |    21 +-
 head/sys/contrib/dev/acpica/compiler/aslresource.c                      |   101 +-
 head/sys/contrib/dev/acpica/compiler/aslrestype1.c                      |    20 +-
 head/sys/contrib/dev/acpica/compiler/aslrestype1i.c                     |    94 +-
 head/sys/contrib/dev/acpica/compiler/aslrestype2.c                      |     5 +-
 head/sys/contrib/dev/acpica/compiler/aslrestype2d.c                     |    42 +-
 head/sys/contrib/dev/acpica/compiler/aslrestype2e.c                     |    48 +-
 head/sys/contrib/dev/acpica/compiler/aslrestype2q.c                     |    40 +-
 head/sys/contrib/dev/acpica/compiler/aslrestype2s.c                     |  1187 +
 head/sys/contrib/dev/acpica/compiler/aslrestype2w.c                     |    34 +-
 head/sys/contrib/dev/acpica/compiler/aslstubs.c                         |    17 +
 head/sys/contrib/dev/acpica/compiler/asltransform.c                     |    17 +-
 head/sys/contrib/dev/acpica/compiler/asltree.c                          |    20 +-
 head/sys/contrib/dev/acpica/compiler/asltypes.h                         |     8 +-
 head/sys/contrib/dev/acpica/compiler/aslutils.c                         |    63 +-
 head/sys/contrib/dev/acpica/compiler/aslwalks.c                         |    73 +
 head/sys/contrib/dev/acpica/compiler/dtcompile.c                        |    28 +-
 head/sys/contrib/dev/acpica/compiler/dtcompiler.h                       |    22 +
 head/sys/contrib/dev/acpica/compiler/dtfield.c                          |    13 +
 head/sys/contrib/dev/acpica/compiler/dtsubtable.c                       |     5 +
 head/sys/contrib/dev/acpica/compiler/dttable.c                          |   447 +
 head/sys/contrib/dev/acpica/compiler/dttemplate.h                       |   116 +-
 head/sys/contrib/dev/acpica/compiler/dtutils.c                          |    11 +
 head/sys/contrib/dev/acpica/debugger/dbcmds.c                           |   499 +-
 head/sys/contrib/dev/acpica/debugger/dbdisply.c                         |    22 +-
 head/sys/contrib/dev/acpica/debugger/dbfileio.c                         |     5 +-
 head/sys/contrib/dev/acpica/debugger/dbinput.c                          |     9 +-
 head/sys/contrib/dev/acpica/debugger/dbutils.c                          |     2 +-
 head/sys/contrib/dev/acpica/disassembler/dmbuffer.c                     |     8 +-
 head/sys/contrib/dev/acpica/disassembler/dmopcode.c                     |    73 +-
 head/sys/contrib/dev/acpica/disassembler/dmresrc.c                      |    13 +-
 head/sys/contrib/dev/acpica/disassembler/dmresrcl.c                     |     1 -
 head/sys/contrib/dev/acpica/disassembler/dmresrcl2.c                    |   700 +
 head/sys/contrib/dev/acpica/disassembler/dmresrcs.c                     |    49 +-
 head/sys/contrib/dev/acpica/disassembler/dmutils.c                      |    50 +-
 head/sys/contrib/dev/acpica/disassembler/dmwalk.c                       |     3 +-
 head/sys/contrib/dev/acpica/dispatcher/dsargs.c                         |     2 +-
 head/sys/contrib/dev/acpica/dispatcher/dsfield.c                        |    86 +-
 head/sys/contrib/dev/acpica/events/evevent.c                            |    14 +
 head/sys/contrib/dev/acpica/events/evglock.c                            |     7 +
 head/sys/contrib/dev/acpica/events/evregion.c                           |    30 +-
 head/sys/contrib/dev/acpica/executer/exconfig.c                         |     2 +-
 head/sys/contrib/dev/acpica/executer/excreate.c                         |    28 +-
 head/sys/contrib/dev/acpica/executer/exdump.c                           |     6 +-
 head/sys/contrib/dev/acpica/executer/exfield.c                          |    26 +-
 head/sys/contrib/dev/acpica/executer/exfldio.c                          |    28 +-
 head/sys/contrib/dev/acpica/executer/exprep.c                           |    27 +
 head/sys/contrib/dev/acpica/executer/exutils.c                          |    30 +
 head/sys/contrib/dev/acpica/hardware/hwvalid.c                          |     2 +
 head/sys/contrib/dev/acpica/include/acapps.h                            |     9 +
 head/sys/contrib/dev/acpica/include/acconfig.h                          |     5 +-
 head/sys/contrib/dev/acpica/include/acdebug.h                           |     4 +
 head/sys/contrib/dev/acpica/include/acdisasm.h                          |   198 +-
 head/sys/contrib/dev/acpica/include/acevents.h                          |     3 +-
 head/sys/contrib/dev/acpica/include/acglobal.h                          |    20 +-
 head/sys/contrib/dev/acpica/include/acinterp.h                          |     4 +
 head/sys/contrib/dev/acpica/include/aclocal.h                           |    29 +-
 head/sys/contrib/dev/acpica/include/acnames.h                           |     1 +
 head/sys/contrib/dev/acpica/include/acobject.h                          |     4 +
 head/sys/contrib/dev/acpica/include/acopcode.h                          |     4 +
 head/sys/contrib/dev/acpica/include/acpixf.h                            |    30 +-
 head/sys/contrib/dev/acpica/include/acpredef.h                          |    38 +-
 head/sys/contrib/dev/acpica/include/acresrc.h                           |   115 +-
 head/sys/contrib/dev/acpica/include/acrestyp.h                          |   226 +-
 head/sys/contrib/dev/acpica/include/actbl.h                             |    21 +-
 head/sys/contrib/dev/acpica/include/actbl1.h                            |    85 +-
 head/sys/contrib/dev/acpica/include/actbl3.h                            |   650 +
 head/sys/contrib/dev/acpica/include/actypes.h                           |    15 +-
 head/sys/contrib/dev/acpica/include/acutils.h                           |    17 +
 head/sys/contrib/dev/acpica/include/amlcode.h                           |    29 +-
 head/sys/contrib/dev/acpica/include/amlresrc.h                          |   160 +
 head/sys/contrib/dev/acpica/include/platform/acenv.h                    |    24 +-
 head/sys/contrib/dev/acpica/namespace/nspredef.c                        |    43 +-
 head/sys/contrib/dev/acpica/namespace/nsrepair.c                        |     1 +
 head/sys/contrib/dev/acpica/namespace/nsrepair2.c                       |    20 +-
 head/sys/contrib/dev/acpica/os_specific/service_layers/osunixxf.c       |  1214 ++
 head/sys/contrib/dev/acpica/osunixxf.c                                  |  1208 --
 head/sys/contrib/dev/acpica/parser/psargs.c                             |   145 +-
 head/sys/contrib/dev/acpica/parser/psopcode.c                           |    11 +-
 head/sys/contrib/dev/acpica/parser/pstree.c                             |     7 +-
 head/sys/contrib/dev/acpica/resources/rscalc.c                          |    67 +-
 head/sys/contrib/dev/acpica/resources/rscreate.c                        |    73 +
 head/sys/contrib/dev/acpica/resources/rsdump.c                          |   156 +-
 head/sys/contrib/dev/acpica/resources/rsinfo.c                          |    59 +-
 head/sys/contrib/dev/acpica/resources/rsirq.c                           |    32 +
 head/sys/contrib/dev/acpica/resources/rslist.c                          |    75 +-
 head/sys/contrib/dev/acpica/resources/rsmisc.c                          |   266 +-
 head/sys/contrib/dev/acpica/resources/rsserial.c                        |   425 +
 head/sys/contrib/dev/acpica/resources/rsutils.c                         |    59 +
 head/sys/contrib/dev/acpica/resources/rsxface.c                         |    56 +-
 head/sys/contrib/dev/acpica/tables/tbfadt.c                             |    28 +-
 head/sys/contrib/dev/acpica/tables/tbutils.c                            |     8 +
 head/sys/contrib/dev/acpica/tools/acpiexec/aecommon.h                   |   197 -
 head/sys/contrib/dev/acpica/utilities/utdecode.c                        |     4 +-
 head/sys/contrib/dev/acpica/utilities/utmutex.c                         |     9 +-
 head/sys/contrib/dev/acpica/utilities/utresrc.c                         |   293 +-
 head/sys/contrib/dev/acpica/utilities/utxfmutex.c                       |   213 +
 head/sys/contrib/ipfilter/netinet/ip_compat.h                           |     6 +-
 head/sys/contrib/ipfilter/netinet/ip_proxy.c                            |     4 +-
 head/sys/contrib/octeon-sdk/cvmx-helper-board.c                         |    25 +-
 head/sys/contrib/pf/net/pf.c                                            |     6 +-
 head/sys/dev/acpica/acpi_battery.c                                      |    10 +-
 head/sys/dev/ahci/ahci.c                                                |     8 +-
 head/sys/dev/amd/amd.c                                                  |  2539 ----
 head/sys/dev/amd/amd.h                                                  |   585 -
 head/sys/dev/arcmsr/arcmsr.c                                            |    19 +-
 head/sys/dev/ata/chipsets/ata-ati.c                                     |    26 +-
 head/sys/dev/ata/chipsets/ata-nvidia.c                                  |     6 +-
 head/sys/dev/dc/dcphy.c                                                 |     4 +-
 head/sys/dev/dc/pnphy.c                                                 |     4 +-
 head/sys/dev/e1000/if_em.c                                              |   131 +-
 head/sys/dev/e1000/if_igb.c                                             |    98 +-
 head/sys/dev/e1000/if_lem.c                                             |    81 +-
 head/sys/dev/ed/if_ed.c                                                 |    21 +-
 head/sys/dev/et/if_et.c                                                 |   104 +-
 head/sys/dev/et/if_etreg.h                                              |    37 +-
 head/sys/dev/fdt/fdt_common.c                                           |     8 +-
 head/sys/dev/fdt/fdt_powerpc.c                                          |     4 +-
 head/sys/dev/fdt/fdtbus.c                                               |     4 +-
 head/sys/dev/gpio/gpioiic.c                                             |    40 +-
 head/sys/dev/hptiop/hptiop.c                                            |     6 +-
 head/sys/dev/hptmv/entry.c                                              |    15 +-
 head/sys/dev/hptrr/hptrr_osm_bsd.c                                      |    12 +-
 head/sys/dev/hwpmc/hwpmc_core.c                                         |    10 +-
 head/sys/dev/iicbus/iicbus.c                                            |     8 +-
 head/sys/dev/iicbus/iicbus.h                                            |     4 +-
 head/sys/dev/iicbus/iiconf.c                                            |    10 +-
 head/sys/dev/ixgbe/ixgbe.c                                              |   150 +-
 head/sys/dev/mii/acphy.c                                                |     4 +-
 head/sys/dev/mii/amphy.c                                                |     4 +-
 head/sys/dev/mii/atphy.c                                                |     5 +-
 head/sys/dev/mii/axphy.c                                                |     4 +-
 head/sys/dev/mii/bmtphy.c                                               |     5 +-
 head/sys/dev/mii/brgphy.c                                               |     8 +-
 head/sys/dev/mii/ciphy.c                                                |     4 +-
 head/sys/dev/mii/e1000phy.c                                             |     4 +-
 head/sys/dev/mii/gentbi.c                                               |     4 +-
 head/sys/dev/mii/icsphy.c                                               |     4 +-
 head/sys/dev/mii/ip1000phy.c                                            |     4 +-
 head/sys/dev/mii/jmphy.c                                                |     4 +-
 head/sys/dev/mii/lxtphy.c                                               |     4 +-
 head/sys/dev/mii/mii.c                                                  |     8 +-
 head/sys/dev/mii/miidevs                                                |    41 +-
 head/sys/dev/mii/mlphy.c                                                |     4 +-
 head/sys/dev/mii/nsgphy.c                                               |     4 +-
 head/sys/dev/mii/nsphy.c                                                |     4 +-
 head/sys/dev/mii/nsphyter.c                                             |     4 +-
 head/sys/dev/mii/pnaphy.c                                               |     4 +-
 head/sys/dev/mii/qsphy.c                                                |     4 +-
 head/sys/dev/mii/rgephy.c                                               |     4 +-
 head/sys/dev/mii/rlphy.c                                                |     4 +-
 head/sys/dev/mii/rlswitch.c                                             |     4 +-
 head/sys/dev/mii/smcphy.c                                               |     8 +-
 head/sys/dev/mii/tdkphy.c                                               |     4 +-
 head/sys/dev/mii/tlphy.c                                                |     4 +-
 head/sys/dev/mii/truephy.c                                              |     4 +-
 head/sys/dev/mii/ukphy.c                                                |     4 +-
 head/sys/dev/mii/xmphy.c                                                |     4 +-
 head/sys/dev/netmap/if_em_netmap.h                                      |   169 +-
 head/sys/dev/netmap/if_igb_netmap.h                                     |   139 +-
 head/sys/dev/netmap/if_lem_netmap.h                                     |   421 +-
 head/sys/dev/netmap/if_re_netmap.h                                      |   145 +-
 head/sys/dev/netmap/ixgbe_netmap.h                                      |   342 +-
 head/sys/dev/netmap/netmap.c                                            |   290 +-
 head/sys/dev/netmap/netmap_kern.h                                       |    20 +-
 head/sys/dev/ofw/ofw_fdt.c                                              |     6 +-
 head/sys/dev/ofw/openfirm.c                                             |     4 +-
 head/sys/dev/pci/pcireg.h                                               |     3 +-
 head/sys/dev/re/if_re.c                                                 |   163 +-
 head/sys/dev/sfxge/common/efsys.h                                       |     5 +-
 head/sys/dev/sfxge/common/efx.h                                         |     2 +
 head/sys/dev/sfxge/common/efx_bootcfg.c                                 |     3 +
 head/sys/dev/sfxge/common/efx_ev.c                                      |     3 +
 head/sys/dev/sfxge/common/efx_filter.c                                  |     3 +
 head/sys/dev/sfxge/common/efx_impl.h                                    |     2 +
 head/sys/dev/sfxge/common/efx_intr.c                                    |     3 +
 head/sys/dev/sfxge/common/efx_mac.c                                     |     3 +
 head/sys/dev/sfxge/common/efx_mcdi.c                                    |     3 +
 head/sys/dev/sfxge/common/efx_mcdi.h                                    |     2 +
 head/sys/dev/sfxge/common/efx_mon.c                                     |     3 +
 head/sys/dev/sfxge/common/efx_nic.c                                     |     3 +
 head/sys/dev/sfxge/common/efx_nvram.c                                   |     3 +
 head/sys/dev/sfxge/common/efx_phy.c                                     |     3 +
 head/sys/dev/sfxge/common/efx_port.c                                    |     3 +
 head/sys/dev/sfxge/common/efx_regs.h                                    |     2 +
 head/sys/dev/sfxge/common/efx_regs_ef10.h                               |     2 +
 head/sys/dev/sfxge/common/efx_regs_mcdi.h                               |     5 +-
 head/sys/dev/sfxge/common/efx_regs_pci.h                                |     2 +
 head/sys/dev/sfxge/common/efx_rx.c                                      |     3 +
 head/sys/dev/sfxge/common/efx_sram.c                                    |     3 +
 head/sys/dev/sfxge/common/efx_tx.c                                      |     3 +
 head/sys/dev/sfxge/common/efx_types.h                                   |     2 +
 head/sys/dev/sfxge/common/efx_vpd.c                                     |     3 +
 head/sys/dev/sfxge/common/efx_wol.c                                     |     3 +
 head/sys/dev/sfxge/common/siena_flash.h                                 |     3 +-
 head/sys/dev/sfxge/common/siena_impl.h                                  |     2 +
 head/sys/dev/sfxge/common/siena_mac.c                                   |     4 +
 head/sys/dev/sfxge/common/siena_mon.c                                   |     4 +
 head/sys/dev/sfxge/common/siena_nic.c                                   |     4 +
 head/sys/dev/sfxge/common/siena_nvram.c                                 |     3 +
 head/sys/dev/sfxge/common/siena_phy.c                                   |     4 +
 head/sys/dev/sfxge/common/siena_sram.c                                  |     4 +
 head/sys/dev/sfxge/common/siena_vpd.c                                   |     3 +
 head/sys/dev/uart/uart_bus_fdt.c                                        |     6 +-
 head/sys/dev/usb/net/ruephy.c                                           |     4 +-
 head/sys/dev/usb/quirk/usb_quirk.c                                      |     3 +-
 head/sys/dev/usb/template/usb_template.c                                |     4 +-
 head/sys/dev/usb/template/usb_template_kbd.c                            |     8 +-
 head/sys/dev/usb/template/usb_template_modem.c                          |     8 +-
 head/sys/dev/usb/template/usb_template_mouse.c                          |     8 +-
 head/sys/dev/usb/usb_msctest.c                                          |     4 +-
 head/sys/dev/usb/usb_transfer.h                                         |   116 +-
 head/sys/dev/usb/usbdevs                                                |     6 +-
 head/sys/dev/usb/wlan/if_urtw.c                                         |     6 +-
 head/sys/dev/usb/wlan/if_zyd.c                                          |     6 +-
 head/sys/dev/virtio/balloon/virtio_balloon.c                            |     3 +-
 head/sys/dev/virtio/balloon/virtio_balloon.h                            |    27 +-
 head/sys/dev/virtio/block/virtio_blk.c                                  |    31 +-
 head/sys/dev/virtio/block/virtio_blk.h                                  |    37 +-
 head/sys/dev/virtio/network/if_vtnet.c                                  |    77 +-
 head/sys/dev/virtio/network/if_vtnetvar.h                               |     3 +-
 head/sys/dev/virtio/network/virtio_net.h                                |    27 +-
 head/sys/dev/virtio/pci/virtio_pci.h                                    |    27 +-
 head/sys/dev/virtio/virtio.h                                            |    27 +-
 head/sys/dev/virtio/virtio_ring.h                                       |    34 +-
 head/sys/dev/vr/if_vr.c                                                 |    79 +-
 head/sys/dev/vr/if_vrreg.h                                              |    13 +-
 head/sys/dev/xl/xlphy.c                                                 |     4 +-
 head/sys/fs/fifofs/fifo_vnops.c                                         |     4 +-
 head/sys/fs/nfs/nfsclstate.h                                            |    13 +-
 head/sys/fs/nfsclient/nfs_clbio.c                                       |     4 +-
 head/sys/fs/nfsclient/nfs_clstate.c                                     |   147 +-
 head/sys/fs/nfsserver/nfs_nfsdport.c                                    |   123 +-
 head/sys/fs/nfsserver/nfs_nfsdsubs.c                                    |    12 +-
 head/sys/fs/ntfs/ntfs_subr.c                                            |    88 +-
 head/sys/fs/ntfs/ntfs_subr.h                                            |     6 +-
 head/sys/fs/ntfs/ntfs_vnops.c                                           |    11 +-
 head/sys/fs/nwfs/nwfs_io.c                                              |     4 +-
 head/sys/fs/smbfs/smbfs_io.c                                            |     4 +-
 head/sys/geom/geom_vfs.c                                                |     6 +-
 head/sys/geom/part/g_part_apm.c                                         |    81 +-
 head/sys/i386/conf/PAE                                                  |     3 +-
 head/sys/kern/kern_cpuset.c                                             |     3 +-
 head/sys/kern/kern_ffclock.c                                            |   106 +-
 head/sys/kern/kern_proc.c                                               |   113 +-
 head/sys/kern/kern_resource.c                                           |     7 +-
 head/sys/kern/kern_switch.c                                             |     4 +-
 head/sys/kern/kern_synch.c                                              |     5 +-
 head/sys/kern/kern_tc.c                                                 |   138 +-
 head/sys/kern/kern_thr.c                                                |     8 +-
 head/sys/kern/kern_umtx.c                                               |   140 +-
 head/sys/kern/subr_blist.c                                              |    12 +-
 head/sys/kern/subr_bus.c                                                |    37 +-
 head/sys/kern/sys_pipe.c                                                |    45 +-
 head/sys/kern/uipc_shm.c                                                |     4 +-
 head/sys/kern/vfs_bio.c                                                 |     6 +-
 head/sys/kern/vfs_syscalls.c                                            |    17 +-
 head/sys/mips/atheros/ar71xx_chip.c                                     |    58 +-
 head/sys/mips/atheros/ar71xx_cpudef.h                                   |     2 +-
 head/sys/mips/atheros/ar71xx_machdep.c                                  |    18 +-
 head/sys/mips/atheros/ar724x_chip.c                                     |    65 +-
 head/sys/mips/atheros/ar91xx_chip.c                                     |    58 +-
 head/sys/mips/atheros/if_arge.c                                         |    14 +-
 head/sys/mips/cavium/files.octeon1                                      |     8 +-
 head/sys/mips/cavium/octe/ethernet-rgmii.c                              |     9 +
 head/sys/mips/cavium/octe/octe.c                                        |    13 +-
 head/sys/mips/cavium/octeon_machdep.c                                   |     6 +-
 head/sys/mips/conf/AR91XX_BASE                                          |    27 +-
 head/sys/mips/conf/AR91XX_BASE.hints                                    |     3 +-
 head/sys/mips/conf/OCTEON1                                              |    44 +-
 head/sys/mips/conf/OCTEON1.hints                                        |    17 +-
 head/sys/mips/conf/PB92                                                 |    12 +-
 head/sys/mips/conf/TP-WN1043ND                                          |    19 +-
 head/sys/mips/conf/TP-WN1043ND.hints                                    |    60 +-
 head/sys/mips/conf/XLPN32                                               |     8 +-
 head/sys/mips/mips/bus_space_generic.c                                  |    25 +-
 head/sys/mips/mips/db_trace.c                                           |     9 +-
 head/sys/mips/nlm/hal/cpucontrol.h                                      |     4 +-
 head/sys/mips/nlm/xlp_machdep.c                                         |     4 +-
 head/sys/modules/Makefile                                               |     4 +-
 head/sys/modules/acpi/acpi/Makefile                                     |     7 +-
 head/sys/modules/amd/Makefile                                           |    10 -
 head/sys/modules/cam/Makefile                                           |    11 +-
 head/sys/net/bpf.c                                                      |   156 +-
 head/sys/net/bpf.h                                                      |    25 +-
 head/sys/net/if_clone.c                                                 |   108 +-
 head/sys/net/if_clone.h                                                 |    21 +-
 head/sys/net/if_vlan.c                                                  |   166 +-
 head/sys/net/netmap.h                                                   |    11 +-
 head/sys/netinet/in.c                                                   |    12 +-
 head/sys/netinet/sctp_header.h                                          |     5 +-
 head/sys/netinet/sctp_output.c                                          |    12 +-
 head/sys/netinet/sctp_pcb.c                                             |     9 +-
 head/sys/netinet/sctp_uio.h                                             |     6 +-
 head/sys/netinet/tcp_reass.c                                            |    41 +-
 head/sys/netipsec/xform_ah.c                                            |    16 +-
 head/sys/netipsec/xform_esp.c                                           |    42 +-
 head/sys/nfsclient/nfs_bio.c                                            |     4 +-
 head/sys/nfsserver/nfs_serv.c                                           |   131 +-
 head/sys/pc98/include/md_var.h                                          |     8 +-
 head/sys/pc98/pc98/pc98_machdep.h                                       |     5 +-
 head/sys/pci/if_rlreg.h                                                 |    38 +-
 head/sys/powerpc/booke/platform_bare.c                                  |     4 +-
 head/sys/powerpc/powermac/platform_powermac.c                           |     6 +-
 head/sys/powerpc/powermac/pmu.c                                         |    16 +-
 head/sys/powerpc/powermac/pmuvar.h                                      |     3 +-
 head/sys/sparc64/conf/GENERIC                                           |     4 +-
 head/sys/sparc64/include/atomic.h                                       |     7 +-
 head/sys/sparc64/include/md_var.h                                       |     9 +-
 head/sys/sparc64/pci/schizo.c                                           |     4 +-
 head/sys/sparc64/sparc64/ata_machdep.c                                  |    17 +-
 head/sys/sparc64/sparc64/cam_machdep.c                                  |    74 +
 head/sys/sparc64/sparc64/ofw_machdep.c                                  |     4 +-
 head/sys/sparc64/sparc64/vm_machdep.c                                   |     4 +-
 head/sys/sys/resource.h                                                 |     4 +-
 head/sys/sys/sysctl.h                                                   |     4 +-
 head/sys/sys/timeffc.h                                                  |   157 +-
 head/sys/sys/umtx.h                                                     |     3 +-
 head/sys/vm/vm_page.c                                                   |    49 +-
 head/sys/vm/vm_page.h                                                   |    23 +-
 head/sys/vm/vm_reserv.c                                                 |   329 +-
 head/sys/vm/vm_reserv.h                                                 |    10 +-
 head/sys/vm/vnode_pager.c                                               |     6 +-
 head/sys/x86/acpica/acpi_apm.c                                          |    90 +-
 head/sys/xen/evtchn/evtchn_dev.c                                        |    19 +-
 head/tools/build/options/WITHOUT_GPIO                                   |     2 +-
 head/tools/build/options/WITHOUT_PROFILE                                |     2 +-
 head/tools/build/options/WITH_CTF                                       |     4 +
 head/tools/build/options/WITH_LIBCPLUSPLUS                              |     2 +
 head/tools/build/options/WITH_OFED                                      |     2 +-
 head/tools/regression/bin/sh/builtins/case11.0                          |     6 +
 head/tools/regression/bin/sh/builtins/case12.0                          |     6 +
 head/tools/regression/bin/test/regress.sh                               |    44 +-
 head/tools/regression/pipe/pipe-fstatbug.c                              |     4 +-
 head/tools/regression/pipe/pipe-ino.c                                   |    66 +
 head/tools/regression/pipe/pipe-reverse.c                               |     5 +-
 head/tools/regression/pipe/pipe-wraparound.c                            |     5 +-
 head/tools/regression/sbin/Makefile                                     |     4 +-
 head/tools/regression/sbin/dhclient/Makefile                            |    16 +
 head/tools/regression/sbin/dhclient/fake.c                              |    60 +
 head/tools/regression/sbin/dhclient/option-domain-search.c              |   328 +
 head/tools/regression/usr.bin/make/execution/ellipsis/Makefile          |    21 +
 head/tools/regression/usr.bin/make/execution/ellipsis/expected.status.1 |     1 +
 head/tools/regression/usr.bin/make/execution/ellipsis/expected.stdout.1 |    12 +
 head/tools/regression/usr.bin/make/execution/ellipsis/test.t            |    15 +
 head/tools/regression/usr.bin/make/execution/empty/Makefile             |    13 +
 head/tools/regression/usr.bin/make/execution/empty/expected.status.1    |     1 +
 head/tools/regression/usr.bin/make/execution/empty/test.t               |    15 +
 head/tools/regression/usr.bin/make/execution/plus/Makefile              |     7 +
 head/tools/regression/usr.bin/make/execution/plus/expected.status.1     |     1 +
 head/tools/regression/usr.bin/make/execution/plus/expected.stdout.1     |     1 +
 head/tools/regression/usr.bin/make/execution/plus/test.t                |    15 +
 head/tools/tinder.sh                                                    |    61 +
 head/tools/tools/ath/Makefile                                           |     2 +-
 head/tools/tools/ath/Makefile.inc                                       |     2 +-
 head/tools/tools/ath/arcode/Makefile                                    |     2 +-
 head/tools/tools/ath/arcode/arcode.c                                    |     2 +-
 head/tools/tools/ath/ath_ee_9287_print/9287.c                           |     2 +-
 head/tools/tools/ath/ath_ee_9287_print/9287.h                           |     2 +-
 head/tools/tools/ath/ath_ee_9287_print/Makefile                         |     2 +-
 head/tools/tools/ath/ath_ee_9287_print/eeprom.c                         |     2 +-
 head/tools/tools/ath/ath_ee_9287_print/eeprom.h                         |     2 +-
 head/tools/tools/ath/ath_ee_9287_print/main.c                           |     2 +-
 head/tools/tools/ath/ath_ee_v14_print/Makefile                          |     2 +-
 head/tools/tools/ath/ath_ee_v14_print/ath_ee_v14_print.c                |     2 +-
 head/tools/tools/ath/ath_ee_v4k_print/Makefile                          |     2 +-
 head/tools/tools/ath/ath_ee_v4k_print/eeprom.c                          |     2 +-
 head/tools/tools/ath/ath_ee_v4k_print/eeprom.h                          |     2 +-
 head/tools/tools/ath/ath_ee_v4k_print/main.c                            |     2 +-
 head/tools/tools/ath/ath_ee_v4k_print/v4k.c                             |     2 +-
 head/tools/tools/ath/ath_ee_v4k_print/v4k.h                             |     2 +-
 head/tools/tools/ath/ath_prom_read/Makefile                             |     2 +-
 head/tools/tools/ath/ath_prom_read/ath_prom_read.c                      |     2 +-
 head/tools/tools/ath/athctrl.sh                                         |     2 +-
 head/tools/tools/ath/athdebug/Makefile                                  |     2 +-
 head/tools/tools/ath/athdebug/athdebug.c                                |     2 +-
 head/tools/tools/ath/athdecode/Makefile                                 |     2 +-
 head/tools/tools/ath/athdecode/main.c                                   |     2 +-
 head/tools/tools/ath/athkey/Makefile                                    |     2 +-
 head/tools/tools/ath/athkey/athkey.c                                    |     2 +-
 head/tools/tools/ath/athpoke/Makefile                                   |     2 +-
 head/tools/tools/ath/athpoke/athpoke.c                                  |     2 +-
 head/tools/tools/ath/athpow/Makefile                                    |     2 +-
 head/tools/tools/ath/athpow/athpow.c                                    |     2 +-
 head/tools/tools/ath/athprom/Makefile                                   |     2 +-
 head/tools/tools/ath/athprom/athprom.c                                  |     2 +-
 head/tools/tools/ath/athprom/eeprom-14                                  |     2 +-
 head/tools/tools/ath/athprom/eeprom-3                                   |     2 +-
 head/tools/tools/ath/athprom/eeprom-4                                   |     2 +-
 head/tools/tools/ath/athprom/eeprom-5                                   |     2 +-
 head/tools/tools/ath/athradar/Makefile                                  |     2 +-
 head/tools/tools/ath/athradar/athradar.c                                |     2 +-
 head/tools/tools/ath/athrd/Makefile                                     |     2 +-
 head/tools/tools/ath/athrd/athrd.1                                      |     2 +-
 head/tools/tools/ath/athrd/athrd.c                                      |     2 +-
 head/tools/tools/ath/athrd/run.sh                                       |     2 +-
 head/tools/tools/ath/athregs/Makefile                                   |     2 +-
 head/tools/tools/ath/athregs/dumpregs.c                                 |     2 +-
 head/tools/tools/ath/athstats/Makefile                                  |     2 +-
 head/tools/tools/ath/athstats/athstats.h                                |     2 +-
 head/tools/tools/ath/athstats/main.c                                    |     2 +-
 head/tools/tools/ath/athstats/statfoo.c                                 |     2 +-
 head/tools/tools/ath/athstats/statfoo.h                                 |     2 +-
 head/tools/tools/ath/common/ah_osdep.h                                  |     2 +-
 head/tools/tools/ath/common/diag.h                                      |     2 +-
 head/tools/tools/ath/common/dumpregs.h                                  |     2 +-
 head/tools/tools/ath/common/dumpregs_5210.c                             |     2 +-
 head/tools/tools/ath/common/dumpregs_5211.c                             |     2 +-
 head/tools/tools/ath/common/dumpregs_5212.c                             |     2 +-
 head/tools/tools/ath/common/dumpregs_5416.c                             |     2 +-
 head/tools/tools/netmap/pkt-gen.c                                       |    19 +-
 head/usr.bin/grep/Makefile                                              |    17 +-
 head/usr.bin/grep/util.c                                                |    18 +-
 head/usr.bin/m4/Makefile                                                |    18 +-
 head/usr.bin/m4/eval.c                                                  |   401 +-
 head/usr.bin/m4/expr.c                                                  |   661 +-
 head/usr.bin/m4/extern.h                                                |   108 +-
 head/usr.bin/m4/gnum4.c                                                 |   241 +-
 head/usr.bin/m4/lib/ohash.h                                             |    75 +
 head/usr.bin/m4/lib/ohash_create_entry.c                                |    40 +
 head/usr.bin/m4/lib/ohash_delete.c                                      |    33 +
 head/usr.bin/m4/lib/ohash_do.c                                          |   113 +
 head/usr.bin/m4/lib/ohash_entries.c                                     |    28 +
 head/usr.bin/m4/lib/ohash_enum.c                                        |    38 +
 head/usr.bin/m4/lib/ohash_init.3                                        |   231 +
 head/usr.bin/m4/lib/ohash_init.c                                        |    43 +
 head/usr.bin/m4/lib/ohash_int.h                                         |    25 +
 head/usr.bin/m4/lib/ohash_interval.3                                    |    92 +
 head/usr.bin/m4/lib/ohash_interval.c                                    |    38 +
 head/usr.bin/m4/lib/ohash_lookup_interval.c                             |    70 +
 head/usr.bin/m4/lib/ohash_lookup_memory.c                               |    66 +
 head/usr.bin/m4/lib/ohash_qlookup.c                                     |    29 +
 head/usr.bin/m4/lib/ohash_qlookupi.c                                    |    31 +
 head/usr.bin/m4/look.c                                                  |   271 +-
 head/usr.bin/m4/m4.1                                                    |   504 +-
 head/usr.bin/m4/main.c                                                  |   413 +-
 head/usr.bin/m4/mdef.h                                                  |   102 +-
 head/usr.bin/m4/misc.c                                                  |   164 +-
 head/usr.bin/m4/parser.y                                                |    83 +
 head/usr.bin/m4/pathnames.h                                             |     9 +-
 head/usr.bin/m4/stdd.h                                                  |     6 +-
 head/usr.bin/m4/tokenizer.l                                             |   111 +
 head/usr.bin/m4/trace.c                                                 |   120 +-
 head/usr.bin/make/Makefile                                              |     6 +-
 head/usr.bin/make/job.c                                                 |   113 +-
 head/usr.bin/procstat/Makefile                                          |     3 +-
 head/usr.bin/procstat/procstat.1                                        |     8 +-
 head/usr.bin/procstat/procstat.c                                        |    20 +-
 head/usr.bin/procstat/procstat.h                                        |     3 +-
 head/usr.bin/procstat/procstat_auxv.c                                   |    98 +-
 head/usr.bin/procstat/procstat_rlimit.c                                 |    78 +
 head/usr.bin/truss/setup.c                                              |    18 +-
 head/usr.sbin/acpi/Makefile.inc                                         |    29 +-
 head/usr.sbin/acpi/acpidb/Makefile                                      |    10 +-
 head/usr.sbin/acpi/acpidb/acpidb.c                                      |     5 +-
 head/usr.sbin/acpi/iasl/Makefile                                        |    21 +-
 head/usr.sbin/bsdinstall/distextract/distextract.c                      |     3 +-
 head/usr.sbin/bsdinstall/distfetch/distfetch.c                          |     3 +-
 head/usr.sbin/bsdinstall/partedit/gpart_ops.c                           |     4 +-
 head/usr.sbin/bsdinstall/scripts/auto                                   |    25 +-
 head/usr.sbin/bsdinstall/scripts/services                               |    16 +-
 head/usr.sbin/config/mkmakefile.c                                       |     4 +-
 head/usr.sbin/cron/crontab/crontab.5                                    |     4 +-
 head/usr.sbin/makefs/Makefile                                           |     1 +
 head/usr.sbin/mergemaster/mergemaster.sh                                |     6 +-
 head/usr.sbin/mfiutil/mfi_config.c                                      |    10 +-
 head/usr.sbin/mfiutil/mfi_evt.c                                         |     4 +-
 head/usr.sbin/sade/Makefile                                             |    12 +-
 head/usr.sbin/sade/config.c                                             |   333 -
 head/usr.sbin/sade/devices.c                                            |    17 +-
 head/usr.sbin/sade/disks.c                                              |   187 +-
 head/usr.sbin/sade/dispatch.c                                           |   161 -
 head/usr.sbin/sade/dmenu.c                                              |   250 +-
 head/usr.sbin/sade/install.c                                            |   158 +-
 head/usr.sbin/sade/label.c                                              |   291 +-
 head/usr.sbin/sade/main.c                                               |    15 +-
 head/usr.sbin/sade/menus.c                                              |    47 +-
 head/usr.sbin/sade/misc.c                                               |   211 +-
 head/usr.sbin/sade/msg.c                                                |    49 +-
 head/usr.sbin/sade/sade.h                                               |    64 +-
 head/usr.sbin/sade/system.c                                             |    37 +-
 head/usr.sbin/tzsetup/Makefile                                          |     8 +-
 head/usr.sbin/tzsetup/tzsetup.c                                         |   206 +-
 827 files changed, 60048 insertions(+), 48460 deletions(-)

diffs (134648 lines):

diff -r 167f7ed19c6d -r 4aee9df9e1ae head/Makefile.inc1
--- a/head/Makefile.inc1	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/Makefile.inc1	Tue Dec 06 20:26:16 2011 +0200
@@ -1,5 +1,5 @@
 #
-# $FreeBSD: head/Makefile.inc1 227841 2011-11-22 21:18:14Z des $
+# $FreeBSD: head/Makefile.inc1 228158 2011-11-30 18:11:49Z fjoe $
 #
 # Make command line options:
 #	-DNO_CLEANDIR run ${MAKE} clean, instead of ${MAKE} cleandir
@@ -60,8 +60,6 @@
 .endif
 .if ${MK_CDDL} != "no"
 SUBDIR+=cddl
-.else
-NO_CTF=1
 .endif
 SUBDIR+=gnu include
 .if ${MK_KERBEROS} != "no"
@@ -241,7 +239,7 @@
 		BOOTSTRAPPING=${OSRELDATE} \
 		SSP_CFLAGS= \
 		-DWITHOUT_HTML -DWITHOUT_INFO -DNO_LINT -DWITHOUT_MAN \
-		-DNO_PIC -DWITHOUT_PROFILE -DNO_SHARED \
+		-DNO_PIC -DNO_PROFILE -DNO_SHARED \
 		-DNO_CPU_CFLAGS -DNO_WARNS -DNO_CTF
 
 # build-tools stage
@@ -441,7 +439,7 @@
 	@echo "--------------------------------------------------------------"
 	${_+_}cd ${.CURDIR}; \
 	    ${WMAKE} -DNO_FSCHG -DWITHOUT_HTML -DWITHOUT_INFO -DNO_LINT \
-	    -DWITHOUT_MAN -DWITHOUT_PROFILE libraries
+	    -DWITHOUT_MAN -DNO_PROFILE libraries
 _depend:
 	@echo
 	@echo "--------------------------------------------------------------"
@@ -1235,6 +1233,9 @@
 _startup_libs+=	gnu/lib/libgcc
 _startup_libs+=	lib/libcompiler_rt
 _startup_libs+=	lib/libc
+.if ${MK_LIBCPLUSPLUS} != "no"
+_startup_libs+=	lib/libcxxrt
+.endif
 
 gnu/lib/libgcc__L: lib/libc__L
 
@@ -1247,7 +1248,7 @@
 		${_lib_libgssapi} ${_lib_libipx} \
 		lib/libkiconv lib/libkvm lib/liblzma lib/libmd \
 		lib/ncurses/ncurses lib/ncurses/ncursesw \
-		lib/libopie ${_lib_libthr} \
+		lib/libopie lib/libpam ${_lib_libthr} \
 		lib/libradius lib/libsbuf lib/libtacplus \
 		${_cddl_lib_libumem} \
 		lib/libutil ${_lib_libypclnt} lib/libz lib/msun \
@@ -1335,12 +1336,12 @@
 		cd ${.CURDIR}/${_lib}; \
 		${MAKE} DIRPRFX=${_lib}/ obj; \
 		${MAKE} DIRPRFX=${_lib}/ depend; \
-		${MAKE} -DWITHOUT_PROFILE -DNO_PIC DIRPRFX=${_lib}/ all; \
-		${MAKE} -DWITHOUT_PROFILE -DNO_PIC DIRPRFX=${_lib}/ install
+		${MAKE} -DNO_PROFILE -DNO_PIC DIRPRFX=${_lib}/ all; \
+		${MAKE} -DNO_PROFILE -DNO_PIC DIRPRFX=${_lib}/ install
 .endif
 .endfor
 
-.for _lib in ${_startup_libs} ${_prebuild_libs} ${_generic_libs}
+.for _lib in ${_startup_libs} ${_prebuild_libs:Nlib/libpam} ${_generic_libs}
 ${_lib}__L: .PHONY
 .if exists(${.CURDIR}/${_lib})
 	${_+_}@${ECHODIR} "===> ${_lib} (obj,depend,all,install)"; \
@@ -1352,6 +1353,17 @@
 .endif
 .endfor
 
+# libpam is special: we need to build static PAM modules before
+# static PAM library, and dynamic PAM library before dynamic PAM
+# modules.
+lib/libpam__L: .PHONY
+	${_+_}@${ECHODIR} "===> lib/libpam (obj,depend,all,install)"; \
+		cd ${.CURDIR}/lib/libpam; \
+		${MAKE} DIRPRFX=lib/libpam/ obj; \
+		${MAKE} DIRPRFX=lib/libpam/ depend; \
+		${MAKE} DIRPRFX=lib/libpam/ -D_NO_LIBPAM_SO_YET all; \
+		${MAKE} DIRPRFX=lib/libpam/ -D_NO_LIBPAM_SO_YET install
+
 _prereq_libs: ${_prereq_libs:S/$/__PL/}
 _startup_libs: ${_startup_libs:S/$/__L/}
 _prebuild_libs: ${_prebuild_libs:S/$/__L/}
@@ -1558,7 +1570,7 @@
 .endif
 
 NOFUN=-DNO_FSCHG -DWITHOUT_HTML -DWITHOUT_INFO -DNO_LINT \
-	-DWITHOUT_MAN -DWITHOUT_NLS -DWITHOUT_PROFILE \
+	-DWITHOUT_MAN -DWITHOUT_NLS -DNO_PROFILE \
 	-DWITHOUT_KERBEROS -DWITHOUT_RESCUE -DNO_WARNS \
 	TARGET=${XDEV} TARGET_ARCH=${XDEV_ARCH} \
 	CPUTYPE=${XDEV_CPUTYPE}
@@ -1642,4 +1654,7 @@
 			ln -sf ../../${XDTP}/usr/bin/$$i \
 			    ../../../../usr/bin/${XDDIR}${OSREL}-$$i; \
 		done
+.else
+xdev xdev-buil xdev-install:
+	@echo "*** Error: Both XDEV and XDEV_ARCH must be defined for \"${.TARGET}\" target"
 .endif
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/ObsoleteFiles.inc
--- a/head/ObsoleteFiles.inc	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/ObsoleteFiles.inc	Tue Dec 06 20:26:16 2011 +0200
@@ -1,5 +1,5 @@
 #
-# $FreeBSD: head/ObsoleteFiles.inc 227214 2011-11-06 14:00:18Z antoine $
+# $FreeBSD: head/ObsoleteFiles.inc 227982 2011-11-25 19:29:21Z marius $
 #
 # This file lists old files (OLD_FILES), libraries (OLD_LIBS) and
 # directories (OLD_DIRS) which should get removed at an update. Recently
@@ -38,6 +38,19 @@
 #   xargs -n1 | sort | uniq -d;
 # done
 
+# 20111125: amd(4) removed
+OLD_FILES+=usr/share/man/man4/amd.4.gz
+# 20111125: libodialog removed
+OLD_FILES+=usr/lib/libodialog.a
+OLD_FILES+=usr/lib/libodialog.so
+OLD_LIBS+=usr/lib/libodialog.so.7
+OLD_FILES+=usr/lib/libodialog_p.a
+.if ${TARGET_ARCH} == "amd64" || ${TARGET_ARCH} == "powerpc64"
+OLD_FILES+=usr/lib32/libodialog.a
+OLD_FILES+=usr/lib32/libodialog.so
+OLD_LIBS+=usr/lib32/libodialog.so.7
+OLD_FILES+=usr/lib32/libodialog_p.a
+.endif
 # 20110930: sysinstall removed
 OLD_FILES+=usr/sbin/sysinstall
 OLD_FILES+=usr/share/man/man8/sysinstall.8.gz
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/UPDATING
--- a/head/UPDATING	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/UPDATING	Tue Dec 06 20:26:16 2011 +0200
@@ -22,6 +22,10 @@
 	machines to maximize performance.  (To disable malloc debugging, run
 	ln -s aj /etc/malloc.conf.)
 
+20111122:
+	The acpi_wmi(4) status device /dev/wmistat has been renamed to
+	/dev/wmistat0.
+
 20111108:
 	The option VFS_ALLOW_NONMPSAFE option has been added in order to
 	explicitely support non-MPSAFE filesystems.
@@ -1519,4 +1523,4 @@
 Contact Warner Losh if you have any questions about your use of
 this document.
 
-$FreeBSD: head/UPDATING 227333 2011-11-08 10:18:07Z attilio $
+$FreeBSD: head/UPDATING 228163 2011-11-30 20:08:30Z jh $
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/bin/sh/eval.c
--- a/head/bin/sh/eval.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/bin/sh/eval.c	Tue Dec 06 20:26:16 2011 +0200
@@ -36,7 +36,7 @@
 #endif
 #endif /* not lint */
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/bin/sh/eval.c 223282 2011-06-18 23:58:59Z jilles $");
+__FBSDID("$FreeBSD: head/bin/sh/eval.c 228015 2011-11-27 00:09:59Z jilles $");
 
 #include <paths.h>
 #include <signal.h>
@@ -89,7 +89,7 @@
 
 static void evalloop(union node *, int);
 static void evalfor(union node *, int);
-static void evalcase(union node *, int);
+static union node *evalcase(union node *, int);
 static void evalsubshell(union node *, int);
 static void evalredir(union node *, int);
 static void expredir(union node *);
@@ -256,7 +256,7 @@
 			evalfor(n, flags & ~EV_EXIT);
 			break;
 		case NCASE:
-			evalcase(n, flags);
+			next = evalcase(n, flags);
 			break;
 		case NDEFUN:
 			defun(n->narg.text, n->narg.next);
@@ -343,8 +343,6 @@
 	for (argp = n->nfor.args ; argp ; argp = argp->narg.next) {
 		oexitstatus = exitstatus;
 		expandarg(argp, &arglist, EXP_FULL | EXP_TILDE);
-		if (evalskip)
-			goto out;
 	}
 	*arglist.lastp = NULL;
 
@@ -364,13 +362,12 @@
 		}
 	}
 	loopnest--;
-out:
 	popstackmark(&smark);
 }
 
 
 
-static void
+static union node *
 evalcase(union node *n, int flags)
 {
 	union node *cp;
@@ -383,26 +380,24 @@
 	oexitstatus = exitstatus;
 	exitstatus = 0;
 	expandarg(n->ncase.expr, &arglist, EXP_TILDE);
-	for (cp = n->ncase.cases ; cp && evalskip == 0 ; cp = cp->nclist.next) {
+	for (cp = n->ncase.cases ; cp ; cp = cp->nclist.next) {
 		for (patp = cp->nclist.pattern ; patp ; patp = patp->narg.next) {
 			if (casematch(patp, arglist.list->text)) {
+				popstackmark(&smark);
 				while (cp->nclist.next &&
 				    cp->type == NCLISTFALLTHRU) {
-					if (evalskip != 0)
-						break;
 					evaltree(cp->nclist.body,
 					    flags & ~EV_EXIT);
+					if (evalskip != 0)
+						return (NULL);
 					cp = cp->nclist.next;
 				}
-				if (evalskip == 0) {
-					evaltree(cp->nclist.body, flags);
-				}
-				goto out;
+				return (cp->nclist.body);
 			}
 		}
 	}
-out:
 	popstackmark(&smark);
+	return (NULL);
 }
 
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/bin/test/test.c
--- a/head/bin/test/test.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/bin/test/test.c	Tue Dec 06 20:26:16 2011 +0200
@@ -15,7 +15,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/bin/test/test.c 226961 2011-10-31 08:59:17Z ed $");
+__FBSDID("$FreeBSD: head/bin/test/test.c 227984 2011-11-25 23:45:29Z jilles $");
 
 #include <sys/types.h>
 #include <sys/stat.h>
@@ -119,7 +119,7 @@
 };
 
 static struct t_op {
-	const char *op_text;
+	char op_text[4];
 	short op_num, op_type;
 } const ops [] = {
 	{"-r",	FILRD,	UNOP},
@@ -162,7 +162,7 @@
 	{"-o",	BOR,	BBINOP},
 	{"(",	LPAREN,	PAREN},
 	{")",	RPAREN,	PAREN},
-	{0,	0,	0}
+	{"",	0,	0}
 };
 
 static struct t_op const *t_wp_op;
@@ -427,7 +427,7 @@
 		t_wp_op = NULL;
 		return EOI;
 	}
-	while (op->op_text) {
+	while (*op->op_text) {
 		if (strcmp(s, op->op_text) == 0) {
 			if (((op->op_type == UNOP || op->op_type == BUNOP)
 						&& isunopoperand()) ||
@@ -456,7 +456,7 @@
 	if (nargc == 2)
 		return parenlevel == 1 && strcmp(s, ")") == 0;
 	t = *(t_wp + 2);
-	while (op->op_text) {
+	while (*op->op_text) {
 		if (strcmp(s, op->op_text) == 0)
 			return op->op_type == BINOP &&
 			    (parenlevel == 0 || t[0] != ')' || t[1] != '\0');
@@ -478,7 +478,7 @@
 		return parenlevel == 1 && strcmp(s, ")") == 0;
 	if (nargc != 3)
 		return 0;
-	while (op->op_text) {
+	while (*op->op_text) {
 		if (strcmp(s, op->op_text) == 0)
 			return op->op_type == BINOP;
 		op++;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/cddl/contrib/opensolaris/cmd/zdb/zdb.8
--- a/head/cddl/contrib/opensolaris/cmd/zdb/zdb.8	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/cddl/contrib/opensolaris/cmd/zdb/zdb.8	Tue Dec 06 20:26:16 2011 +0200
@@ -1,65 +1,79 @@
 '\" te
+.\" Copyright (c) 2011, Martin Matuska <mm at FreeBSD.org>.
+.\" All Rights Reserved.
+.\"
+.\" The contents of this file are subject to the terms of the
+.\" Common Development and Distribution License (the "License").
+.\" You may not use this file except in compliance with the License.
+.\"
+.\" You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
+.\" or http://www.opensolaris.org/os/licensing.
+.\" See the License for the specific language governing permissions
+.\" and limitations under the License.
+.\"
+.\" When distributing Covered Code, include this CDDL HEADER in each
+.\" file and include the License file at usr/src/OPENSOLARIS.LICENSE.
+.\" If applicable, add the following below this CDDL HEADER, with the
+.\" fields enclosed by brackets "[]" replaced with your own identifying
+.\" information: Portions Copyright [yyyy] [name of copyright owner]
+.\"
 .\" Copyright (c) 2004, Sun Microsystems, Inc. All Rights Reserved.
-.\" The contents of this file are subject to the terms of the Common Development and Distribution License (the "License").  You may not use this file except in compliance with the License.
-.\" You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE or http://www.opensolaris.org/os/licensing.  See the License for the specific language governing permissions and limitations under the License.
-.\" When distributing Covered Code, include this CDDL HEADER in each file and include the License file at usr/src/OPENSOLARIS.LICENSE.  If applicable, add the following below this CDDL HEADER, with the fields enclosed by brackets "[]" replaced with your own identifying information: Portions Copyright [yyyy] [name of copyright owner]
-.\" Portions Copyright 2011 Martin Matuska <mm at FreeBSD.org>
-.TH ZDB 8 "Oct 31, 2005"
-.SH NAME
-zdb \- ZFS debugger
-.SH SYNOPSIS
-.LP
-.nf
-\fBzdb\fR \fIpool\fR
-.fi
-
-.SH DESCRIPTION
-.sp
-.LP
-The \fBzdb\fR command is used by support engineers to diagnose failures and
-gather statistics. Since the \fBZFS\fR file system is always consistent on disk
-and is self-repairing, \fBzdb\fR should only be run under the direction by a
-support engineer.
-.sp
-.LP
-If no arguments are specified, \fBzdb\fR, performs basic consistency checks on
-the pool and associated datasets, and report any problems detected.
-.sp
-.LP
+.\"
+.\" $FreeBSD: head/cddl/contrib/opensolaris/cmd/zdb/zdb.8 228019 2011-11-27 11:44:20Z mm $
+.\"
+.Dd November 26, 2011
+.Dt ZDB 8
+.Os
+.Sh NAME
+.Nm zdb
+.Nd ZFS debugger
+.Sh SYNOPSIS
+.Nm
+.Ar pool
+.Sh DESCRIPTION
+The
+.Nm
+command is used by support engineers to diagnose failures and
+gather statistics. Since the
+.Tn ZFS
+file system is always consistent on disk and is self-repairing,
+.Nm
+should only be run under the direction by a support engineer.
+.Pp
+If no arguments are specified,
+.Nm
+performs basic consistency checks on the pool and associated datasets, and
+report any problems detected.
+.Nm
 Any options supported by this command are internal to Sun and subject to change
 at any time.
-.SH EXIT STATUS
-.sp
-.LP
+.Sh EXIT STATUS
 The following exit values are returned:
-.sp
-.ne 2
-.na
-\fB\fB0\fR\fR
-.ad
-.RS 5n
+.Bl -tag -offset 2n -width 2n
+.It 0
 The pool is consistent.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB1\fR\fR
-.ad
-.RS 5n
+.It 1
 An error was detected.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB2\fR\fR
-.ad
-.RS 5n
+.It 2
 Invalid command line options were specified.
-.RE
-
-.SH SEE ALSO
-.sp
-.LP
-zfs(8), zpool(8)
+.El
+.Sh SEE ALSO
+.Xr zfs 8 ,
+.Xr zpool 8
+.Sh AUTHORS
+This manual page is a
+.Xr mdoc 7
+reimplementation of the
+.Tn OpenSolaris
+manual page
+.Em zdb(1M) ,
+modified and customized for
+.Fx
+and licensed under the
+.Tn Common Development and Distribution License
+.Pq Tn CDDL .
+.Pp
+The
+.Xr mdoc 7
+implementation of this manual page was initially written by
+.An Martin Matuska Aq mm at FreeBSD.org .
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/cddl/contrib/opensolaris/cmd/zfs/zfs.8
--- a/head/cddl/contrib/opensolaris/cmd/zfs/zfs.8	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/cddl/contrib/opensolaris/cmd/zfs/zfs.8	Tue Dec 06 20:26:16 2011 +0200
@@ -1,561 +1,543 @@
 '\" te
-.\" Copyright (c) 2009 Sun Microsystems, Inc. All Rights Reserved.
-.\" The contents of this file are subject to the terms of the Common Development and Distribution License (the "License").  You may not use this file except in compliance with the License. You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE or http://www.opensolaris.org/os/licensing.
-.\"  See the License for the specific language governing permissions and limitations under the License. When distributing Covered Code, include this CDDL HEADER in each file and include the License file at usr/src/OPENSOLARIS.LICENSE.  If applicable, add the following below this CDDL HEADER, with
-.\" the fields enclosed by brackets "[]" replaced with your own identifying information: Portions Copyright [yyyy] [name of copyright owner]
-.\" The contents of this file are subject to the terms of the Common Development and Distribution License (the "License").  You may not use this file except in compliance with the License. You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE or http://www.opensolaris.org/os/licensing.
-.\"  See the License for the specific language governing permissions and limitations under the License. When distributing Covered Code, include this CDDL HEADER in each file and include the License file at usr/src/OPENSOLARIS.LICENSE.  If applicable, add the following below this CDDL HEADER, with
-.\" the fields enclosed by brackets "[]" replaced with your own identifying information: Portions Copyright [yyyy] [name of copyright owner]
+.\" Copyright (c) 2011, Martin Matuska <mm at FreeBSD.org>.
+.\" All Rights Reserved.
+.\"
+.\" The contents of this file are subject to the terms of the
+.\" Common Development and Distribution License (the "License").
+.\" You may not use this file except in compliance with the License.
+.\"
+.\" You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
+.\" or http://www.opensolaris.org/os/licensing.
+.\" See the License for the specific language governing permissions
+.\" and limitations under the License.
+.\"
+.\" When distributing Covered Code, include this CDDL HEADER in each
+.\" file and include the License file at usr/src/OPENSOLARIS.LICENSE.
+.\" If applicable, add the following below this CDDL HEADER, with the
+.\" fields enclosed by brackets "[]" replaced with your own identifying
+.\" information: Portions Copyright [yyyy] [name of copyright owner]
+.\"
+.\" Copyright (c) 2010, Sun Microsystems, Inc. All Rights Reserved.
 .\" Copyright 2011 Nexenta Systems, Inc.  All rights reserved.
-.\" Copyright 2011 by Delphix.  All rights reserved.
-.\" Portions Copyright 2011 Pawel Jakub Dawidek <pjd at FreeBSD.org>
-.\" Portions Copyright 2011 Martin Matuska <mm at FreeBSD.org>
-.TH ZFS 8 "September 24, 2009" FreeBSD
-.SH NAME
-zfs \- configures ZFS file systems
-.SH SYNOPSIS
-.LP
-.nf
-\fBzfs\fR [\fB-?\fR]
-.fi
-
-.LP
-.nf
-\fBzfs\fR \fBcreate\fR [\fB-p\fR] [\fB-o\fR \fIproperty\fR=\fIvalue\fR] ... \fIfilesystem\fR
-.fi
-
-.LP
-.nf
-\fBzfs\fR \fBcreate\fR [\fB-ps\fR] [\fB-b\fR \fIblocksize\fR] [\fB-o\fR \fIproperty\fR=\fIvalue\fR] ... \fB-V\fR \fIsize\fR \fIvolume\fR
-.fi
-
-.LP
-.nf
-\fBzfs\fR \fBdestroy\fR [\fB-rRf\fR] \fIfilesystem\fR|\fIvolume\fR
-.fi
-
-.LP
-.nf
-\fBzfs\fR \fBdestroy\fR [\fB-rRd\fR] \fIsnapshot\fR
-.fi
-
-.LP
-.nf
-\fBzfs\fR \fBsnapshot\fR [\fB-r\fR] [\fB-o\fR \fIproperty\fR=\fIvalue\fR]...
-      \fIfilesystem at snapname\fR|\fIvolume at snapname\fR
-.fi
-
-.LP
-.nf
-\fBzfs\fR \fBrollback\fR [\fB-rRf\fR] \fIsnapshot\fR
-.fi
-
-.LP
-.nf
-\fBzfs\fR \fBclone\fR [\fB-p\fR] [\fB-o\fR \fIproperty\fR=\fIvalue\fR] ... \fIsnapshot\fR \fIfilesystem\fR|\fIvolume\fR
-.fi
-
-.LP
-.nf
-\fBzfs\fR \fBpromote\fR \fIclone-filesystem\fR
-.fi
-
-.LP
-.nf
-\fBzfs\fR \fBrename\fR \fIfilesystem\fR|\fIvolume\fR|\fIsnapshot\fR
-     \fIfilesystem\fR|\fIvolume\fR|\fIsnapshot\fR
-.fi
-
-.LP
-.nf
-\fBzfs\fR \fBrename\fR [\fB-p\fR] \fIfilesystem\fR|\fIvolume\fR \fIfilesystem\fR|\fIvolume\fR
-.fi
-
-.LP
-.nf
-\fBzfs\fR \fBrename\fR \fB-r\fR \fIsnapshot\fR \fIsnapshot\fR
-.fi
-
-.LP
-.nf
-\fBzfs\fR \fBrename\fR \fB-u\fR [\fB-p\fR] \fIfilesystem\fR \fIfilesystem\fR
-.fi
-
-.LP
-.nf
-\fBzfs\fR \fBlist\fR [\fB-r\fR|\fB-d\fR \fIdepth\fR][\fB-H\fR][\fB-o\fR \fIproperty\fR[,...]] [\fB-t\fR \fItype\fR[,...]]
-     [\fB-s\fR \fIproperty\fR] ... [\fB-S\fR \fIproperty\fR] ... [\fIfilesystem\fR|\fIvolume\fR|\fIsnapshot\fR] ...
-.fi
-
-.LP
-.nf
-\fBzfs\fR \fBset\fR \fIproperty\fR=\fIvalue\fR \fIfilesystem\fR|\fIvolume\fR|\fIsnapshot\fR ...
-.fi
-
-.LP
-.nf
-\fBzfs\fR \fBget\fR [\fB-r\fR|\fB-d\fR \fIdepth\fR][\fB-Hp\fR][\fB-o\fR \fIfield\fR[,...]] [\fB-s\fR \fIsource\fR[,...]]
-     "\fIall\fR" | \fIproperty\fR[,...] \fIfilesystem\fR|\fIvolume\fR|\fIsnapshot\fR ...
-.fi
-
-.LP
-.nf
-\fBzfs\fR \fBinherit\fR [\fB-r\fR] \fIproperty\fR \fIfilesystem\fR|\fIvolume|snapshot\fR ...
-.fi
-
-.LP
-.nf
-\fBzfs\fR \fBupgrade\fR [\fB-v\fR]
-.fi
-
-.LP
-.nf
-\fBzfs\fR \fBupgrade\fR [\fB-r\fR] [\fB-V\fR \fIversion\fR] \fB-a\fR | \fIfilesystem\fR
-.fi
-
-.LP
-.nf
-\fBzfs\fR \fBuserspace\fR [\fB-niHp\fR] [\fB-o\fR \fIfield\fR[,...]] [\fB-sS\fR \fIfield\fR] ...
-     [\fB-t\fR \fItype\fR [,...]] \fIfilesystem\fR|\fIsnapshot\fR
-.fi
-
-.LP
-.nf
-\fBzfs\fR \fBgroupspace\fR [\fB-niHp\fR] [\fB-o\fR \fIfield\fR[,...]] [\fB-sS\fR \fIfield\fR] ...
-     [\fB-t\fR \fItype\fR [,...]] \fIfilesystem\fR|\fIsnapshot\fR
-.fi
-
-.LP
-.nf
-\fBzfs\fR \fBmount\fR
-.fi
-
-.LP
-.nf
-\fBzfs\fR \fBmount\fR [\fB-vO\fR] [\fB-o \fIoptions\fR\fR] \fB-a\fR | \fIfilesystem\fR
-.fi
-
-.LP
-.nf
-\fBzfs\fR \fBunmount\fR [\fB-f\fR] \fB-a\fR | \fIfilesystem\fR|\fImountpoint\fR
-.fi
-
-.LP
-.nf
-\fBzfs\fR \fBshare\fR \fB-a\fR | \fIfilesystem\fR
-.fi
-
-.LP
-.nf
-\fBzfs\fR \fBunshare\fR \fB-a\fR \fIfilesystem\fR|\fImountpoint\fR
-.fi
-
-.LP
-.nf
-\fBzfs\fR \fBsend\fR [\fB-vR\fR] [\fB-\fR[\fBiI\fR] \fIsnapshot\fR] \fIsnapshot\fR
-.fi
-
-.LP
-.nf
-\fBzfs\fR \fBreceive\fR [\fB-vnFu\fR] \fIfilesystem\fR|\fIvolume\fR|\fIsnapshot\fR
-.fi
-
-.LP
-.nf
-\fBzfs\fR \fBreceive\fR [\fB-vnFu\fR] \fB-d\fR \fIfilesystem\fR
-.fi
-
-.LP
-.nf
-\fBzfs\fR \fBallow\fR \fIfilesystem\fR|\fIvolume\fR
-.fi
-
-.LP
-.nf
-\fBzfs\fR \fBallow\fR [\fB-ldug\fR] "\fIeveryone\fR"|\fIuser\fR|\fIgroup\fR[,...] \fIperm\fR|\fI at setname\fR[,...]
-     \fIfilesystem\fR|\fIvolume\fR
-.fi
-
-.LP
-.nf
-\fBzfs\fR \fBallow\fR [\fB-ld\fR] \fB-e\fR \fIperm\fR|@\fIsetname\fR[,...] \fIfilesystem\fR|\fIvolume\fR
-.fi
-
-.LP
-.nf
-\fBzfs\fR \fBallow\fR \fB-c\fR \fIperm\fR|@\fIsetname\fR[,...] \fIfilesystem\fR|\fIvolume\fR
-.fi
-
-.LP
-.nf
-\fBzfs\fR \fBallow\fR \fB-s\fR @\fIsetname\fR \fIperm\fR|@\fIsetname\fR[,...] \fIfilesystem\fR|\fIvolume\fR
-.fi
-
-.LP
-.nf
-\fBzfs\fR \fBunallow\fR [\fB-rldug\fR] "\fIeveryone\fR"|\fIuser\fR|\fIgroup\fR[,...] [\fIperm\fR|@\fIsetname\fR[,... ]]
-     \fIfilesystem\fR|\fIvolume\fR
-.fi
-
-.LP
-.nf
-\fBzfs\fR \fBunallow\fR [\fB-rld\fR] \fB-e\fR [\fIperm\fR|@\fIsetname\fR[,... ]] \fIfilesystem\fR|\fIvolume\fR
-.fi
-
-.LP
-.nf
-\fBzfs\fR \fBunallow\fR [\fB-r\fR] \fB-c\fR [\fIperm\fR|@\fIsetname\fR[ ... ]] \fIfilesystem\fR|\fIvolume\fR
-.fi
-
-.LP
-.nf
-\fBzfs\fR \fBunallow\fR [\fB-r\fR] \fB-s\fR @\fIsetname\fR [\fIperm\fR|@\fIsetname\fR[,... ]] \fIfilesystem\fR|\fIvolume\fR
-.fi
-
-.LP
-.nf
-\fBzfs\fR \fBhold\fR [\fB-r\fR] \fItag\fR \fIsnapshot\fR...
-.fi
-
-.LP
-.nf
-\fBzfs\fR \fBholds\fR [\fB-r\fR] \fIsnapshot\fR...
-.fi
-
-.LP
-.nf
-\fBzfs\fR \fBrelease\fR [\fB-r\fR] \fItag\fR \fIsnapshot\fR...
-.fi
-
-.LP
-.nf
-\fBzfs\fR \fBjail\fR \fIjailid\fR \fIfilesystem\fR
-.fi
-
-.LP
-.nf
-\fBzfs\fR \fBunjail\fR \fIjailid\fR \fIfilesystem\fR
-.fi
-
-.SH DESCRIPTION
-.sp
-.LP
-The \fBzfs\fR command configures \fBZFS\fR datasets within a \fBZFS\fR storage
-pool, as described in \fBzpool\fR(8). A dataset is identified by a unique path
-within the \fBZFS\fR namespace. For example:
-.sp
-.in +2
-.nf
-pool/{filesystem,volume,snapshot}
-.fi
-.in -2
-.sp
-
-.sp
-.LP
-where the maximum length of a dataset name is \fBMAXNAMELEN\fR (256 bytes).
-.sp
-.LP
+.\" Copyright (c) 2011 by Delphix. All rights reserved.
+.\" Copyright (c) 2011, Pawel Jakub Dawidek <pjd at FreeBSD.org>
+.\"
+.\" $FreeBSD: head/cddl/contrib/opensolaris/cmd/zfs/zfs.8 228206 2011-12-02 19:56:46Z mm $
+.\"
+.Dd November 26, 2011
+.Dt ZFS 8
+.Os
+.Sh NAME
+.Nm zfs
+.Nd configures ZFS file systems
+.Sh SYNOPSIS
+.Nm
+.Op Fl \&?
+.Nm
+.Cm create
+.Op Fl p
+.Op Fl o Ar property Ns = Ns Ar value
+.Ar ... filesystem
+.Nm
+.Cm create
+.Op Fl ps
+.Op Fl b Ar blocksize
+.Op Fl o Ar property Ns = Ns Ar value
+.Ar ...
+.Fl V
+.Ar size volume
+.Nm
+.Cm destroy
+.Op Fl fnpRrv
+.Ar filesystem Ns | Ns Ar volume
+.Nm
+.Cm destroy
+.Op Fl dnpRrv
+.Sm off
+.Ar snapshot
+.Ns Op % Ns Ar snapname
+.Ns Op , Ns Ar ...
+.Sm on
+.Nm
+.Cm snapshot
+.Op Fl r
+.Op Fl o Ar property Ns = Ns Ar value
+.Ar ... filesystem at snapname Ns | Ns Ar volume at snapname
+.Nm
+.Cm rollback
+.Op Fl rRf
+.Ar snapshot
+.Nm
+.Cm clone
+.Op Fl p
+.Op Fl o Ar property Ns = Ns Ar value
+.Ar ... snapshot filesystem Ns | Ns Ar volume
+.Nm
+.Cm promote
+.Ar clone-filesystem
+.Nm
+.Cm rename
+.Ar filesystem Ns | Ns Ar volume Ns | Ns Ar snapshot
+.Ar filesystem Ns | Ns Ar volume Ns | Ns Ar snapshot
+.Nm
+.Cm rename
+.Fl p
+.Ar filesystem Ns | Ns Ar volume
+.Ar filesystem Ns | Ns Ar volume
+.Nm
+.Cm rename
+.Fl r
+.Ar snapshot snapshot
+.Nm
+.Cm rename
+.Fl u
+.Op Fl p
+.Ar filesystem filesystem
+.Nm
+.Cm list
+.Op Fl r Ns | Ns Fl d Ar depth
+.Op Fl H
+.Op Fl o Ar property Ns Op , Ns Ar ...
+.Op Fl t Ar type Ns Op , Ns Ar ...
+.Op Fl s Ar property
+.Ar ...
+.Op Fl S Ar property
+.Ar ...
+.Ar filesystem Ns | Ns Ar volume Ns | Ns Ar snapshot
+.Nm
+.Cm set
+.Ar property Ns = Ns Ar value
+.Ar filesystem Ns | Ns Ar volume Ns | Ns Ar snapshot
+.Nm
+.Cm get
+.Op Fl r Ns | Ns Fl d Ar depth
+.Op Fl Hp
+.Op Fl o Ar all | field Ns Op , Ns Ar ...
+.Op Fl s Ar source Ns Op , Ns Ar ...
+.Ar all | property Ns Op , Ns Ar ...
+.Ar filesystem Ns | Ns Ar volume Ns | Ns Ar snapshot
+.Nm
+.Cm inherit
+.Op Fl rS
+.Ar property
+.Ar filesystem Ns | Ns Ar volume Ns | Ns Ar snapshot
+.Nm
+.Cm upgrade
+.Op Fl v
+.Nm
+.Cm upgrade
+.Op Fl r
+.Op Fl V Ar version
+.Fl a | Ar filesystem
+.Nm
+.Cm userspace
+.Op Fl niHp
+.Op Fl o Ar field Ns Op , Ns Ar ...
+.Op Fl sS Ar field
+.Ar ...
+.Op Fl t Ar type Ns Op , Ns Ar ...
+.Ar filesystem Ns | Ns Ar snapshot
+.Nm
+.Cm groupspace
+.Op Fl niHp
+.Op Fl o Ar field Ns Op , Ns Ar ...
+.Op Fl sS Ar field
+.Ar ...
+.Op Fl t Ar type Ns Op , Ns Ar ...
+.Ar filesystem Ns | Ns Ar snapshot
+.Nm
+.Cm mount
+.Nm
+.Cm mount
+.Op Fl vO
+.Op Fl o Ar property Ns Op , Ns Ar ...
+.Fl a | Ar filesystem
+.Nm
+.Cm unmount
+.Op Fl f
+.Fl a | Ar filesystem Ns | Ns Ar mountpoint
+.Nm
+.Cm share
+.Fl a | Ar filesystem
+.Nm
+.Cm unshare
+.Fl a | Ar filesystem Ns | Ns Ar mountpoint
+.Nm
+.Cm send
+.Op Fl DnPpRrv
+.Op Fl i Ar snapshot | Fl I Ar snapshot
+.Ar snapshot
+.Nm
+.Cm receive
+.Op Fl vnFu
+.Ar filesystem Ns | Ns Ar volume Ns | Ns Ar snapshot
+.Nm
+.Cm receive
+.Op Fl vnFu
+.Op Fl d | e
+.Ar filesystem
+.Nm
+.Cm allow
+.Ar filesystem Ns | Ns Ar volume
+.Nm
+.Cm allow
+.Op Fl ldug
+.Cm everyone Ns | Ns Ar user Ns | Ns Ar group Ns Op , Ns Ar ...
+.Ar perm Ns | Ns Ar @setname Ns Op , Ns Ar ...
+.Ar filesystem Ns | Ns Ar volume
+.Nm
+.Cm allow
+.Op Fl ld
+.Fl e
+.Ar perm Ns | Ns Ar @setname Ns Op , Ns Ar ...
+.Ar filesystem Ns | Ns Ar volume
+.Nm
+.Cm allow
+.Fl c
+.Ar perm Ns | Ns Ar @setname Ns Op , Ns Ar ...
+.Ar filesystem Ns | Ns Ar volume
+.Nm
+.Cm allow
+.Fl s
+.Ar @setname
+.Ar perm Ns | Ns Ar @setname Ns Op , Ns Ar ...
+.Ar filesystem Ns | Ns Ar volume
+.Nm
+.Cm unallow
+.Op Fl rldug
+.Cm everyone Ns | Ns Ar user Ns | Ns Ar group Ns Op , Ns Ar ...
+.Op Ar perm Ns | Ns Ar @setname Ns Op , Ns Ar ...
+.Ar filesystem Ns | Ns Ar volume
+.Nm
+.Cm unallow
+.Op Fl rld
+.Fl e
+.Op Ar perm Ns | Ns Ar @setname Ns Op , Ns Ar ...
+.Ar filesystem Ns | Ns Ar volume
+.Nm
+.Cm unallow
+.Op Fl r
+.Fl c
+.Op Ar perm Ns | Ns Ar @setname Ns Op , Ns Ar ...
+.Ar filesystem Ns | Ns Ar volume
+.Nm
+.Cm unallow
+.Op Fl r
+.Fl s
+.Ar @setname
+.Ar perm Ns | Ns Ar @setname Ns Op , Ns Ar ...
+.Ar filesystem Ns | Ns Ar volume
+.Nm
+.Cm hold
+.Op Fl r
+.Ar tag snapshot ...
+.Nm
+.Cm holds
+.Op Fl r
+.Ar snapshot ...
+.Nm
+.Cm release
+.Op Fl r
+.Ar tag snapshot ...
+.Nm
+.Cm diff
+.Op Fl FHt
+.Ar snapshot
+.Op Ar snapshot Ns | Ns Ar filesystem
+.Nm
+.Cm jail
+.Ar jailid filesystem
+.Nm
+.Cm unjail
+.Ar jailid filesystem
+.Sh DESCRIPTION
+The
+.Nm
+command configures
+.Tn ZFS
+datasets within a
+.Tn ZFS
+storage pool, as described in
+.Xr zpool 8 .
+A dataset is identified by a unique path within the
+.Tn ZFS
+namespace. For example:
+.Bd -ragged -offset 4n
+.No pool/ Ns Brq filesystem,volume,snapshot
+.Ed
+.Pp
+where the maximum length of a dataset name is
+.Dv MAXNAMELEN
+(256 bytes).
+.Pp
 A dataset can be one of the following:
-.sp
-.ne 2
-.na
-\fB\fIfile system\fR\fR
-.ad
-.sp .6
-.RS 4n
-A \fBZFS\fR dataset of type \fBfilesystem\fR can be mounted within the standard
-system namespace and behaves like other file systems. While \fBZFS\fR file
-systems are designed to be \fBPOSIX\fR compliant, known issues exist that
-prevent compliance in some cases. Applications that depend on standards
-conformance might fail due to nonstandard behavior when checking file system
-free space.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fIvolume\fR\fR
-.ad
-.sp .6
-.RS 4n
+.Bl -hang -width 12n
+.It Sy file system
+A
+.Tn ZFS
+dataset of type
+.Em filesystem
+can be mounted within the standard system namespace and behaves like other file
+systems. While
+.Tn ZFS
+file systems are designed to be
+.Tn POSIX
+compliant, known issues exist that prevent compliance in some cases.
+Applications that depend on standards conformance might fail due to nonstandard
+behavior when checking file system free space.
+.It Sy volume
 A logical volume exported as a raw or block device. This type of dataset should
 only be used under special circumstances. File systems are typically used in
 most environments.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fIsnapshot\fR\fR
-.ad
-.sp .6
-.RS 4n
+.It Sy snapshot
 A read-only version of a file system or volume at a given point in time. It is
-specified as \fIfilesystem at name\fR or \fIvolume at name\fR.
-.RE
-
-.SS "ZFS File System Hierarchy"
-.sp
-.LP
-A \fBZFS\fR storage pool is a logical collection of devices that provide space
-for datasets. A storage pool is also the root of the \fBZFS\fR file system
-hierarchy.
-.sp
-.LP
+specified as
+.Em filesystem at name
+or
+.Em volume at name .
+.El
+.Ss ZFS File System Hierarchy
+A
+.Tn ZFS
+storage pool is a logical collection of devices that provide space for
+datasets. A storage pool is also the root of the
+.Tn ZFS
+file system hierarchy.
+.Pp
 The root of the pool can be accessed as a file system, such as mounting and
 unmounting, taking snapshots, and setting properties. The physical storage
-characteristics, however, are managed by the \fBzpool\fR(8) command.
-.sp
-.LP
-See \fBzpool\fR(8) for more information on creating and administering pools.
-.SS "Snapshots"
-.sp
-.LP
+characteristics, however, are managed by the
+.Xr zpool 8
+command.
+.Pp
+See
+.Xr zpool 8
+for more information on creating and administering pools.
+.Ss Snapshots
 A snapshot is a read-only copy of a file system or volume. Snapshots can be
 created extremely quickly, and initially consume no additional space within the
 pool. As data within the active dataset changes, the snapshot consumes more
 data than would otherwise be shared with the active dataset.
-.sp
-.LP
+.Pp
 Snapshots can have arbitrary names. Snapshots of volumes can be cloned or
 rolled back, but cannot be accessed independently.
-.sp
-.LP
-File system snapshots can be accessed under the \fB\&.zfs/snapshot\fR directory
-in the root of the file system. Snapshots are automatically mounted on demand
-and may be unmounted at regular intervals. The visibility of the \fB\&.zfs\fR
-directory can be controlled by the \fBsnapdir\fR property.
-.SS "Clones"
-.sp
-.LP
+.Pp
+File system snapshots can be accessed under the
+.Pa \&.zfs/snapshot
+directory in the root of the file system. Snapshots are automatically mounted
+on demand and may be unmounted at regular intervals. The visibility of the
+.Pa \&.zfs
+directory can be controlled by the
+.Sy snapdir
+property.
+.Ss Clones
 A clone is a writable volume or file system whose initial contents are the same
 as another dataset. As with snapshots, creating a clone is nearly
 instantaneous, and initially consumes no additional space.
-.sp
-.LP
+.Pp
 Clones can only be created from a snapshot. When a snapshot is cloned, it
 creates an implicit dependency between the parent and child. Even though the
 clone is created somewhere else in the dataset hierarchy, the original snapshot
-cannot be destroyed as long as a clone exists. The \fBorigin\fR property
-exposes this dependency, and the \fBdestroy\fR command lists any such
-dependencies, if they exist.
-.sp
-.LP
+cannot be destroyed as long as a clone exists. The
+.Sy origin
+property exposes this dependency, and the
+.Cm destroy
+command lists any such dependencies, if they exist.
+.Pp
 The clone parent-child dependency relationship can be reversed by using the
-\fBpromote\fR subcommand. This causes the "origin" file system to become a
-clone of the specified file system, which makes it possible to destroy the file
-system that the clone was created from.
-.SS "Mount Points"
-.sp
-.LP
-Creating a \fBZFS\fR file system is a simple operation, so the number of file
-systems per system is likely to be numerous. To cope with this, \fBZFS\fR
+.Cm promote
+subcommand. This causes the "origin" file system to become a clone of the
+specified file system, which makes it possible to destroy the file system that
+the clone was created from.
+.Ss Mount Points
+Creating a
+.Tn ZFS
+file system is a simple operation, so the number of file systems per system is
+likely to be numerous. To cope with this,
+.Tn ZFS
 automatically manages mounting and unmounting file systems without the need to
-edit the \fB/etc/fstab\fR file. All automatically managed file systems are
-mounted by \fBZFS\fR at boot time.
-.sp
-.LP
-By default, file systems are mounted under \fB/\fIpath\fR\fR, where \fIpath\fR
-is the name of the file system in the \fBZFS\fR namespace. Directories are
-created and destroyed as needed.
-.sp
-.LP
-A file system can also have a mount point set in the \fBmountpoint\fR property.
-This directory is created as needed, and \fBZFS\fR automatically mounts the
-file system when the \fBzfs mount -a\fR command is invoked (without editing
-\fB/etc/fstab\fR). The \fBmountpoint\fR property can be inherited, so if
-\fBpool/home\fR has a mount point of \fB/export/stuff\fR, then
-\fBpool/home/user\fR automatically inherits a mount point of
-\fB/export/stuff/user\fR.
-.sp
-.LP
-A file system \fBmountpoint\fR property of \fBnone\fR prevents the file system
-from being mounted.
-.sp
-.LP
-If needed, \fBZFS\fR file systems can also be managed with traditional tools
-(\fBmount\fR, \fBumount\fR, \fB/etc/fstab\fR). If a file system's mount point
-is set to \fBlegacy\fR, \fBZFS\fR makes no attempt to manage the file system,
-and the administrator is responsible for mounting and unmounting the file
-system.
-.SS "Jails"
-.sp
-.LP
-A \fBZFS\fR dataset can be attached to a jail by using the \fBzfs\fR
-\fBjail\fR subcommand. You cannot attach a dataset to one jail and the
-children of the same dataset to another jails. To allow managment of the
-dataset from within a jail, the "\fBjailed\fR" property has to be set.
-The \fBquota\fR property cannot be changed from within a jail.
-.sp
-.LP
-A \fBZFS\fR dataset can be detached from a jail using the \fBzfs\fR
-\fBunjail\fR subcommand.
-.sp
-.LP
-After a dataset is attached to a jail and the \fBjailed\fR property is set,
-a jailed file system cannot be mounted outside the jail, since the jail
-administrator might have set the mount point to an unacceptable value.
-.SS "Native Properties"
-.sp
-.LP
+edit the
+.Pa /etc/fstab
+file. All automatically managed file systems are mounted by
+.Tn ZFS
+at boot time.
+.Pp
+By default, file systems are mounted under
+.Pa /path ,
+where
+.Ar path
+is the name of the file system in the
+.Tn ZFS
+namespace. Directories are created and destroyed as needed.
+.Pp
+A file system can also have a mount point set in the
+.Sy mountpoint
+property. This directory is created as needed, and
+.Tn ZFS
+automatically mounts the file system when the
+.Qq Nm Cm mount Fl a
+command is invoked (without editing
+.Pa /etc/fstab Ns ).
+The
+.Sy mountpoint
+property can be inherited, so if
+.Em pool/home
+has a mount point of
+.Pa /home ,
+then
+.Em pool/home/user
+automatically inherits a mount point of
+.Pa /home/user .
+.Pp
+A file system
+.Sy mountpoint
+property of
+.Cm none
+prevents the file system from being mounted.
+.Pp
+If needed,
+.Tn ZFS
+file systems can also be managed with traditional tools
+.Pq Xr mount 8 , Xr umount 8 , Xr fstab 5 .
+If a file system's mount point is set to
+.Cm legacy ,
+.Tn ZFS
+makes no attempt to manage the file system, and the administrator is
+responsible for mounting and unmounting the file system.
+.Ss Jails
+.No A Tn ZFS
+dataset can be attached to a jail by using the
+.Qq Nm Cm jail
+subcommand. You cannot attach a dataset to one jail and the children of the
+same dataset to another jails. To allow managment of the dataset from within
+a jail, the
+.Sy jailed
+property has to be set. The
+.Sy quota
+property cannot be changed from within a jail.
+.Pp
+.No A Tn ZFS
+dataset can be detached from a jail using the
+.Qq Nm Cm unjail
+subcommand.
+.Pp
+After a dataset is attached to a jail and the jailed property is set, a jailed
+file system cannot be mounted outside the jail, since the jail administrator
+might have set the mount point to an unacceptable value.
+.Ss Deduplication
+Deduplication is the process for removing redundant data at the block-level,
+reducing the total amount of data stored. If a file system has the
+.Cm dedup
+property enabled, duplicate data blocks are removed synchronously. The result
+is that only unique data is stored and common components are shared among
+files.
+.Ss Native Properties
 Properties are divided into two types, native properties and user-defined (or
 "user") properties. Native properties either export internal statistics or
-control \fBZFS\fR behavior. In addition, native properties are either editable
-or read-only. User properties have no effect on \fBZFS\fR behavior, but you can
-use them to annotate datasets in a way that is meaningful in your environment.
-For more information about user properties, see the "User Properties" section,
-below.
-.sp
-.LP
+control
+.Tn ZFS
+behavior. In addition, native properties are either editable or read-only. User
+properties have no effect on
+.Tn ZFS
+behavior, but you can use them to annotate datasets in a way that is meaningful
+in your environment. For more information about user properties, see the
+.Qq Sx User Properties
+section, below.
+.Pp
 Every dataset has a set of properties that export statistics about the dataset
 as well as control various behaviors. Properties are inherited from the parent
 unless overridden by the child. Some properties apply only to certain types of
 datasets (file systems, volumes, or snapshots).
-.sp
-.LP
+.Pp
 The values of numeric properties can be specified using human-readable suffixes
-(for example, \fBk\fR, \fBKB\fR, \fBM\fR, \fBGb\fR, and so forth, up to \fBZ\fR
+(for example,
+.Sy k , KB , M , Gb ,
+and so forth, up to
+.Sy Z
 for zettabyte). The following are all valid (and equal) specifications:
-.sp
-.in +2
-.nf
+.Bd -ragged -offset 4n
 1536M, 1.5g, 1.50GB
-.fi
-.in -2
-.sp
-
-.sp
-.LP
+.Ed
+.Pp
 The values of non-numeric properties are case sensitive and must be lowercase,
-except for \fBmountpoint\fR, \fBsharenfs\fR, and \fBsharesmb\fR.
-.sp
-.LP
+except for
+.Sy mountpoint , sharenfs , No and Sy sharesmb .
+.Pp
 The following native properties consist of read-only statistics about the
 dataset. These properties can be neither set, nor inherited. Native properties
 apply to all dataset types unless otherwise noted.
-.sp
-.ne 2
-.na
-\fB\fBavailable\fR\fR
-.ad
-.sp .6
-.RS 4n
+.Bl -tag -width 2n
+.It Sy available
 The amount of space available to the dataset and all its children, assuming
 that there is no other activity in the pool. Because space is shared within a
 pool, availability can be limited by any number of factors, including physical
 pool size, quotas, reservations, or other datasets within the pool.
-.sp
+.Pp
 This property can also be referred to by its shortened column name,
-\fBavail\fR.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBcompressratio\fR\fR
-.ad
-.sp .6
-.RS 4n
-For non-snapshots, the compression ratio achieved for the \fBused\fR
-space of this dataset, expressed as a multiplier.  The \fBused\fR
+.Sy avail .
+.It Sy compressratio
+For non-snapshots, the compression ratio achieved for the
+.Sy used
+space of this dataset, expressed as a multiplier.  The
+.Sy used
 property includes descendant datasets, and, for clones, does not include
 the space shared with the origin snapshot.  For snapshots, the
-\fBcompressratio\fR is the same as the \fBrefcompressratio\fR property.
-Compression can be turned on by running: \fBzfs set compression=on
-\fIdataset\fR\fR. The default value is \fBoff\fR.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBcreation\fR\fR
-.ad
-.sp .6
-.RS 4n
+.Sy compressratio
+is the same as the
+.Sy refcompressratio
+property. Compression can be turned on by running:
+.Qq Nm Cm set compression=on Ar dataset
+The default value is
+.Cm off .
+.It Sy creation
 The time this dataset was created.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBdefer_destroy\fR\fR
-.ad
-.sp .6
-.RS 4n
-This property is \fBon\fR if the snapshot has been marked for deferred destroy
-by using the \fBzfs destroy\fR \fB-d\fR command. Otherwise, the property is
-\fBoff\fR.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBmounted\fR\fR
-.ad
-.sp .6
-.RS 4n
+.It Sy clones
+For snapshots, this property is a comma-separated list of filesystems or
+volumes which are clones of this snapshot.  The clones'
+.Sy origin
+property is this snapshot.  If the
+.Sy clones
+property is not empty, then this snapshot can not be destroyed (even with the
+.Fl r
+or
+.Fl f
+options).
+.It Sy defer_destroy
+This property is
+.Cm on
+if the snapshot has been marked for deferred destroy by using the
+.Qq Nm Cm destroy -d
+command. Otherwise, the property is
+.Cm off .
+.It Sy mounted
 For file systems, indicates whether the file system is currently mounted. This
-property can be either \fByes\fR or \fBno\fR.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBorigin\fR\fR
-.ad
-.sp .6
-.RS 4n
+property can be either
+.Cm yes
+or
+.Cm no .
+.It Sy origin
 For cloned file systems or volumes, the snapshot from which the clone was
-created. The origin cannot be destroyed (even with the \fB-r\fR or \fB-f\fR
-options) so long as a clone exists.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBreferenced\fR\fR
-.ad
-.sp .6
-.RS 4n
+created. See also the
+.Sy clones
+property.
+.It Sy referenced
 The amount of data that is accessible by this dataset, which may or may not be
 shared with other datasets in the pool. When a snapshot or clone is created, it
 initially references the same amount of space as the file system or snapshot it
 was created from, since its contents are identical.
-.sp
+.Pp
 This property can also be referred to by its shortened column name,
-\fBrefer\fR.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBrefcompressratio\fR\fR
-.ad
-.sp .6
-.RS 4n
-The compression ratio achieved for the \fBreferenced\fR space of this
-dataset, expressed as a multiplier.  See also the \fBcompressratio\fR
+.Sy refer .
+.It Sy refcompressratio
+The compression ratio achieved for the
+.Sy referenced
+space of this dataset, expressed as a multiplier.  See also the
+.Sy compressratio
 property.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBtype\fR\fR
-.ad
-.sp .6
-.RS 4n
-The type of dataset: \fBfilesystem\fR, \fBvolume\fR, or \fBsnapshot\fR.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBused\fR\fR
-.ad
-.sp .6
-.RS 4n
+.It Sy type
+The type of dataset:
+.Sy filesystem , volume , No or Sy snapshot .
+.It Sy used
 The amount of space consumed by this dataset and all its descendents. This is
 the value that is checked against this dataset's quota and reservation. The
 space used does not include this dataset's reservation, but does take into
@@ -563,673 +545,629 @@
 dataset consumes from its parent, as well as the amount of space that are freed
 if this dataset is recursively destroyed, is the greater of its space used and
 its reservation.
-.sp
-When snapshots (see the "Snapshots" section) are created, their space is
+.Pp
+When snapshots (see the
+.Qq Sx Snapshots
+section) are created, their space is
 initially shared between the snapshot and the file system, and possibly with
 previous snapshots. As the file system changes, space that was previously
 shared becomes unique to the snapshot, and counted in the snapshot's space
 used. Additionally, deleting snapshots can increase the amount of space unique
 to (and used by) other snapshots.
-.sp
+.Pp
 The amount of space used, available, or referenced does not take into account
 pending changes. Pending changes are generally accounted for within a few
-seconds. Committing a change to a disk using \fBfsync\fR(2) or \fBO_SYNC\fR
+seconds. Committing a change to a disk using
+.Xr fsync 2
+or
+.Sy O_SYNC
 does not necessarily guarantee that the space usage information is updated
 immediately.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBusedby*\fR\fR
-.ad
-.sp .6
-.RS 4n
-The \fBusedby*\fR properties decompose the \fBused\fR properties into the
-various reasons that space is used. Specifically, \fBused\fR =
-\fBusedbychildren\fR + \fBusedbydataset\fR + \fBusedbyrefreservation\fR +,
-\fBusedbysnapshots\fR. These properties are only available for datasets created
-on \fBzpool\fR "version 13" pools.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBusedbychildren\fR\fR
-.ad
-.sp .6
-.RS 4n
+.It Sy usedby*
+The
+.Sy usedby*
+properties decompose the
+.Sy used
+properties into the various reasons that space is used. Specifically,
+.Sy used No =
+.Sy usedbysnapshots + usedbydataset + usedbychildren + usedbyrefreservation .
+These properties are only available for datasets created
+with
+.Tn ZFS
+pool version 13 pools and higher.
+.It Sy usedbysnapshots
+The amount of space consumed by snapshots of this dataset. In particular, it is
+the amount of space that would be freed if all of this dataset's snapshots were
+destroyed. Note that this is not simply the sum of the snapshots'
+.Sy used
+properties because space can be shared by multiple snapshots.
+.It Sy usedbydataset
+The amount of space used by this dataset itself, which would be freed if the
+dataset were destroyed (after first removing any
+.Sy refreservation
+and destroying any necessary snapshots or descendents).
+.It Sy usedbychildren
 The amount of space used by children of this dataset, which would be freed if
 all the dataset's children were destroyed.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBusedbydataset\fR\fR
-.ad
-.sp .6
-.RS 4n
-The amount of space used by this dataset itself, which would be freed if the
-dataset were destroyed (after first removing any \fBrefreservation\fR and
-destroying any necessary snapshots or descendents).
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBusedbyrefreservation\fR\fR
-.ad
-.sp .6
-.RS 4n
-The amount of space used by a \fBrefreservation\fR set on this dataset, which
-would be freed if the \fBrefreservation\fR was removed.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBusedbysnapshots\fR\fR
-.ad
-.sp .6
-.RS 4n
-The amount of space consumed by snapshots of this dataset. In particular, it is
-the amount of space that would be freed if all of this dataset's snapshots were
-destroyed. Note that this is not simply the sum of the snapshots' \fBused\fR
-properties because space can be shared by multiple snapshots.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBuserused@\fR\fIuser\fR\fR
-.ad
-.sp .6
-.RS 4n
+.It Sy usedbyrefreservation
+The amount of space used by a
+.Sy refreservation
+set on this dataset, which would be freed if the
+.Sy refreservation
+was removed.
+.It Sy userused@ Ns Ar user
 The amount of space consumed by the specified user in this dataset. Space is
-charged to the owner of each file, as displayed by \fBls\fR \fB-l\fR. The
-amount of space charged is displayed by \fBdu\fR and \fBls\fR \fB-s\fR. See the
-\fBzfs userspace\fR subcommand for more information.
-.sp
+charged to the owner of each file, as displayed by
+.Qq Nm ls Fl l .
+The amount of space charged is displayed by
+.Qq Nm du
+and
+.Qq Nm ls Fl s .
+See the
+.Qq Nm Cm userspace
+subcommand for more information.
+.Pp
 Unprivileged users can access only their own space usage. The root user, or a
-user who has been granted the \fBuserused\fR privilege with \fBzfs allow\fR,
+user who has been granted the
+.Sy userused
+privilege with
+.Qq Nm Cm allow ,
 can access everyone's usage.
-.sp
-The \fBuserused@\fR... properties are not displayed by \fBzfs get all\fR. The
-user's name must be appended after the \fB@\fR symbol, using one of the
-following forms:
-.RS +4
-.TP
-.ie t \(bu
-.el o
-\fIPOSIX name\fR (for example, \fBjoe\fR)
-.RE
-.RS +4
-.TP
-.ie t \(bu
-.el o
-\fIPOSIX numeric ID\fR (for example, \fB789\fR)
-.RE
-.RS +4
-.TP
-.ie t \(bu
-.el o
-\fISID name\fR (for example, \fBjoe.smith at mydomain\fR)
-.RE
-.RS +4
-.TP
-.ie t \(bu
-.el o
-\fISID numeric ID\fR (for example, \fBS-1-123-456-789\fR)
-.RE
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBuserrefs\fR\fR
-.ad
-.sp .6
-.RS 4n
+.Pp
+The 
+.Sy userused@ Ns ...
+properties are not displayed by
+.Qq Nm Cm get all .
+The user's name must be appended after the
+.Sy @
+symbol, using one of the following forms:
+.Bl -bullet -offset 2n
+.It
+POSIX name (for example,
+.Em joe Ns )
+.It
+POSIX numeric ID (for example,
+.Em 1001 Ns )
+.El
+.It Sy userrefs
 This property is set to the number of user holds on this snapshot. User holds
-are set by using the \fBzfs hold\fR command.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBgroupused@\fR\fIgroup\fR\fR
-.ad
-.sp .6
-.RS 4n
+are set by using the
+.Qq Nm Cm hold
+command.
+.It Sy groupused@ Ns Ar group
 The amount of space consumed by the specified group in this dataset. Space is
-charged to the group of each file, as displayed by \fBls\fR \fB-l\fR. See the
-\fBuserused@\fR\fIuser\fR property for more information.
-.sp
+charged to the group of each file, as displayed by
+.Nm ls Fl l .
+See the
+.Sy userused@ Ns Ar user
+property for more information.
+.Pp
 Unprivileged users can only access their own groups' space usage. The root
-user, or a user who has been granted the \fBgroupused\fR privilege with \fBzfs
-allow\fR, can access all groups' usage.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBvolblocksize\fR=\fIblocksize\fR\fR
-.ad
-.sp .6
-.RS 4n
-For volumes, specifies the block size of the volume. The \fBblocksize\fR cannot
-be changed once the volume has been written, so it should be set at volume
-creation time. The default \fBblocksize\fR for volumes is 8 Kbytes. Any power
-of 2 from 512 bytes to 128 Kbytes is valid.
-.sp
+user, or a user who has been granted the
+.Sy groupused
+privilege with
+.Qq Nm Cm allow ,
+can access all groups' usage.
+.It Sy volblocksize Ns = Ns Ar blocksize
+For volumes, specifies the block size of the volume. The
+.Ar blocksize
+cannot be changed once the volume has been written, so it should be set at
+volume creation time. The default
+.Ar blocksize
+for volumes is 8 Kbytes. Any
+power of 2 from 512 bytes to 128 Kbytes is valid.
+.Pp
 This property can also be referred to by its shortened column name,
-\fBvolblock\fR.
-.RE
-
-.sp
-.LP
+.Sy volblock .
+.It Sy written
+The amount of
+.Sy referenced
+space written to this dataset since the previous snapshot.
+.It Sy written@ Ns Ar snapshot
+The amount of
+.Sy referenced
+space written to this dataset since the specified snapshot.  This is the space
+that is referenced by this dataset but was not referenced by the specified
+snapshot.
+.Pp
+The
+.Ar snapshot
+may be specified as a short snapshot name (just the part after the
+.Sy @ Ns ),
+in which case it will be interpreted as a snapshot in the same filesystem as
+this dataset. The
+.Ar snapshot
+may be a full snapshot name
+.Pq Em filesystem at snapshot ,
+which for clones may be a snapshot in the origin's filesystem (or the origin of
+the origin's filesystem, etc).
+.El
+.Pp
 The following native properties can be used to change the behavior of a
-\fBZFS\fR dataset.
-.sp
-.ne 2
-.na
-\fB\fBaclinherit\fR=\fBdiscard\fR | \fBnoallow\fR | \fBrestricted\fR |
-\fBpassthrough\fR | \fBpassthrough-x\fR\fR
-.ad
-.sp .6
-.RS 4n
-Controls how \fBACL\fR entries are inherited when files and directories are
-created. A file system with an \fBaclinherit\fR property of \fBdiscard\fR does
-not inherit any \fBACL\fR entries. A file system with an \fBaclinherit\fR
-property value of \fBnoallow\fR only inherits inheritable \fBACL\fR entries
-that specify "deny" permissions. The property value \fBrestricted\fR (the
-default) removes the \fBwrite_acl\fR and \fBwrite_owner\fR permissions when the
-\fBACL\fR entry is inherited. A file system with an \fBaclinherit\fR property
-value of \fBpassthrough\fR inherits all inheritable \fBACL\fR entries without
-any modifications made to the \fBACL\fR entries when they are inherited. A file
-system with an \fBaclinherit\fR property value of \fBpassthrough-x\fR has the
-same meaning as \fBpassthrough\fR, except that the \fBowner@\fR, \fBgroup@\fR,
-and \fBeveryone@\fR \fBACE\fRs inherit the execute permission only if the file
-creation mode also requests the execute bit.
-.sp
-When the property value is set to \fBpassthrough\fR, files are created with a
-mode determined by the inheritable \fBACE\fRs. If no inheritable \fBACE\fRs
+.Tn ZFS
+dataset.
+.Bl -tag -width 2n
+.It Xo
+.Sy aclinherit Ns = Ns Cm discard |
+.Cm noallow |
+.Cm restricted |
+.Cm passthrough |
+.Cm passthrough-x
+.Xc
+Controls how
+.Tn ACL
+entries are inherited when files and directories are created. A file system
+with an
+.Sy aclinherit
+property of
+.Cm discard
+does not inherit any
+.Tn ACL
+entries. A file system with an
+.Sy aclinherit
+property value of
+.Cm noallow
+only inherits inheritable
+.Tn ACL
+entries that specify "deny" permissions. The property value
+.Cm restricted
+(the default) removes the
+.Em write_acl
+and
+.Em write_owner
+permissions when the
+.Tn ACL
+entry is inherited. A file system with an
+.Sy aclinherit
+property value of
+.Cm passthrough
+inherits all inheritable
+.Tn ACL
+entries without any modifications made to the
+.Tn ACL
+entries when they are inherited. A file system with an
+.Sy aclinherit
+property value of
+.Cm passthrough-x
+has the same meaning as
+.Cm passthrough ,
+except that the
+.Em owner@ , group@ , No and Em everyone@ Tn ACE Ns s
+inherit the execute permission only if the file creation mode also requests the
+execute bit.
+.Pp
+When the property value is set to
+.Cm passthrough ,
+files are created with a mode determined by the inheritable
+.Tn ACE Ns s.
+If no inheritable
+.Tn ACE Ns s
 exist that affect the mode, then the mode is set in accordance to the requested
 mode from the application.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBaclmode\fR=\fBdiscard\fR | \fBgroupmask\fR | \fBpassthrough\fR\fR
-.ad
-.sp .6
-.RS 4n
-Controls how an \fBACL\fR is modified during \fBchmod\fR(2). A file system with
-an \fBaclmode\fR property of \fBdiscard\fR (the default) deletes all \fBACL\fR
-entries that do not represent the mode of the file. An \fBaclmode\fR property
-of \fBgroupmask\fR reduces permissions granted in all \fBALLOW\fR entries found
-in the \fBACL\fR such that they are no greater than the group permissions
-specified by \fBchmod\fR.  A file system with an \fBaclmode\fR property of
-\fBpassthrough\fR indicates that no changes are made to the \fBACL\fR other
-than creating or updating the necessary \fBACL\fR entries to
-represent the new mode of the file or directory.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBatime\fR=\fBon\fR | \fBoff\fR\fR
-.ad
-.sp .6
-.RS 4n
+.It Sy aclmode Ns = Ns Cm discard | groupmask | passthrough
+Controls how an
+.Tn ACL
+is modified during
+.Xr chmod 2 .
+A file system with an
+.Sy aclmode
+property of
+.Cm discard
+(the default) deletes all
+.Tn ACL
+entries that do not represent the mode of the file. An
+.Sy aclmode
+property of
+.Cm groupmask
+reduces permissions granted in all
+.Em ALLOW
+entries found in the
+.Tn ACL
+such that they are no greater than the group permissions specified by
+.Xr chmod 2 .
+A file system with an
+.Sy aclmode
+property of
+.Cm passthrough
+indicates that no changes are made to the
+.Tn ACL
+other than creating or updating the necessary
+.Tn ACL
+entries to represent the new mode of the file or directory.
+.It Sy atime Ns = Ns Cm on | off
 Controls whether the access time for files is updated when they are read.
 Turning this property off avoids producing write traffic when reading files and
 can result in significant performance gains, though it might confuse mailers
-and other similar utilities. The default value is \fBon\fR.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBcanmount\fR=\fBon\fR | \fBoff\fR | \fBnoauto\fR\fR
-.ad
-.sp .6
-.RS 4n
-If this property is set to \fBoff\fR, the file system cannot be mounted, and is
-ignored by \fBzfs mount -a\fR. Setting this property to \fBoff\fR is similar to
-setting the \fBmountpoint\fR property to \fBnone\fR, except that the dataset
-still has a normal \fBmountpoint\fR property, which can be inherited. Setting
-this property to \fBoff\fR allows datasets to be used solely as a mechanism to
-inherit properties. One example of setting \fBcanmount=\fR\fBoff\fR is to have
-two datasets with the same \fBmountpoint\fR, so that the children of both
-datasets appear in the same directory, but might have different inherited
-characteristics.
-.sp
-When the \fBnoauto\fR option is set, a dataset can only be mounted and
-unmounted explicitly. The dataset is not mounted automatically when the dataset
-is created or imported, nor is it mounted by the \fBzfs mount -a\fR command or
-unmounted by the \fBzfs unmount -a\fR command.
-.sp
+and other similar utilities. The default value is
+.Cm on .
+.It Sy canmount Ns = Ns Cm on | off | noauto
+If this property is set to
+.Cm off ,
+the file system cannot be mounted, and is ignored by
+.Qq Nm Cm mount Fl a .
+Setting this property to
+.Cm off
+is similar to setting the
+.Sy mountpoint
+property to
+.Cm none ,
+except that the dataset still has a normal
+.Sy mountpoint
+property, which can be inherited. Setting this property to
+.Cm off
+allows datasets to be used solely as a mechanism to inherit properties. One
+example of setting
+.Sy canmount Ns = Ns Cm off
+is to have two datasets with the same
+.Sy mountpoint ,
+so that the children of both datasets appear in the same directory, but might
+have different inherited characteristics.
+.Pp
+When the
+.Cm noauto
+value is set, a dataset can only be mounted and unmounted explicitly. The
+dataset is not mounted automatically when the dataset is created or imported,
+nor is it mounted by the
+.Qq Nm Cm mount Fl a
+command or unmounted by the
+.Qq Nm Cm umount Fl a
+command.
+.Pp
 This property is not inherited.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBchecksum\fR=\fBon\fR | \fBoff\fR | \fBfletcher2,\fR| \fBfletcher4\fR |
-\fBsha256\fR\fR
-.ad
-.sp .6
-.RS 4n
+.It Sy checksum Ns = Ns Cm on | off | fletcher2 | fletcher4
 Controls the checksum used to verify data integrity. The default value is
-\fBon\fR, which automatically selects an appropriate algorithm (currently,
-\fBfletcher4\fR, but this may change in future releases). The value \fBoff\fR
-disables integrity checking on user data. Disabling checksums is \fBNOT\fR a
-recommended practice.
-.sp
+.Cm on ,
+which automatically selects an appropriate algorithm (currently,
+.Cm fletcher4 ,
+but this may change in future releases). The value
+.Cm off
+disables integrity checking on user data. Disabling checksums is
+.Em NOT
+a recommended practice.
+.It Sy compression Ns = Ns Cm on | off | lzjb | gzip | gzip- Ns Ar N | Cm zle
+Controls the compression algorithm used for this dataset. The
+.CM lzjb
+compression algorithm is optimized for performance while providing decent data
+compression. Setting compression to
+.Cm on
+uses the
+.Cm lzjb
+compression algorithm. The
+.Cm gzip
+compression algorithm uses the same compression as the
+.Xr gzip 1
+command. You can specify the
+.Cm gzip
+level by using the value
+.Cm gzip- Ns Ar N
+where
+.Ar N
+is an integer from 1 (fastest) to 9 (best compression ratio). Currently,
+.Cm gzip
+is equivalent to
+.Cm gzip-6
+(which is also the default for
+.Xr gzip 1 Ns ).
+The
+.Cm zle
+compression algorithm compresses runs of zeros.
+.Pp
+This property can also be referred to by its shortened column name
+.Cm compress .
 Changing this property affects only newly-written data.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBcompression\fR=\fBon\fR | \fBoff\fR | \fBlzjb\fR | \fBgzip\fR |
-\fBgzip-\fR\fIN\fR\fR
-.ad
-.sp .6
-.RS 4n
-Controls the compression algorithm used for this dataset. The \fBlzjb\fR
-compression algorithm is optimized for performance while providing decent data
-compression. Setting compression to \fBon\fR uses the \fBlzjb\fR compression
-algorithm. The \fBgzip\fR compression algorithm uses the same compression as
-the \fBgzip\fR(1) command. You can specify the \fBgzip\fR level by using the
-value \fBgzip-\fR\fIN\fR where \fIN\fR is an integer from 1 (fastest) to 9
-(best compression ratio). Currently, \fBgzip\fR is equivalent to \fBgzip-6\fR
-(which is also the default for \fBgzip\fR(1)).
-.sp
-This property can also be referred to by its shortened column name
-\fBcompress\fR. Changing this property affects only newly-written data.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBcopies\fR=\fB1\fR | \fB2\fR | \fB3\fR\fR
-.ad
-.sp .6
-.RS 4n
+.It Sy copies Ns = Ns Cm 1 | 2 | 3
 Controls the number of copies of data stored for this dataset. These copies are
 in addition to any redundancy provided by the pool, for example, mirroring or
 RAID-Z. The copies are stored on different disks, if possible. The space used
 by multiple copies is charged to the associated file and dataset, changing the
-\fBused\fR property and counting against quotas and reservations.
-.sp
+.Sy used
+property and counting against quotas and reservations.
+.Pp
 Changing this property only affects newly-written data. Therefore, set this
-property at file system creation time by using the \fB-o\fR
-\fBcopies=\fR\fIN\fR option.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBdevices\fR=\fBon\fR | \fBoff\fR\fR
-.ad
-.sp .6
-.RS 4n
-Controls whether device nodes can be opened on this file system. The default
-value is \fBon\fR.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBexec\fR=\fBon\fR | \fBoff\fR\fR
-.ad
-.sp .6
-.RS 4n
+property at file system creation time by using the
+.Fl o Cm copies= Ns Ar N
+option.
+.It Sy dedup Ns = Ns Cm on | off | verify | sha256 Ns Op Cm ,verify
+Configures deduplication for a dataset. The default value is
+.Cm off .
+The default deduplication checksum is
+.Cm sha256
+(this may change in the future).
+When
+.Sy dedup
+is enabled, the checksum defined here overrides the
+.Sy checksum
+property. Setting the value to
+.Cm verify
+has the same effect as the setting
+.Cm sha256,verify .
+.Pp
+If set to
+.Cm verify ,
+.Tn ZFS
+will do a byte-to-byte comparsion in case of two blocks having the same
+signature to make sure the block contents are identical.
+.It Sy devices Ns = Ns Cm on | off
+The
+.Sy devices
+property is currently not supported on
+.Fx .
+.It Sy exec Ns = Ns Cm on | off
 Controls whether processes can be executed from within this file system. The
-default value is \fBon\fR.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBjailed\fR=\fBon\fR | \fBoff\fR\fR
-.ad
-.sp .6
-.RS 4n
-Controls whether the dataset is managed from within a jail. See the "Jails"
-section for more information. The default value is \fBoff\fR.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBmountpoint\fR=\fIpath\fR | \fBnone\fR | \fBlegacy\fR\fR
-.ad
-.sp .6
-.RS 4n
-Controls the mount point used for this file system. See the "Mount Points"
+default value is
+.Cm on .
+.It Sy mlslabel Ns = Ns Ar label | Cm none
+The
+.Sy mlslabel
+property is currently not supported on
+.Fx .
+.It Sy mountpoint Ns = Ns Ar path | Cm none | legacy
+Controls the mount point used for this file system. See the
+.Qq Sx Mount Points
 section for more information on how this property is used.
-.sp
-When the \fBmountpoint\fR property is changed for a file system, the file
-system and any children that inherit the mount point are unmounted. If the new
-value is \fBlegacy\fR, then they remain unmounted. Otherwise, they are
-automatically remounted in the new location if the property was previously
-\fBlegacy\fR or \fBnone\fR, or if they were mounted before the property was
-changed. In addition, any shared file systems are unshared and shared in the
-new location.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBnbmand\fR=\fBon\fR | \fBoff\fR\fR
-.ad
-.sp .6
-.RS 4n
-Controls whether the file system should be mounted with \fBnbmand\fR (Non
-Blocking mandatory locks). This is used for \fBCIFS\fR clients. Changes to this
-property only take effect when the file system is umounted and remounted. See
-\fBmount\fR(8) for more information on \fBnbmand\fR mounts.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBprimarycache\fR=\fBall\fR | \fBnone\fR | \fBmetadata\fR\fR
-.ad
-.sp .6
-.RS 4n
+.Pp
+When the
+.Sy mountpoint
+property is changed for a file system, the file system and any children that
+inherit the mount point are unmounted. If the new value is
+.Cm legacy ,
+then they remain unmounted. Otherwise, they are automatically remounted in the
+new location if the property was previously
+.Cm legacy
+or
+.Cm none ,
+or if they were mounted before the property was changed. In addition, any
+shared file systems are unshared and shared in the new location.
+.It Sy nbmand Ns = Ns Cm on | off
+The
+.Sy nbmand
+property is currently not supported on
+.Fx .
+.It Sy primarycache Ns = Ns Cm all | none | metadata
 Controls what is cached in the primary cache (ARC). If this property is set to
-\fBall\fR, then both user data and metadata is cached. If this property is set
-to \fBnone\fR, then neither user data nor metadata is cached. If this property
-is set to \fBmetadata\fR, then only metadata is cached. The default value is
-\fBall\fR.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBquota\fR=\fIsize\fR | \fBnone\fR\fR
-.ad
-.sp .6
-.RS 4n
+.Cm all ,
+then both user data and metadata is cached. If this property is set to
+.Cm none ,
+then neither user data nor metadata is cached. If this property is set to
+.Cm metadata ,
+then only metadata is cached. The default value is
+.Cm all .
+.It Sy quota Ns = Ns Ar size | Cm none
 Limits the amount of space a dataset and its descendents can consume. This
 property enforces a hard limit on the amount of space used. This includes all
 space consumed by descendents, including file systems and snapshots. Setting a
 quota on a descendent of a dataset that already has a quota does not override
 the ancestor's quota, but rather imposes an additional limit.
-.sp
-Quotas cannot be set on volumes, as the \fBvolsize\fR property acts as an
-implicit quota.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBuserquota@\fR\fIuser\fR=\fIsize\fR | \fBnone\fR\fR
-.ad
-.sp .6
-.RS 4n
-Limits the amount of space consumed by the specified user. User space
-consumption is identified by the \fBuserspace@\fR\fIuser\fR property.
+.Pp
+Quotas cannot be set on volumes, as the
+.Sy volsize
+property acts as an implicit quota.
+.It Sy userquota@ Ns Ar user Ns = Ns Ar size | Cm none
+Limits the amount of space consumed by the specified user.
+Similar to the
+.Sy refquota
+property, the
+.Sy userquota
+space calculation does not include space that is used by descendent datasets,
+such as snapshots and clones. User space consumption is identified by the
+.Sy userspace@ Ns Ar user
+property.
 .sp
 Enforcement of user quotas may be delayed by several seconds. This delay means
 that a user might exceed their quota before the system notices that they are
-over quota and begins to refuse additional writes with the \fBEDQUOT\fR error
-message . See the \fBzfs userspace\fR subcommand for more information.
+over quota and begins to refuse additional writes with the
+.Em EDQUOT
+error message. See the
+.Cm userspace
+subcommand for more information.
 .sp
 Unprivileged users can only access their own groups' space usage. The root
-user, or a user who has been granted the \fBuserquota\fR privilege with \fBzfs
-allow\fR, can get and set everyone's quota.
+user, or a user who has been granted the
+.Sy userquota
+privilege with
+.Qq Nm Cm allow ,
+can get and set everyone's quota.
 .sp
 This property is not available on volumes, on file systems before version 4, or
-on pools before version 15. The \fBuserquota@\fR... properties are not
-displayed by \fBzfs get all\fR. The user's name must be appended after the
-\fB@\fR symbol, using one of the following forms:
-.RS +4
-.TP
-.ie t \(bu
-.el o
-\fIPOSIX name\fR (for example, \fBjoe\fR)
-.RE
-.RS +4
-.TP
-.ie t \(bu
-.el o
-\fIPOSIX numeric ID\fR (for example, \fB789\fR)
-.RE
-.RS +4
-.TP
-.ie t \(bu
-.el o
-\fISID name\fR (for example, \fBjoe.smith at mydomain\fR)
-.RE
-.RS +4
-.TP
-.ie t \(bu
-.el o
-\fISID numeric ID\fR (for example, \fBS-1-123-456-789\fR)
-.RE
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBgroupquota@\fR\fIgroup\fR=\fIsize\fR | \fBnone\fR\fR
-.ad
-.sp .6
-.RS 4n
+on pools before version 15. The
+.Sy userquota@ Ns ...
+properties are not displayed by
+.Qq Nm Cm get all .
+The user's name must be appended after the
+.Sy @
+symbol, using one of the following forms:
+.Bl -bullet -offset 2n
+.It
+POSIX name (for example,
+.Em joe Ns )
+.It
+POSIX numeric ID (for example,
+.Em 1001 Ns )
+.El
+.It Sy groupquota@ Ns Ar group Ns = Ns Ar size | Cm none
 Limits the amount of space consumed by the specified group. Group space
-consumption is identified by the \fBuserquota@\fR\fIuser\fR property.
+consumption is identified by the
+.Sy userquota@ Ns Ar user
+property.
 .sp
 Unprivileged users can access only their own groups' space usage. The root
-user, or a user who has been granted the \fBgroupquota\fR privilege with \fBzfs
-allow\fR, can get and set all groups' quotas.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBreadonly\fR=\fBon\fR | \fBoff\fR\fR
-.ad
-.sp .6
-.RS 4n
-Controls whether this dataset can be modified. The default value is \fBoff\fR.
-.sp
-This property can also be referred to by its shortened column name,
-\fBrdonly\fR.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBrecordsize\fR=\fIsize\fR\fR
-.ad
-.sp .6
-.RS 4n
+user, or a user who has been granted the
+.Sy groupquota
+privilege with
+.Qq Nm Cm allow ,
+can get and set all groups' quotas.
+.It Sy readonly Ns = Ns Cm on | off
+Controls whether this dataset can be modified. The default value is
+.Cm off .
+.It Sy recordsize Ns = Ns Ar size
 Specifies a suggested block size for files in the file system. This property is
 designed solely for use with database workloads that access files in fixed-size
-records. \fBZFS\fR automatically tunes block sizes according to internal
-algorithms optimized for typical access patterns.
-.sp
+records.
+.Tn ZFS
+automatically tunes block sizes according to internal algorithms optimized for
+typical access patterns.
+.Pp
 For databases that create very large files but access them in small random
-chunks, these algorithms may be suboptimal. Specifying a \fBrecordsize\fR
+chunks, these algorithms may be suboptimal. Specifying a
+.Sy recordsize
 greater than or equal to the record size of the database can result in
 significant performance gains. Use of this property for general purpose file
 systems is strongly discouraged, and may adversely affect performance.
-.sp
+.Pp
 The size specified must be a power of two greater than or equal to 512 and less
 than or equal to 128 Kbytes.
-.sp
-Changing the file system's \fBrecordsize\fR affects only files created
-afterward; existing files are unaffected.
+.Pp
+Changing the file system's
+.Sy recordsize
+affects only files created afterward; existing files are unaffected.
 .sp
 This property can also be referred to by its shortened column name,
-\fBrecsize\fR.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBrefquota\fR=\fIsize\fR | \fBnone\fR\fR
-.ad
-.sp .6
-.RS 4n
+.Sy recsize .
+.It Sy refquota Ns = Ns Ar size | Cm none
 Limits the amount of space a dataset can consume. This property enforces a hard
 limit on the amount of space used. This hard limit does not include space used
 by descendents, including file systems and snapshots.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBrefreservation\fR=\fIsize\fR | \fBnone\fR\fR
-.ad
-.sp .6
-.RS 4n
+.It Sy refreservation Ns = Ns Ar size | Cm none
 The minimum amount of space guaranteed to a dataset, not including its
 descendents. When the amount of space used is below this value, the dataset is
 treated as if it were taking up the amount of space specified by
-\fBrefreservation\fR. The \fBrefreservation\fR reservation is accounted for in
-the parent datasets' space used, and counts against the parent datasets' quotas
-and reservations.
+.Sy refreservation .
+The
+.Sy refreservation
+reservation is accounted for in the parent datasets' space used, and counts
+against the parent datasets' quotas and reservations.
 .sp
-If \fBrefreservation\fR is set, a snapshot is only allowed if there is enough
-free pool space outside of this reservation to accommodate the current number
-of "referenced" bytes in the dataset.
+If
+.Sy refreservation
+is set, a snapshot is only allowed if there is enough free pool space outside
+of this reservation to accommodate the current number of "referenced" bytes in
+the dataset.
 .sp
 This property can also be referred to by its shortened column name,
-\fBrefreserv\fR.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBreservation\fR=\fIsize\fR | \fBnone\fR\fR
-.ad
-.sp .6
-.RS 4n
+.Sy refreserv .
+.It Sy reservation Ns = Ns Ar size | Cm none
 The minimum amount of space guaranteed to a dataset and its descendents. When
 the amount of space used is below this value, the dataset is treated as if it
 were taking up the amount of space specified by its reservation. Reservations
 are accounted for in the parent datasets' space used, and count against the
 parent datasets' quotas and reservations.
-.sp
+.Pp
 This property can also be referred to by its shortened column name,
-\fBreserv\fR.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBsecondarycache\fR=\fBall\fR | \fBnone\fR | \fBmetadata\fR\fR
-.ad
-.sp .6
-.RS 4n
+.Sy reserv .
+.It Sy secondarycache Ns = Ns Cm all | none | metadata
 Controls what is cached in the secondary cache (L2ARC). If this property is set
-to \fBall\fR, then both user data and metadata is cached. If this property is
-set to \fBnone\fR, then neither user data nor metadata is cached. If this
-property is set to \fBmetadata\fR, then only metadata is cached. The default
-value is \fBall\fR.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBsetuid\fR=\fBon\fR | \fBoff\fR\fR
-.ad
-.sp .6
-.RS 4n
-Controls whether the set-\fBUID\fR bit is respected for the file system. The
-default value is \fBon\fR.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBsharesmb\fR=\fBon\fR | \fBoff\fR | \fIopts\fR\fR
-.ad
-.sp .6
-.RS 4n
-The \fB\fBsharesmb\fR property has currently no effect on FreeBSD.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBsharenfs\fR=\fBon\fR | \fBoff\fR | \fIopts\fR\fR
-.ad
-.sp .6
-.RS 4n
-Controls whether the file system is shared via \fBNFS\fR, and what options are
-used. A file system with a \fBsharenfs\fR property of \fBoff\fR is managed
-the traditional way via \fBexports\fR(5). Otherwise, the file system is
-automatically shared and unshared with the \fBzfs share\fR and
-\fBzfs unshare\fR commands. If the property is set to \fBon\fR, no NFS export
-options are used. Otherwise, NFS export options are equivalent to the contents
-of this property.
-.sp
-When the \fBsharenfs\fR property is changed for a dataset, the \fBmountd\fR(8)
-daemon is reloaded.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBlogbias\fR = \fBlatency\fR | \fBthroughput\fR\fR
-.ad
-.sp .6
-.RS 4n
-Provide a hint to ZFS about handling of synchronous requests in this dataset.
-If \fBlogbias\fR is set to \fBlatency\fR (the default), ZFS will use pool log
-devices (if configured) to handle the requests at low latency. If \fBlogbias\fR
-is set to \fBthroughput\fR, ZFS will not use configured pool log devices. ZFS
+to
+.Cm all ,
+then both user data and metadata is cached. If this property is set to
+.Cm none ,
+then neither user data nor metadata is cached. If this property is set to
+.Cm metadata ,
+then only metadata is cached. The default value is
+.Cm all .
+.It Sy setuid Ns = Ns Cm on | off
+Controls whether the
+.No set- Ns Tn UID
+bit is respected for the file system. The default value is
+.Cm on .
+.It Sy sharesmb Ns = Ns Cm on | off | Ar opts
+The
+.Sy sharesmb
+property has currently no effect o
+.Fx .
+.It Sy sharenfs Ns = Ns Cm on | off | Ar opts
+Controls whether the file system is shared via
+.Tn NFS ,
+and what options are used. A file system with a
+.Sy sharenfs
+property of
+.Cm off
+is managed the traditional way via
+.Xr exports 5 .
+Otherwise, the file system is automatically shared and unshared with the
+.Qq Nm Cm share
+and
+.Qq Nm Cm unshare
+commands. If the property is set to
+.Cm on
+no
+.Tn NFS
+export options are used. Otherwise,
+.Tn NFS
+export options are equivalent to the contents of this property. The export
+options may be comma-separated. See
+.Xr exports 5
+for a list of valid options.
+.Pp
+When the
+.Sy sharenfs
+property is changed for a dataset, the
+.Xr mountd 8
+dameon is reloaded.
+.It Sy logbias Ns = Ns Cm latency | throughput
+Provide a hint to
+.Tn ZFS
+about handling of synchronous requests in this dataset.
+If
+.Sy logbias
+is set to
+.Cm latency
+(the default),
+.Tn ZFS
+will use pool log devices (if configured) to handle the requests at low
+latency. If
+.Sy logbias
+is set to
+.Cm throughput ,
+.Tn ZFS
+will not use configured pool log devices.
+.Tn ZFS
 will instead optimize synchronous operations for global pool throughput and
 efficient use of resources.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBsnapdir\fR=\fBhidden\fR | \fBvisible\fR\fR
-.ad
-.sp .6
-.RS 4n
-Controls whether the \fB\&.zfs\fR directory is hidden or visible in the root of
-the file system as discussed in the "Snapshots" section. The default value is
-\fBhidden\fR.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBversion\fR=\fB1\fR | \fB2\fR | \fBcurrent\fR\fR
-.ad
-.sp .6
-.RS 4n
-The on-disk version of this file system, which is independent of the pool
-version. This property can only be set to later supported versions. See the
-\fBzfs upgrade\fR command.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBvolsize\fR=\fIsize\fR\fR
-.ad
-.sp .6
-.RS 4n
+.It Sy snapdir Ns = Ns Cm hidden | visible
+Controls whether the 
+.Pa \&.zfs
+directory is hidden or visible in the root of the file system as discussed in
+the
+.Qq Sx Snapshots
+section. The default value is
+.Cm hidden .
+.It Sy sync Ns = Ns Cm standard | always | disabled
+Controls the behavior of synchronous requests (e.g.
+.Xr fsync 2 ,
+O_DSYNC). This property accepts the following values:
+.Bl -tag -offset 4n -width 8n
+.It Sy standard
+This is the POSIX specified behavior of ensuring all synchronous requests are
+written to stable storage and all devices are flushed to ensure data is not
+cached by device controllers (this is the default).
+.It Sy always
+All file system transactions are written and flushed before their system calls
+return. This has a large performance penalty.
+.It Sy disabled
+Disables synchronous requests. File system transactions are only committed to
+stable storage periodically. This option will give the highest performance.
+However, it is very dangerous as
+.Tn ZFS
+would be ignoring the synchronous transaction demands of applications such as
+databases or
+.Tn NFS .
+Administrators should only use this option when the risks are understood.
+.El
+.It Sy volsize Ns = Ns Ar size
 For volumes, specifies the logical size of the volume. By default, creating a
 volume establishes a reservation of equal size. For storage pools with a
-version number of 9 or higher, a \fBrefreservation\fR is set instead. Any
-changes to \fBvolsize\fR are reflected in an equivalent change to the
-reservation (or \fBrefreservation\fR). The \fBvolsize\fR can only be set to a
-multiple of \fBvolblocksize\fR, and cannot be zero.
-.sp
+version number of 9 or higher, a
+.Sy refreservation
+is set instead. Any changes to
+.Sy volsize
+are reflected in an equivalent change to the reservation (or
+.Sy refreservation Ns ).
+The
+.Sy volsize
+can only be set to a multiple of
+.Cm volblocksize ,
+and cannot be zero.
+.Pp
 The reservation is kept equal to the volume's logical size to prevent
 unexpected behavior for consumers. Without the reservation, the volume could
 run out of space, resulting in undefined behavior or data corruption, depending
@@ -1238,1880 +1176,1645 @@
 should be used when adjusting the volume size.
 .sp
 Though not recommended, a "sparse volume" (also known as "thin provisioning")
-can be created by specifying the \fB-s\fR option to the \fBzfs create -V\fR
+can be created by specifying the
+.Fl s
+option to the
+.Qq Nm Cm create Fl V
 command, or by changing the reservation after the volume has been created. A
 "sparse volume" is a volume where the reservation is less then the volume size.
-Consequently, writes to a sparse volume can fail with \fBENOSPC\fR when the
-pool is low on space. For a sparse volume, changes to \fBvolsize\fR are not
-reflected in the reservation.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBvscan\fR=\fBon\fR | \fBoff\fR\fR
-.ad
-.sp .6
-.RS 4n
-Controls whether regular files should be scanned for viruses when a file is
-opened and closed. In addition to enabling this property, the virus scan
-service must also be enabled for virus scanning to occur. The default value is
-\fBoff\fR.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBxattr\fR=\fBon\fR | \fBoff\fR\fR
-.ad
-.sp .6
-.RS 4n
-Controls whether extended attributes are enabled for this file system. The
-default value is \fBon\fR.
-.RE
-
-.sp
-.LP
+Consequently, writes to a sparse volume can fail with
+.Sy ENOSPC
+when the pool is low on space. For a sparse volume, changes to
+.Sy volsize
+are not reflected in the reservation.
+.It Sy vscan Ns = Ns Cm off | on
+The
+.Sy vscan
+property is currently not supported on
+.Fx . 
+.It Sy xattr Ns = Ns Cm off | on
+The
+.Sy xattr
+property is currently not supported on
+.Fx .
+.It Sy jailed Ns = Ns Cm off | on
+Controls whether the dataset is managed from a jail. See the
+.Qq Sx Jails
+section for more information. The default value is
+.Cm off .
+.El
+.Pp
 The following three properties cannot be changed after the file system is
 created, and therefore, should be set when the file system is created. If the
-properties are not set with the \fBzfs create\fR or \fBzpool create\fR
+properties are not set with the
+.Qq Nm Cm create
+or
+.Nm zpool Cm create
 commands, these properties are inherited from the parent dataset. If the parent
 dataset lacks these properties due to having been created prior to these
 features being supported, the new file system will have the default values for
 these properties.
-.sp
-.ne 2
-.na
-\fB\fBcasesensitivity\fR=\fBsensitive\fR | \fBinsensitive\fR | \fBmixed\fR\fR
-.ad
-.sp .6
-.RS 4n
-The \fB\fBcasesensitivity\fR property is currently not supported on FreeBSD.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBnormalization\fR = \fBnone\fR | \fBformC\fR | \fBformD\fR | \fBformKC\fR
-| \fBformKD\fR\fR
-.ad
-.sp .6
-.RS 4n
-Indicates whether the file system should perform a \fBunicode\fR normalization
-of file names whenever two file names are compared, and which normalization
-algorithm should be used. File names are always stored unmodified, names are
-normalized as part of any comparison process. If this property is set to a
-legal value other than \fBnone\fR, and the \fButf8only\fR property was left
-unspecified, the \fButf8only\fR property is automatically set to \fBon\fR. The
-default value of the \fBnormalization\fR property is \fBnone\fR. This property
-cannot be changed after the file system is created.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fButf8only\fR=\fBon\fR | \fBoff\fR\fR
-.ad
-.sp .6
-.RS 4n
+.Bl -tag -width 4n
+.It Sy casesensitivity Ns = Ns Cm sensitive | insensitive | mixed
+The
+.Sy casesensitivity
+property is currently not supported on
+.Fx .
+.It Sy normalization Ns = Ns Cm none | formC | formD | formKC | formKD
+Indicates whether the file system should perform a
+.Sy unicode
+normalization of file names whenever two file names are compared, and which
+normalization algorithm should be used. File names are always stored
+unmodified, names are normalized as part of any comparison process. If this
+property is set to a legal value other than
+.Cm none ,
+and the
+.Sy utf8only
+property was left unspecified, the
+.Sy utf8only
+property is automatically set to
+.Cm on .
+The default value of the
+.Sy normalization
+property is
+.Cm none .
+This property cannot be changed after the file system is created.
+.It Sy utf8only Ns = Ns Cm on | off
 Indicates whether the file system should reject file names that include
-characters that are not present in the \fBUTF-8\fR character code set. If this
-property is explicitly set to \fBoff\fR, the normalization property must either
-not be explicitly set or be set to \fBnone\fR. The default value for the
-\fButf8only\fR property is \fBoff\fR. This property cannot be changed after the
-file system is created.
-.RE
-
-.sp
-.LP
-The \fBcasesensitivity\fR, \fBnormalization\fR, and \fButf8only\fR properties
-are also new permissions that can be assigned to non-privileged users by using
-the \fBZFS\fR delegated administration feature.
-.SS "Temporary Mount Point Properties"
-.sp
-.LP
-When a file system is mounted, either through \fBmount\fR(8) for legacy mounts
-or the \fBzfs mount\fR command for normal file systems, its mount options are
-set according to its properties. The correlation between properties and mount
-options is as follows:
-.sp
-.in +2
-.nf
-    PROPERTY                MOUNT OPTION
-     devices                 devices/nodevices
-     exec                    exec/noexec
-     readonly                ro/rw
-     setuid                  setuid/nosetuid
-     xattr                   xattr/noxattr
-.fi
-.in -2
-.sp
-
-.sp
-.LP
-In addition, these options can be set on a per-mount basis using the \fB-o\fR
+characters that are not present in the
+.Sy UTF-8
+character code set. If this property is explicitly set to
+.Cm off ,
+the normalization property must either not be explicitly set or be set to
+.Cm none .
+The default value for the
+.Sy utf8only
+property is
+.Cm off .
+This property cannot be changed after the file system is created.
+.El
+.Pp
+The
+.Sy casesensitivity , normalization , No and Sy utf8only
+properties are also new permissions that can be assigned to non-privileged
+users by using the
+.Tn ZFS
+delegated administration feature.
+.Ss Temporary Mount Point Properties
+When a file system is mounted, either through
+.Xr mount 8
+for legacy mounts or the
+.Qq Nm Cm mount
+command for normal file systems, its mount options are set according to its
+properties. The correlation between properties and mount options is as follows:
+.Bl -column -offset 4n "PROPERTY" "MOUNT OPTION"
+.It PROPERTY	MOUNT OPTION
+.It atime	atime/noatime
+.It exec	exec/noexec
+.It readonly	ro/rw
+.It setuid	suid/nosuid
+.El
+.Pp
+In addition, these options can be set on a per-mount basis using the
+.Fl o
 option, without affecting the property that is stored on disk. The values
-specified on the command line override the values stored in the dataset. The
-\fB-nosuid\fR option is an alias for \fBnodevices,nosetuid\fR. These properties
-are reported as "temporary" by the \fBzfs get\fR command. If the properties are
-changed while the dataset is mounted, the new setting overrides any temporary
-settings.
-.SS "User Properties"
-.sp
-.LP
-In addition to the standard native properties, \fBZFS\fR supports arbitrary
-user properties. User properties have no effect on \fBZFS\fR behavior, but
-applications or administrators can use them to annotate datasets (file systems,
-volumes, and snapshots).
-.sp
-.LP
-User property names must contain a colon (\fB:\fR) character to distinguish
-them from native properties. They may contain lowercase letters, numbers, and
-the following punctuation characters: colon (\fB:\fR), dash (\fB-\fR), period
-(\fB\&.\fR), and underscore (\fB_\fR). The expected convention is that the
-property name is divided into two portions such as
-\fImodule\fR\fB:\fR\fIproperty\fR, but this namespace is not enforced by
-\fBZFS\fR. User property names can be at most 256 characters, and cannot begin
-with a dash (\fB-\fR).
-.sp
-.LP
+specified on the command line override the values stored in the dataset. These 
+properties are reported as "temporary" by the
+.Qq Nm Cm get
+command. If the properties are changed while the dataset is mounted, the new
+setting overrides any temporary settings.
+.Ss User Properties
+In addition to the standard native properties,
+.Tn ZFS
+supports arbitrary user properties. User properties have no effect on
+.Tn ZFS
+behavior, but applications or administrators can use them to annotate datasets
+(file systems, volumes, and snapshots).
+.Pp
+User property names must contain a colon
+.Pq Sy \&:
+character to distinguish them from native properties. They may contain
+lowercase letters, numbers, and the following punctuation characters: colon
+.Pq Sy \&: ,
+dash
+.Pq Sy \&- ,
+period
+.Pq Sy \&.
+and underscore
+.Pq Sy \&_ .
+The expected convention is that the property name is divided into two portions
+such as
+.Em module Ns Sy \&: Ns Em property ,
+but this namespace is not enforced by
+.Tn ZFS .
+User property names can be at most 256 characters, and cannot begin with a dash
+.Pq Sy \&- .
+.Pp
 When making programmatic use of user properties, it is strongly suggested to
-use a reversed \fBDNS\fR domain name for the \fImodule\fR component of property
-names to reduce the chance that two independently-developed packages use the
-same property name for different purposes. Property names beginning with
-\fBcom.sun\fR. are reserved for use by Sun Microsystems.
-.sp
-.LP
+use a reversed
+.Tn DNS
+domain name for the
+.Ar module
+component of property names to reduce the chance that two
+independently-developed packages use the same property name for different
+purposes. Property names beginning with 
+.Em com.sun
+are reserved for use by Sun Microsystems.
+.Pp
 The values of user properties are arbitrary strings, are always inherited, and
-are never validated. All of the commands that operate on properties (\fBzfs
-list\fR, \fBzfs get\fR, \fBzfs set\fR, and so forth) can be used to manipulate
-both native properties and user properties. Use the \fBzfs inherit\fR command
-to clear a user property . If the property is not defined in any parent
+are never validated. All of the commands that operate on properties
+.Po
+.Qq Nm Cm list ,
+.Qq Nm Cm get ,
+.Qq Nm Cm set
+and so forth
+.Pc
+can be used to manipulate both native properties and user properties. Use the
+.Qq Nm Cm inherit
+command to clear a user property. If the property is not defined in any parent
 dataset, it is removed entirely. Property values are limited to 1024
 characters.
-.SH SUBCOMMANDS
-.sp
-.LP
+.Sh SUBCOMMANDS
 All subcommands that modify state are logged persistently to the pool in their
 original form.
-.sp
-.ne 2
-.na
-\fB\fBzfs ?\fR\fR
-.ad
-.br
-.na
-\fB\fBzfs rename\fR \fB-u\fR [\fB-p\fR] \fIfilesystem\fR \fIfilesystem\fR\fR
-.ad
-.sp .6
-.RS 4n
+.Bl -tag -width 2n
+.It Xo
+.Nm
+.Op Fl \&?
+.Xc
+.Pp
 Displays a help message.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzfs create\fR [\fB-p\fR] [\fB-o\fR \fIproperty\fR=\fIvalue\fR] ...
-\fIfilesystem\fR\fR
-.ad
-.sp .6
-.RS 4n
-Creates a new \fBZFS\fR file system. The file system is automatically mounted
-according to the \fBmountpoint\fR property inherited from the parent.
-.sp
-.ne 2
-.na
-\fB\fB-p\fR\fR
-.ad
-.sp .6
-.RS 4n
+.It Xo
+.Nm
+.Cm create
+.Op Fl p
+.Op Fl o Ar property Ns = Ns Ar value
+.Ar ... filesystem
+.Xc
+.Pp
+Creates a new
+.Tn ZFS
+file system. The file system is automatically mounted according to the
+.Sy mountpoint
+property inherited from the parent.
+.Bl -tag -width indent
+.It Fl p
 Creates all the non-existing parent datasets. Datasets created in this manner
-are automatically mounted according to the \fBmountpoint\fR property inherited
-from their parent. Any property specified on the command line using the
-\fB-o\fR option is ignored. If the target filesystem already exists, the
-operation completes successfully.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-o\fR \fIproperty\fR=\fIvalue\fR\fR
-.ad
-.sp .6
-.RS 4n
-Sets the specified property as if the command \fBzfs set\fR
-\fIproperty\fR=\fIvalue\fR was invoked at the same time the dataset was
-created. Any editable \fBZFS\fR property can also be set at creation time.
-Multiple \fB-o\fR options can be specified. An error results if the same
-property is specified in multiple \fB-o\fR options.
-.RE
-
-.sp
-.ne 2
-.mk
-.na
-\fB\fB-u\fR\fR
-.ad
-.sp .6
-.RS 4n
-Do not remount file systems during rename. If a file system's \fBmountpoint\fR property is set to \fBlegacy\fR or \fBnone\fR, file system is not unmounted even if this option is not given.
-.RE
-
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzfs create\fR [\fB-ps\fR] [\fB-b\fR \fIblocksize\fR] [\fB-o\fR
-\fIproperty\fR=\fIvalue\fR] ... \fB-V\fR \fIsize\fR \fIvolume\fR\fR
-.ad
-.sp .6
-.RS 4n
+are automatically mounted according to the
+.Sy mountpoint
+property inherited from their parent. Any property specified on the command
+line using the
+.Fl o
+option is ignored. If the target filesystem already exists, the operation
+completes successfully.
+.It Fl o Ar property Ns = Ns Ar value
+Sets the specified property as if the command
+.Qq Nm Cm set Ar property Ns = Ns Ar value
+was invoked at the same time the dataset was created. Any editable
+.Tn ZFS
+property can also be set at creation time. Multiple
+.Fl o
+options can be specified. An error results if the same property is specified in
+multiple
+.Fl o
+options.
+.El
+.It Xo
+.Nm
+.Cm create
+.Op Fl ps
+.Op Fl b Ar blocksize
+.Op Fl o Ar property Ns = Ns Ar value
+.Ar ...
+.Fl V
+.Ar size volume
+.Xc
+.Pp
 Creates a volume of the given size. The volume is exported as a block device in
-\fB/dev/zvol/{dsk,rdsk}/\fR\fIpath\fR, where \fIpath\fR is the name of the
-volume in the \fBZFS\fR namespace. The size represents the logical size as
-exported by the device. By default, a reservation of equal size is created.
-.sp
-\fIsize\fR is automatically rounded up to the nearest 128 Kbytes to ensure that
-the volume has an integral number of blocks regardless of \fIblocksize\fR.
-.sp
-.ne 2
-.na
-\fB\fB-p\fR\fR
-.ad
-.sp .6
-.RS 4n
+.Pa /dev/zvol/path ,
+where
+.Ar path
+is the name of the volume in the
+.Tn ZFS
+namespace. The size represents the logical size as exported by the device. By
+default, a reservation of equal size is created.
+.Pp
+.Ar size
+is automatically rounded up to the nearest 128 Kbytes to ensure that
+the volume has an integral number of blocks regardless of
+.Ar blocksize .
+.Bl -tag -width indent
+.It Fl p
 Creates all the non-existing parent datasets. Datasets created in this manner
-are automatically mounted according to the \fBmountpoint\fR property inherited
-from their parent. Any property specified on the command line using the
-\fB-o\fR option is ignored. If the target filesystem already exists, the
-operation completes successfully.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-s\fR\fR
-.ad
-.sp .6
-.RS 4n
-Creates a sparse volume with no reservation. See \fBvolsize\fR in the Native
-Properties section for more information about sparse volumes.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-o\fR \fIproperty\fR=\fIvalue\fR\fR
-.ad
-.sp .6
-.RS 4n
-Sets the specified property as if the \fBzfs set\fR \fIproperty\fR=\fIvalue\fR
+are automatically mounted according to the
+.Sy mountpoint
+property inherited from their parent. Any property specified on the command
+line using the
+.Fl o
+option is ignored. If the target filesystem already exists, the operation
+completes successfully.
+.It Fl s
+Creates a sparse volume with no reservation. See
+.Sy volsize
+in the
+.Qq Sx Native Properties
+section for more information about sparse volumes.
+.It Fl b Ar blocksize
+Equivalent to
+.Fl o Cm volblocksize Ns = Ns Ar blocksize .
+If this option is specified in conjunction with
+.Fl o Cm volblocksize ,
+the resulting behavior is undefined.
+.It Fl o Ar property Ns = Ns Ar value
+Sets the specified property as if the
+.Qq Nm Cm set Ar property Ns = Ns Ar value
 command was invoked at the same time the dataset was created. Any editable
-\fBZFS\fR property can also be set at creation time. Multiple \fB-o\fR options
-can be specified. An error results if the same property is specified in
-multiple \fB-o\fR options.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-b\fR \fIblocksize\fR\fR
-.ad
-.sp .6
-.RS 4n
-Equivalent to \fB-o\fR \fBvolblocksize\fR=\fIblocksize\fR. If this option is
-specified in conjunction with \fB-o\fR \fBvolblocksize\fR, the resulting
-behavior is undefined.
-.RE
-
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzfs destroy\fR [\fB-rRf\fR] \fIfilesystem\fR|\fIvolume\fR\fR
-.ad
-.sp .6
-.RS 4n
+.Tn ZFS
+property can also be set at creation time. Multiple
+.Fl o
+options can be specified. An error results if the same property is specified in
+multiple
+.Fl o
+options.
+.El
+.It Xo
+.Nm
+.Cm destroy
+.Op Fl fnpRrv
+.Ar filesystem Ns | Ns Ar volume
+.Xc
+.Pp
 Destroys the given dataset. By default, the command unshares any file systems
 that are currently shared, unmounts any file systems that are currently
 mounted, and refuses to destroy a dataset that has active dependents (children
 or clones).
-.sp
-.ne 2
-.na
-\fB\fB-r\fR\fR
-.ad
-.sp .6
-.RS 4n
+.Bl -tag -width indent
+.It Fl r
 Recursively destroy all children.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-R\fR\fR
-.ad
-.sp .6
-.RS 4n
+.It Fl R
 Recursively destroy all dependents, including cloned file systems outside the
 target hierarchy.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-f\fR\fR
-.ad
-.sp .6
-.RS 4n
-Force an unmount of any file systems using the \fBunmount -f\fR command. This
-option has no effect on non-file systems or unmounted file systems.
-.RE
-
-Extreme care should be taken when applying either the \fB-r\fR or the \fB-R\fR
+.It Fl f
+Force an unmount of any file systems using the
+.Qq Nm Cm unmount Fl f
+command. This option has no effect on non-file systems or unmounted file
+systems.
+.It Fl n
+Do a dry-run ("No-op") deletion. No data will be deleted. This is useful in
+conjunction with the
+.Fl v
+or
+.Fl p
+flags to determine what data would be deleted.
+.It Fl p
+Print machine-parsable verbose information about the deleted data.
+.It Fl v
+Print verbose information about the deleted data.
+.El
+.Pp
+Extreme care should be taken when applying either the
+.Fl r
+or the
+.Fl R
 options, as they can destroy large portions of a pool and cause unexpected
 behavior for mounted file systems in use.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzfs destroy\fR [\fB-rRd\fR] \fIsnapshot\fR\fR
-.ad
-.sp .6
-.RS 4n
-The given snapshot is destroyed immediately if and only if the \fBzfs
-destroy\fR command without the \fB-d\fR option would have destroyed it. Such
-immediate destruction would occur, for example, if the snapshot had no clones
-and the user-initiated reference count were zero.
-.sp
-If the snapshot does not qualify for immediate destruction, it is marked for
+.It Xo
+.Nm
+.Cm destroy
+.Op Fl dnpRrv
+.Sm off
+.Ar snapshot
+.Ns Op % Ns Ar snapname
+.Ns Op , Ns Ar ...
+.Sm on
+.Xc
+.Pp
+The given snapshots are destroyed immediately if and only if the
+.Qq Nm Cm destroy
+command without the
+.Fl d
+option would have destroyed it. Such immediate destruction would occur, for
+example, if the snapshot had no clones and the user-initiated reference count
+were zero.
+.Pp
+If a snapshot does not qualify for immediate destruction, it is marked for
 deferred deletion. In this state, it exists as a usable, visible snapshot until
 both of the preconditions listed above are met, at which point it is destroyed.
-.sp
-.ne 2
-.na
-\fB\fB-d\fR\fR
-.ad
-.sp .6
-.RS 4n
-Defer snapshot deletion.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-r\fR\fR
-.ad
-.sp .6
-.RS 4n
+.Pp
+An inclusive range of snapshots may be specified by separating the
+first and last snapshots with a percent sign
+.Pq Sy % .
+The first and/or last snapshots may be left blank, in which case the
+filesystem's oldest or newest snapshot will be implied.
+.Pp
+Multiple snapshots
+(or ranges of snapshots) of the same filesystem or volume may be specified
+in a comma-separated list of snapshots.
+Only the snapshot's short name (the
+part after the
+.Sy @ )
+should be specified when using a range or comma-separated list to identify
+multiple snapshots.
+.Bl -tag -width indent
+.It Fl r
 Destroy (or mark for deferred deletion) all snapshots with this name in
 descendent file systems.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-R\fR\fR
-.ad
-.sp .6
-.RS 4n
+.It Fl R
 Recursively destroy all dependents.
-.RE
-
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzfs snapshot\fR [\fB-r\fR] [\fB-o\fR \fIproperty\fR=\fIvalue\fR] ...
-\fIfilesystem at snapname\fR|\fIvolume at snapname\fR\fR
-.ad
-.sp .6
-.RS 4n
+.It Fl n
+Do a dry-run ("No-op") deletion. No data will be deleted. This is useful in
+conjunction with the
+.Fl v
+or
+.Fl p
+flags to determine what data would be deleted.
+.It Fl p
+Print machine-parsable verbose information about the deleted data.
+.It Fl v
+Print verbose information about the deleted data.
+.It Fl d
+Defer snapshot deletion.
+.El
+.Pp
+Extreme care should be taken when applying either the
+.Fl r
+or the
+.Fl R
+options, as they can destroy large portions of a pool and cause unexpected
+behavior for mounted file systems in use.
+.It Xo
+.Nm
+.Cm snapshot
+.Op Fl r
+.Op Fl o Ar property Ns = Ns Ar value
+.Ar ...
+.Ar filesystem at snapname Ns | Ns volume at snapname
+.Xc
+.Pp
 Creates a snapshot with the given name. All previous modifications by
 successful system calls to the file system are part of the snapshot. See the
-"Snapshots" section for details.
-.sp
-.ne 2
-.na
-\fB\fB-r\fR\fR
-.ad
-.sp .6
-.RS 4n
+.Qq Sx Snapshots
+section for details.
+.Bl -tag -width indent
+.It Fl r
 Recursively create snapshots of all descendent datasets. Snapshots are taken
 atomically, so that all recursive snapshots correspond to the same moment in
 time.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-o\fR \fIproperty\fR=\fIvalue\fR\fR
-.ad
-.sp .6
-.RS 4n
-Sets the specified property; see \fBzfs create\fR for details.
-.RE
-
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzfs rollback\fR [\fB-rRf\fR] \fIsnapshot\fR\fR
-.ad
-.sp .6
-.RS 4n
+.It Fl o Ar property Ns = Ns Ar value
+Sets the specified property; see
+.Qq Nm Cm create
+for details.
+.El
+.It Xo
+.Nm
+.Cm rollback
+.Op Fl rRf
+.Ar snapshot
+.Xc
+.Pp
 Roll back the given dataset to a previous snapshot. When a dataset is rolled
 back, all data that has changed since the snapshot is discarded, and the
 dataset reverts to the state at the time of the snapshot. By default, the
 command refuses to roll back to a snapshot other than the most recent one. In
 order to do so, all intermediate snapshots must be destroyed by specifying the
-\fB-r\fR option.
-.sp
-The \fB-rR\fR options do not recursively destroy the child snapshots of a
-recursive snapshot. Only the top-level recursive snapshot is destroyed by
-either of these options. To completely roll back a recursive snapshot, you must
-rollback the individual child snapshots.
-.sp
-.ne 2
-.na
-\fB\fB-r\fR\fR
-.ad
-.sp .6
-.RS 4n
+.Fl r
+option.
+.Bl -tag -width indent
+.It Fl r
 Recursively destroy any snapshots more recent than the one specified.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-R\fR\fR
-.ad
-.sp .6
-.RS 4n
+.It Fl R
 Recursively destroy any more recent snapshots, as well as any clones of those
 snapshots.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-f\fR\fR
-.ad
-.sp .6
-.RS 4n
-Used with the \fB-R\fR option to force an unmount of any clone file systems
-that are to be destroyed.
-.RE
-
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzfs clone\fR [\fB-p\fR] [\fB-o\fR \fIproperty\fR=\fIvalue\fR] ...
-\fIsnapshot\fR \fIfilesystem\fR|\fIvolume\fR\fR
-.ad
-.sp .6
-.RS 4n
-Creates a clone of the given snapshot. See the "Clones" section for details.
-The target dataset can be located anywhere in the \fBZFS\fR hierarchy, and is
-created as the same type as the original.
-.sp
-.ne 2
-.na
-\fB\fB-p\fR\fR
-.ad
-.sp .6
-.RS 4n
+.It Fl f
+Used with the
+.Fl R
+option to force an unmount of any clone file systems that are to be destroyed.
+.El
+.It Xo
+.Nm
+.Cm clone
+.Op Fl p
+.Op Fl o Ar property Ns = Ns Ar value
+.Ar ... snapshot filesystem Ns | Ns Ar volume
+.Xc
+.Pp
+Creates a clone of the given snapshot. See the
+.Qq Sx Clones
+section for details. The target dataset can be located anywhere in the
+.Tn ZFS
+hierarchy, and is created as the same type as the original.
+.Bl -tag -width indent
+.It Fl p
 Creates all the non-existing parent datasets. Datasets created in this manner
-are automatically mounted according to the \fBmountpoint\fR property inherited
-from their parent. If the target filesystem or volume already exists, the
-operation completes successfully.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-o\fR \fIproperty\fR=\fIvalue\fR\fR
-.ad
-.sp .6
-.RS 4n
-Sets the specified property; see \fBzfs create\fR for details.
-.RE
-
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzfs promote\fR \fIclone-filesystem\fR\fR
-.ad
-.sp .6
-.RS 4n
+are automatically mounted according to the
+.Sy mountpoint
+property inherited from their parent. If the target filesystem or volume
+already exists, the operation completes successfully.
+.It Fl o Ar property Ns = Ns Ar value
+Sets the specified property; see
+.Qq Nm Cm create
+for details.
+.El
+.It Xo
+.Nm
+.Cm promote
+.Ar clone-filesystem
+.Xc
+.Pp
 Promotes a clone file system to no longer be dependent on its "origin"
 snapshot. This makes it possible to destroy the file system that the clone was
 created from. The clone parent-child dependency relationship is reversed, so
 that the origin file system becomes a clone of the specified file system.
-.sp
+.Pp
 The snapshot that was cloned, and any snapshots previous to this snapshot, are
 now owned by the promoted clone. The space they use moves from the origin file
 system to the promoted clone, so enough space must be available to accommodate
 these snapshots. No new space is consumed by this operation, but the space
 accounting is adjusted. The promoted clone must not have any conflicting
-snapshot names of its own. The \fBrename\fR subcommand can be used to rename
-any conflicting snapshots.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzfs rename\fR \fIfilesystem\fR|\fIvolume\fR|\fIsnapshot\fR\fR
-.ad
-.br
-.na
-\fB\fIfilesystem\fR|\fIvolume\fR|\fIsnapshot\fR\fR
-.ad
-.br
-.na
-\fB\fBzfs rename\fR [\fB-p\fR] \fIfilesystem\fR|\fIvolume\fR
-\fIfilesystem\fR|\fIvolume\fR\fR
-.ad
-.sp .6
-.RS 4n
+snapshot names of its own. The
+.Cm rename
+subcommand can be used to rename any conflicting snapshots.
+.It Xo
+.Nm
+.Cm rename
+.Ar filesystem Ns | Ns Ar volume Ns | Ns Ar snapshot
+.Ar filesystem Ns | Ns Ar volume Ns | Ns Ar snapshot
+.Xc
+.It Xo
+.Nm
+.Cm rename
+.Fl p
+.Ar filesystem Ns | Ns Ar volume
+.Ar filesystem Ns | Ns Ar volume
+.Xc
+.It Xo
+.Nm
+.Cm rename
+.Fl u
+.Op Fl p
+.Ar filesystem filesystem
+.Xc
+.Pp
 Renames the given dataset. The new target can be located anywhere in the
-\fBZFS\fR hierarchy, with the exception of snapshots. Snapshots can only be
-renamed within the parent file system or volume. When renaming a snapshot, the
-parent file system of the snapshot does not need to be specified as part of the
-second argument. Renamed file systems can inherit new mount points, in which
-case they are unmounted and remounted at the new mount point.
-.sp
-.ne 2
-.na
-\fB\fB-p\fR\fR
-.ad
-.sp .6
-.RS 4n
+.Tn ZFS
+hierarchy, with the exception of snapshots. Snapshots can only be renamed
+within the parent file system or volume. When renaming a snapshot, the parent
+file system of the snapshot does not need to be specified as part of the second
+argument. Renamed file systems can inherit new mount points, in which case they
+are unmounted and remounted at the new mount point.
+.Bl -tag -width indent
+.It Fl p
 Creates all the nonexistent parent datasets. Datasets created in this manner
-are automatically mounted according to the \fBmountpoint\fR property inherited
-from their parent.
-.RE
-
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzfs rename\fR \fB-r\fR \fIsnapshot\fR \fIsnapshot\fR\fR
-.ad
-.sp .6
-.RS 4n
+are automatically mounted according to the
+.Sy mountpoint
+property inherited from their parent.
+.It Fl u
+Do not remount file systems during rename. If a file system's
+.Sy mountpoint
+property is set to
+.Cm legacy
+or
+.Cm none ,
+file system is not unmounted even if this option is not given.
+.El
+.It Xo
+.Nm
+.Cm rename
+.Fl r
+.Ar snapshot snapshot
+.Xc
+.Pp
 Recursively rename the snapshots of all descendent datasets. Snapshots are the
 only dataset that can be renamed recursively.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzfs\fR \fBlist\fR [\fB-r\fR|\fB-d\fR \fIdepth\fR] [\fB-H\fR] [\fB-o\fR
-\fIproperty\fR[,\fI\&...\fR]] [ \fB-t\fR \fItype\fR[,\fI\&...\fR]] [ \fB-s\fR
-\fIproperty\fR ] ... [ \fB-S\fR \fIproperty\fR ] ...
-[\fIfilesystem\fR|\fIvolume\fR|\fIsnapshot\fR] ...\fR
-.ad
-.sp .6
-.RS 4n
+.It Xo
+.Nm
+.Cm list
+.Op Fl r Ns | Ns Fl d Ar depth
+.Op Fl H
+.Op Fl o Ar property Ns Op , Ns Ar ...
+.Op Fl t Ar type Ns Op , Ns Ar ...
+.Op Fl s Ar property
+.Ar ...
+.Op Fl S Ar property
+.Ar ...
+.Ar filesystem Ns | Ns Ar volume Ns | Ns Ar snapshot
+.Xc
+.Pp
 Lists the property information for the given datasets in tabular form. If
 specified, you can list property information by the absolute pathname or the
 relative pathname. By default, all file systems and volumes are displayed.
-Snapshots are displayed if the \fBlistsnaps\fR property is \fBon\fR (the
-default is \fBoff\fR) . The following fields are displayed,
-\fBname,used,available,referenced,mountpoint\fR.
-.sp
-.ne 2
-.na
-\fB\fB-H\fR\fR
-.ad
-.sp .6
-.RS 4n
+Snapshots are displayed if the
+.Sy listsnaps
+property is
+.Cm on
+(the default is
+.Cm off Ns ).
+The following fields are displayed,
+.Sy name , used , available , referenced , mountpoint .
+.Bl -tag -width indent
+.It Fl r
+Recursively display any children of the dataset on the command line.
+.It Fl d Ar depth
+Recursively display any children of the dataset, limiting the recursion to
+.Ar depth .
+A depth of
+.Sy 1
+will display only the dataset and its direct children.
+.It Fl H
 Used for scripting mode. Do not print headers and separate fields by a single
 tab instead of arbitrary white space.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-r\fR\fR
-.ad
-.sp .6
-.RS 4n
-Recursively display any children of the dataset on the command line.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-d\fR \fIdepth\fR\fR
-.ad
-.sp .6
-.RS 4n
-Recursively display any children of the dataset, limiting the recursion to
-\fIdepth\fR. A depth of \fB1\fR will display only the dataset and its direct
-children.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-o\fR \fIproperty\fR\fR
-.ad
-.sp .6
-.RS 4n
+.It Fl o Ar property Ns Op , Ns Ar ...
 A comma-separated list of properties to display. The property must be:
-.RS +4
-.TP
-.ie t \(bu
-.el o
-One of the properties described in the "Native Properties" section
-.RE
-.RS +4
-.TP
-.ie t \(bu
-.el o
+.Bl -bullet -offset 2n
+.It
+One of the properties described in the
+.Qq Sx Native Properties
+section
+.It
 A user property
-.RE
-.RS +4
-.TP
-.ie t \(bu
-.el o
-The value \fBname\fR to display the dataset name
-.RE
-.RS +4
-.TP
-.ie t \(bu
-.el o
-The value \fBspace\fR to display space usage properties on file systems and
-volumes. This is a shortcut for specifying \fB-o
-name,avail,used,usedsnap,usedds,usedrefreserv,usedchild\fR \fB-t
-filesystem,volume\fR syntax.
-.RE
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-s\fR \fIproperty\fR\fR
-.ad
-.sp .6
-.RS 4n
+.It
+The value
+.Cm name
+to display the dataset name
+.It
+The value
+.Cm space
+to display space usage properties on file systems and volumes. This is a
+shortcut for specifying
+.Fl o
+.Sy name,avail,used,usedsnap,usedds,usedrefreserv,usedchild
+.Fl t
+.Sy filesystem,volume
+syntax.
+.El
+.It Fl t Ar type Ns Op , Ns Ar ...
+A comma-separated list of types to display, where
+.Ar type
+is one of
+.Sy filesystem , snapshot , volume , No or Sy all .
+For example, specifying
+.Fl o Cm snapshot
+displays only snapshots.
+.It Fl s Ar property
 A property for sorting the output by column in ascending order based on the
 value of the property. The property must be one of the properties described in
-the "Properties" section, or the special value \fBname\fR to sort by the
-dataset name. Multiple properties can be specified at one time using multiple
-\fB-s\fR property options. Multiple \fB-s\fR options are evaluated from left to
-right in decreasing order of importance.
-.sp
+the
+.Qq Sx Properties
+section, or the special value
+.Cm name
+to sort by the dataset name. Multiple properties can be specified at one time
+using multiple
+.Fl s
+property options. Multiple
+.Fl s
+options are evaluated from left to right in decreasing order of importance.
+.Pp
 The following is a list of sorting criteria:
-.RS +4
-.TP
-.ie t \(bu
-.el o
+.Bl -bullet -offset 2n
+.It
 Numeric types sort in numeric order.
-.RE
-.RS +4
-.TP
-.ie t \(bu
-.el o
+.It
 String types sort in alphabetical order.
-.RE
-.RS +4
-.TP
-.ie t \(bu
-.el o
+.It
 Types inappropriate for a row sort that row to the literal bottom, regardless
 of the specified ordering.
-.RE
-.RS +4
-.TP
-.ie t \(bu
-.el o
-If no sorting options are specified the existing behavior of \fBzfs list\fR is
-preserved.
-.RE
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-S\fR \fIproperty\fR\fR
-.ad
-.sp .6
-.RS 4n
-Same as the \fB-s\fR option, but sorts by property in descending order.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-t\fR \fItype\fR\fR
-.ad
-.sp .6
-.RS 4n
-A comma-separated list of types to display, where \fItype\fR is one of
-\fBfilesystem\fR, \fBsnapshot\fR , \fBvolume\fR, or \fBall\fR. For example,
-specifying \fB-t snapshot\fR displays only snapshots.
-.RE
-
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzfs set\fR \fIproperty\fR=\fIvalue\fR
-\fIfilesystem\fR|\fIvolume\fR|\fIsnapshot\fR ...\fR
-.ad
-.sp .6
-.RS 4n
+.It
+If no sorting options are specified the existing behavior of
+.Qq Nm Cm list
+is preserved.
+.El
+.It Fl S Ar property
+Same as the
+.Fl s
+option, but sorts by property in descending order.
+.El
+.It Xo
+.Nm
+.Cm set
+.Ar property Ns = Ns Ar value
+.Ar filesystem Ns | Ns Ar volume Ns | Ns Ar snapshot
+.Xc
+.Pp
 Sets the property to the given value for each dataset. Only some properties can
 be edited. See the "Properties" section for more information on what properties
 can be set and acceptable values. Numeric values can be specified as exact
-values, or in a human-readable form with a suffix of \fBB\fR, \fBK\fR, \fBM\fR,
-\fBG\fR, \fBT\fR, \fBP\fR, \fBE\fR, \fBZ\fR (for bytes, kilobytes, megabytes,
-gigabytes, terabytes, petabytes, exabytes, or zettabytes, respectively). User
-properties can be set on snapshots. For more information, see the "User
-Properties" section.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzfs get\fR [\fB-r\fR|\fB-d\fR \fIdepth\fR] [\fB-Hp\fR] [\fB-o\fR
-\fIfield\fR[,...] [\fB-s\fR \fIsource\fR[,...] "\fIall\fR" |
-\fIproperty\fR[,...] \fIfilesystem\fR|\fIvolume\fR|\fIsnapshot\fR ...\fR
-.ad
-.sp .6
-.RS 4n
+values, or in a human-readable form with a suffix of
+.Sy B , K , M , G , T , P , E , Z
+(for bytes, kilobytes, megabytes, gigabytes, terabytes, petabytes, exabytes, or
+zettabytes, respectively). User properties can be set on snapshots. For more
+information, see the
+.Qq Sx User Properties
+section.
+.It Xo
+.Nm
+.Cm get
+.Op Fl r Ns | Ns Fl d Ar depth
+.Op Fl Hp
+.Op Fl o Ar all | field Ns Op , Ns Ar ...
+.Op Fl s Ar source Ns Op , Ns Ar ...
+.Ar all | property Ns Op , Ns Ar ...
+.Ar filesystem Ns | Ns Ar volume Ns | Ns Ar snapshot
+.Xc
+.Pp
 Displays properties for the given datasets. If no datasets are specified, then
 the command displays properties for all datasets on the system. For each
 property, the following columns are displayed:
-.sp
-.in +2
-.nf
-    name      Dataset name
-     property  Property name
-     value     Property value
-     source    Property source. Can either be local, default,
-               temporary, inherited, or none (-).
-.fi
-.in -2
-.sp
-
-All columns are displayed by default, though this can be controlled by using
-the \fB-o\fR option. This command takes a comma-separated list of properties as
-described in the "Native Properties" and "User Properties" sections.
-.sp
-The special value \fBall\fR can be used to display all properties that apply to
-the given dataset's type (filesystem, volume, or snapshot).
-.sp
-.ne 2
-.na
-\fB\fB-r\fR\fR
-.ad
-.sp .6
-.RS 4n
+.Pp
+.Bl -hang -width "property" -offset indent -compact
+.It name
+Dataset name
+.It property
+Property name
+.It value
+Property value
+.It source
+Property source. Can either be local, default, temporary, inherited, or none
+(\&-).
+.El
+.Pp
+All columns except the
+.Sy RECEIVED
+column are displayed by default. The columns to display can be specified
+by using the
+.Fl o
+option. This command takes a comma-separated list of properties as described in
+the
+.Qq Sx Native Properties
+and
+.Qq Sx User Properties
+sections.
+.Pp
+The special value
+.Cm all
+can be used to display all properties that apply to the given dataset's type
+(filesystem, volume, or snapshot).
+.Bl -tag -width indent
+.It Fl r
 Recursively display properties for any children.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-d\fR \fIdepth\fR\fR
-.ad
-.sp .6
-.RS 4n
+.It Fl d Ar depth
 Recursively display any children of the dataset, limiting the recursion to
-\fIdepth\fR. A depth of \fB1\fR will display only the dataset and its direct
-children.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-H\fR\fR
-.ad
-.sp .6
-.RS 4n
+.Ar depth .
+A depth of
+.Sy 1
+will display only the dataset and its direct children.
+.It Fl H
 Display output in a form more easily parsed by scripts. Any headers are
 omitted, and fields are explicitly separated by a single tab instead of an
 arbitrary amount of space.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-o\fR \fIfield\fR\fR
-.ad
-.sp .6
-.RS 4n
-A comma-separated list of columns to display. \fBname,property,value,source\fR
-is the default value.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-s\fR \fIsource\fR\fR
-.ad
-.sp .6
-.RS 4n
+.It Fl p
+Display numbers in parseable (exact) values.
+.It Fl o Cm all | Ar field Ns Op , Ns Ar ...
+A comma-separated list of columns to display. Supported values are
+.Sy name,property,value,received,source .
+Default values are
+.Sy name,property,value,source .
+The keyword
+.Cm all
+specifies all columns.
+.It Fl s Ar source Ns Op , Ns Ar ...
 A comma-separated list of sources to display. Those properties coming from a
 source other than those in this list are ignored. Each source must be one of
-the following: \fBlocal,default,inherited,temporary,none\fR. The default value
-is all sources.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-p\fR\fR
-.ad
-.sp .6
-.RS 4n
-Display numbers in parseable (exact) values.
-.RE
-
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzfs inherit\fR [\fB-r\fR] \fIproperty\fR
-\fIfilesystem\fR|\fIvolume\fR|\fIsnapshot\fR ...\fR
-.ad
-.sp .6
-.RS 4n
+the following:
+.Sy local,default,inherited,temporary,received,none .
+The default value is all sources.
+.El
+.It Xo
+.Nm
+.Cm inherit
+.Op Fl rS
+.Ar property
+.Ar filesystem Ns | Ns Ar volume Ns | Ns Ar snapshot
+.Xc
+.Pp
 Clears the specified property, causing it to be inherited from an ancestor. If
 no ancestor has the property set, then the default value is used. See the
-"Properties" section for a listing of default values, and details on which
-properties can be inherited.
-.sp
-.ne 2
-.na
-\fB\fB-r\fR\fR
-.ad
-.sp .6
-.RS 4n
+.Qq Sx Properties
+section for a listing of default values, and details on which properties can be
+inherited.
+.Bl -tag -width indent
+.It Fl r
 Recursively inherit the given property for all children.
-.RE
-
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzfs upgrade\fR [\fB-v\fR]\fR
-.ad
-.sp .6
-.RS 4n
+.It Fl S
+For properties with a received value, revert to this value. This flag has no
+effect on properties that do not have a received value.
+.El
+.It Xo
+.Nm
+.Cm upgrade
+.Op Fl v
+.Xc
+.Pp
 Displays a list of file systems that are not the most recent version.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzfs upgrade\fR [\fB-r\fR] [\fB-V\fR \fIversion\fR] [\fB-a\fR |
-\fIfilesystem\fR]\fR
-.ad
-.sp .6
-.RS 4n
+.Bl -tag -width indent
+.It Fl v
+Displays
+.Tn ZFS
+filesystem versions supported by the current software. The current
+.Tn ZFS
+filesystem version and all previous supported versions are displayed, along
+with an explanation of the features provided with each version.
+.El
+.It Xo
+.Nm
+.Cm upgrade
+.Op Fl r
+.Op Fl V Ar version
+.Fl a | Ar filesystem
+.Xc
+.Pp
 Upgrades file systems to a new on-disk version. Once this is done, the file
 systems will no longer be accessible on systems running older versions of the
-software. \fBzfs send\fR streams generated from new snapshots of these file
-systems cannot be accessed on systems running older versions of the software.
-.sp
+software.
+.Qq Nm Cm send
+streams generated from new snapshots of these file systems cannot be accessed
+on systems running older versions of the software.
+.Pp
 In general, the file system version is independent of the pool version. See
-\fBzpool\fR(8) for information on the \fBzpool upgrade\fR command.
-.sp
+.Xr zpool 8
+for information on the
+.Nm zpool Cm upgrade
+command.
+.Pp
 In some cases, the file system version and the pool version are interrelated
 and the pool version must be upgraded before the file system version can be
 upgraded.
-.sp
-.ne 2
-.na
-\fB\fB-a\fR\fR
-.ad
-.sp .6
-.RS 4n
+.Bl -tag -width indent
+.It Fl r
+Upgrade the specified file system and all descendent file systems.
+.It Fl V Ar version
+Upgrade to the specified
+.Ar version .
+If the
+.Fl V
+flag is not specified, this command upgrades to the most recent version. This
+option can only be used to increase the version number, and only up to the most
+recent version supported by this software.
+.It Fl a
 Upgrade all file systems on all imported pools.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fIfilesystem\fR\fR
-.ad
-.sp .6
-.RS 4n
+.It Ar filesystem
 Upgrade the specified file system.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-r\fR\fR
-.ad
-.sp .6
-.RS 4n
-Upgrade the specified file system and all descendent file systems
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-V\fR \fIversion\fR\fR
-.ad
-.sp .6
-.RS 4n
-Upgrade to the specified \fIversion\fR. If the \fB-V\fR flag is not specified,
-this command upgrades to the most recent version. This option can only be used
-to increase the version number, and only up to the most recent version
-supported by this software.
-.RE
-
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzfs userspace\fR [\fB-niHp\fR] [\fB-o\fR \fIfield\fR[,...]] [\fB-sS\fR
-\fIfield\fR]... [\fB-t\fR \fItype\fR [,...]] \fIfilesystem\fR |
-\fIsnapshot\fR\fR
-.ad
-.sp .6
-.RS 4n
+.El
+.It Xo
+.Nm
+.Cm userspace
+.Op Fl niHp
+.Op Fl o Ar field Ns Op , Ns Ar ...
+.Op Fl sS Ar field
+.Ar ...
+.Op Fl t Ar type Ns Op , Ns Ar ...
+.Ar filesystem Ns | Ns Ar snapshot
+.Xc
+.Pp
 Displays space consumed by, and quotas on, each user in the specified
-filesystem or snapshot. This corresponds to the \fBuserused@\fR\fIuser\fR and
-\fBuserquota@\fR\fIuser\fR properties.
-.sp
-.ne 2
-.na
-\fB\fB-n\fR\fR
-.ad
-.sp .6
-.RS 4n
+filesystem or snapshot. This corresponds to the
+.Sy userused@ Ns Ar user
+and
+.Sy userquota@ Ns Ar user
+properties.
+.Bl -tag -width indent
+.It Fl n
 Print numeric ID instead of user/group name.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-H\fR\fR
-.ad
-.sp .6
-.RS 4n
+.It Fl H
 Do not print headers, use tab-delimited output.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-p\fR\fR
-.ad
-.sp .6
-.RS 4n
+.It Fl p
 Use exact (parseable) numeric output.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-o\fR \fIfield\fR[,...]\fR
-.ad
-.sp .6
-.RS 4n
+.It Fl o Ar field Ns Op , Ns Ar ...
 Display only the specified fields from the following set,
-\fBtype,name,used,quota\fR.The default is to display all fields.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-s\fR \fIfield\fR\fR
-.ad
-.sp .6
-.RS 4n
-Sort output by this field. The \fIs\fR and \fIS\fR flags may be specified
-multiple times to sort first by one field, then by another. The default is
-\fB-s type\fR \fB-s name\fR.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-S\fR \fIfield\fR\fR
-.ad
-.sp .6
-.RS 4n
-Sort by this field in reverse order. See \fB-s\fR.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-t\fR \fItype\fR[,...]\fR
-.ad
-.sp .6
-.RS 4n
+.Sy type,name,used,quota .
+The default is to display all fields.
+.It Fl s Ar field
+Sort output by this field. The
+.Fl s
+and
+.Fl S
+flags may be specified multiple times to sort first by one field, then by
+another. The default is
+.Fl s Cm type Fl s Cm name .
+.It Fl S Ar field
+Sort by this field in reverse order. See
+.Fl s .
+.It Fl t Ar type Ns Op , Ns Ar ...
 Print only the specified types from the following set,
-\fBall,posixuser,smbuser,posixgroup,smbgroup\fR.
-.sp
-The default is \fB-t posixuser,smbuser\fR
-.sp
+.Sy all,posixuser,smbuser,posixgroup,smbgroup .
+.Pp
+The default is
+.Fl t Cm posixuser,smbuser .
+.Pp
 The default can be changed to include group types.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-i\fR\fR
-.ad
-.sp .6
-.RS 4n
-Translate SID to POSIX ID. The POSIX ID may be ephemeral if no mapping exists.
-Normal POSIX interfaces (for example, \fBstat\fR(2), \fBls\fR \fB-l\fR) perform
-this translation, so the \fB-i\fR option allows the output from \fBzfs
-userspace\fR to be compared directly with those utilities. However, \fB-i\fR
-may lead to confusion if some files were created by an SMB user before a
-SMB-to-POSIX name mapping was established. In such a case, some files are owned
-by the SMB entity and some by the POSIX entity. However, the \fB-i\fR option
-will report that the POSIX entity has the total usage and quota for both.
-.RE
-
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzfs groupspace\fR [\fB-niHp\fR] [\fB-o\fR \fIfield\fR[,...]] [\fB-sS\fR
-\fIfield\fR]... [\fB-t\fR \fItype\fR [,...]] \fIfilesystem\fR |
-\fIsnapshot\fR\fR
-.ad
-.sp .6
-.RS 4n
+.It Fl i
+Translate SID to POSIX ID. This flag has currently no effect on
+.Fx .
+.El
+.It Xo
+.Nm
+.Cm groupspace
+.Op Fl niHp
+.Op Fl o Ar field Ns Op , Ns Ar ...
+.Op Fl sS Ar field
+.Ar ...
+.Op Fl t Ar type Ns Op , Ns Ar ...
+.Ar filesystem Ns | Ns Ar snapshot
+.Xc
+.Pp
 Displays space consumed by, and quotas on, each group in the specified
-filesystem or snapshot. This subcommand is identical to \fBzfs userspace\fR,
-except that the default types to display are \fB-t posixgroup,smbgroup\fR.
-.sp
-.in +2
-.nf
--
-.fi
-.in -2
-.sp
-
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzfs mount\fR\fR
-.ad
-.sp .6
-.RS 4n
-Displays all \fBZFS\fR file systems currently mounted.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzfs mount\fR [\fB-vO\fR] [\fB-o\fR \fIoptions\fR] \fB-a\fR |
-\fIfilesystem\fR\fR
-.ad
-.sp .6
-.RS 4n
-Mounts \fBZFS\fR file systems. Invoked automatically as part of the boot
-process.
-.sp
-.ne 2
-.na
-\fB\fB-o\fR \fIoptions\fR\fR
-.ad
-.sp .6
-.RS 4n
+filesystem or snapshot. This subcommand is identical to
+.Qq Nm Cm userspace ,
+except that the default types to display are
+.Fl t Sy posixgroup,smbgroup .
+.It Xo
+.Nm
+.Cm mount
+.Xc
+.Pp
+Displays all
+.Tn ZFS
+file systems currently mounted.
+.Bl -tag -width indent
+.It Fl f
+.El
+.It Xo
+.Nm
+.Cm mount
+.Op Fl vO
+.Op Fl o Ar property Ns Op , Ns Ar ...
+.Fl a | Ar filesystem
+.Xc
+.Pp
+Mounts
+.Tn ZFS
+file systems.
+.Bl -tag -width indent
+.It Fl v
+Report mount progress.
+.It Fl O
+Perform an overlay mount. Overlay mounts are not supported on
+.Fx .
+.It Fl o Ar property Ns Op , Ns Ar ...
 An optional, comma-separated list of mount options to use temporarily for the
-duration of the mount. See the "Temporary Mount Point Properties" section for
-details.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-O\fR\fR
-.ad
-.sp .6
-.RS 4n
-Perform an overlay mount. See \fBmount\fR(8) for more information.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-v\fR\fR
-.ad
-.sp .6
-.RS 4n
-Report mount progress.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-a\fR\fR
-.ad
-.sp .6
-.RS 4n
-Mount all available \fBZFS\fR file systems. Invoked automatically as part of
-the boot process.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fIfilesystem\fR\fR
-.ad
-.sp .6
-.RS 4n
+duration of the mount. See the
+.Qq Sx Temporary Mount Point Properties
+section for details.
+.It Fl a
+Mount all available
+.Tn ZFS
+file systems.
+This command may be executed on
+.Fx
+system startup by
+.Pa /etc/rc.d/zfs .
+For more information, see variable
+.Va zfs_enable
+in
+.Xr rc.conf 5 .
+.It Ar filesystem
 Mount the specified filesystem.
-.RE
-
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzfs unmount\fR [\fB-f\fR] \fB-a\fR | \fIfilesystem\fR|\fImountpoint\fR\fR
-.ad
-.sp .6
-.RS 4n
-Unmounts currently mounted \fBZFS\fR file systems. Invoked automatically as
-part of the shutdown process.
-.sp
-.ne 2
-.na
-\fB\fB-f\fR\fR
-.ad
-.sp .6
-.RS 4n
+.El
+.It Xo
+.Nm
+.Cm unmount
+.Op Fl f
+.Fl a | Ar filesystem Ns | Ns Ar mountpoint
+.Xc
+.Pp
+Unmounts currently mounted
+.Tn ZFS
+file systems.
+.Bl -tag -width indent
+.It Fl f
 Forcefully unmount the file system, even if it is currently in use.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-a\fR\fR
-.ad
-.sp .6
-.RS 4n
-Unmount all available \fBZFS\fR file systems. Invoked automatically as part of
-the boot process.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fIfilesystem\fR|\fImountpoint\fR\fR
-.ad
-.sp .6
-.RS 4n
+.It Fl a
+Unmount all available
+.Tn ZFS
+file systems.
+.It Ar filesystem | mountpoint
 Unmount the specified filesystem. The command can also be given a path to a
-\fBZFS\fR file system mount point on the system.
-.RE
-
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzfs share\fR \fB-a\fR | \fIfilesystem\fR\fR
-.ad
-.sp .6
-.RS 4n
-Shares available \fBZFS\fR file systems.
-.sp
-.ne 2
-.na
-\fB\fB-a\fR\fR
-.ad
-.sp .6
-.RS 4n
-Share all available \fBZFS\fR file systems. Invoked automatically as part of
-the boot process.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fIfilesystem\fR\fR
-.ad
-.sp .6
-.RS 4n
-Share the specified filesystem according to the \fBsharenfs\fR and
-\fBsharesmb\fR properties. File systems are shared when the \fBsharenfs\fR or
-\fBsharesmb\fR property is set.
-.RE
-
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzfs unshare\fR \fB-a\fR | \fIfilesystem\fR|\fImountpoint\fR\fR
-.ad
-.sp .6
-.RS 4n
-Unshares currently shared \fBZFS\fR file systems. This is invoked automatically
-as part of the shutdown process.
-.sp
-.ne 2
-.na
-\fB\fB-a\fR\fR
-.ad
-.sp .6
-.RS 4n
-Unshare all available \fBZFS\fR file systems. Invoked automatically as part of
-the boot process.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fIfilesystem\fR|\fImountpoint\fR\fR
-.ad
-.sp .6
-.RS 4n
+.Tn ZFS
+file system mount point on the system.
+.El
+.It Xo
+.Nm
+.Cm share
+.Fl a | Ar filesystem
+.Xc
+.Pp
+Shares
+.Tn ZFS
+file systems that have the
+.Sy sharenfs
+property set.
+.Bl -tag -width indent
+.It Fl a
+Share all
+.Tn ZFS
+file systems that have the
+.Sy sharenfs
+property set.
+This command may be executed on
+.Fx
+system startup by
+.Pa /etc/rc.d/zfs .
+For more information, see variable
+.Va zfs_enable
+in
+.Xr rc.conf 5 .
+.It Ar filesystem
+Share the specified filesystem according to the
+.Tn sharenfs
+property. File systems are shared when the
+.Tn sharenfs
+property is set.
+.El
+.It Xo
+.Nm
+.Cm unshare
+.Fl a | Ar filesystem Ns | Ns Ar mountpoint
+.Xc
+.Pp
+Unshares
+.Tn ZFS
+file systems that have the
+.Tn sharenfs
+property set.
+.Bl -tag -width indent
+.It Fl a
+Unshares
+.Tn ZFS
+file systems that have the
+.Sy sharenfs
+property set.
+This command may be executed on
+.Fx
+system shutdown by
+.Pa /etc/rc.d/zfs .
+For more information, see variable
+.Va zfs_enable
+in
+.Xr rc.conf 5 .
+.It Ar filesystem | mountpoint
 Unshare the specified filesystem. The command can also be given a path to a
-\fBZFS\fR file system shared on the system.
-.RE
-
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzfs send\fR [\fB-vR\fR] [\fB-\fR[\fBiI\fR] \fIsnapshot\fR]
-\fIsnapshot\fR\fR
-.ad
-.sp .6
-.RS 4n
-Creates a stream representation of the second \fIsnapshot\fR, which is written
-to standard output. The output can be redirected to a file or to a different
-system (for example, using \fBssh\fR(1). By default, a full stream is
-generated.
-.sp
-.ne 2
-.na
-\fB\fB-i\fR \fIsnapshot\fR\fR
-.ad
-.sp .6
-.RS 4n
-Generate an incremental stream from the first \fIsnapshot\fR to the second
-\fIsnapshot\fR. The incremental source (the first \fIsnapshot\fR) can be
-specified as the last component of the snapshot name (for example, the part
-after the \fB@\fR), and it is assumed to be from the same file system as the
-second \fIsnapshot\fR.
-.sp
+.Tn ZFS
+file system shared on the system.
+.El
+.It Xo
+.Nm
+.Cm send
+.Op Fl DnPpRrv
+.Op Fl i Ar snapshot | Fl I Ar snapshot
+.Ar snapshot
+.Xc
+.Pp
+Creates a stream representation of the last
+.Ar snapshot
+argument (not part of
+.Fl i
+or
+.Fl I Ns )
+which is written to standard output. The output can be redirected to
+a file or to a different system (for example, using
+.Xr ssh 1 Ns ).
+By default, a full stream is generated.
+.Bl -tag -width indent
+.It Fl i Ar snapshot
+Generate an incremental stream from the
+.Fl i Ar snapshot
+to the last
+.Ar snapshot .
+The incremental source (the
+.Fl i Ar snapshot Ns )
+can be specified as the last component of the snapshot name (for example, the
+part after the
+.Sy @ Ns ),
+and it is assumed to be from the same file system as the last
+.Ar snapshot .
+.Pp
 If the destination is a clone, the source may be the origin snapshot, which
-must be fully specified (for example, \fBpool/fs at origin\fR, not just
-\fB at origin\fR).
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-I\fR \fIsnapshot\fR\fR
-.ad
-.sp .6
-.RS 4n
-Generate a stream package that sends all intermediary snapshots from the first
-snapshot to the second snapshot. For example, \fB-I @a fs at d\fR is similar to
-\fB-i @a fs at b; -i @b fs at c; -i @c fs at d\fR. The incremental source snapshot may
-be specified as with the \fB-i\fR option.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-R\fR\fR
-.ad
-.sp .6
-.RS 4n
+must be fully specified (for example, 
+.Cm pool/fs at origin ,
+not just
+.Cm @origin Ns ).
+.It Fl I Ar snapshot
+Generate a stream package that sends all intermediary snapshots from the
+.Fl I Ar snapshot to the last
+.Ar snapshot . For example,
+.Ic -I @a fs at d
+is similar to
+.Ic -i @a fs at b; -i @b fs at c; -i @c fs at d .
+The incremental source snapshot may be specified as with the
+.Fl i
+option.
+.It Fl R
 Generate a replication stream package, which will replicate the specified
 filesystem, and all descendent file systems, up to the named snapshot. When
 received, all properties, snapshots, descendent file systems, and clones are
 preserved.
-.sp
-If the \fB-i\fR or \fB-I\fR flags are used in conjunction with the \fB-R\fR
+.Pp
+If the
+.Fl i
+or
+.Fl I
+flags are used in conjunction with the
+.Fl R
 flag, an incremental replication stream is generated. The current values of
 properties, and current snapshot and file system names are set when the stream
-is received. If the \fB-F\fR flag is specified when this stream is received,
-snapshots and file systems that do not exist on the sending side are destroyed.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-v\fR\fR
-.ad
-.sp .6
-.RS 4n
+is received. If the
+.Fl F
+flag is specified when this stream is received, snapshots and file systems that
+ do not exist on the sending side are destroyed.
+.It Fl D
+Generate a deduplicated stream. Blocks which would have been sent multiple
+times in the send stream will only be sent once.  The receiving system must
+also support this feature to recieve a deduplicated stream.  This flag can
+be used regardless of the dataset's
+.Sy dedup
+property, but performance will be much better if the filesystem uses a
+dedup-capable checksum (eg.
+.Sy sha256 Ns ).
+.It Fl r
+Recursively send all descendant snapshots.  This is similar to the
+.Fl R
+flag, but information about deleted and renamed datasets is not included, and
+property information is only included if the
+.Fl p
+flag is specified.
+.It Fl p
+Include the dataset's properties in the stream. This flag is implicit when
+.Fl R
+is specified. The receiving system must also support this feature.
+.It Fl n
+Do a dry-run ("No-op") send.  Do not generate any actual send data.  This is
+useful in conjunction with the
+.Fl v
+or
+.Fl P
+flags to determine what data will be sent.
+.It Fl P
+Print machine-parsable verbose information about the stream package generated.
+.It Fl v
 Print verbose information about the stream package generated.
-.RE
-
+.El
+.Pp
 The format of the stream is committed. You will be able to receive your streams
-on future versions of \fBZFS\fR.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzfs receive\fR [\fB-vnFu\fR]
-\fIfilesystem\fR|\fIvolume\fR|\fIsnapshot\fR\fR
-.ad
-.br
-.na
-\fB\fBzfs receive\fR [\fB-vnFu\fR] \fB-d\fR \fIfilesystem\fR\fR
-.ad
-.sp .6
-.RS 4n
+on future versions of
+.Tn ZFS .
+.It Xo
+.Nm
+.Cm receive
+.Op Fl vnFu
+.Ar filesystem Ns | Ns Ar volume Ns | Ns Ar snapshot
+.Xc
+.It Xo
+.Nm
+.Cm receive
+.Op Fl vnFu
+.Op Fl d | e
+.Ar filesystem
+.Xc
+.Pp
 Creates a snapshot whose contents are as specified in the stream provided on
 standard input. If a full stream is received, then a new file system is created
-as well. Streams are created using the \fBzfs send\fR subcommand, which by
-default creates a full stream. \fBzfs recv\fR can be used as an alias for
-\fBzfs receive\fR.
-.sp
+as well. Streams are created using the
+.Qq Nm Cm send
+subcommand, which by default creates a full stream.
+.Qq Nm Cm recv
+can be used as an alias for
+.Qq Nm Cm receive .
+.Pp
 If an incremental stream is received, then the destination file system must
 already exist, and its most recent snapshot must match the incremental stream's
-source. For \fBzvols\fR, the destination device link is destroyed and
-recreated, which means the \fBzvol\fR cannot be accessed during the
-\fBreceive\fR operation.
-.sp
+source. For
+.Sy zvol Ns s,
+the destination device link is destroyed and recreated, which means the
+.Sy zvol
+cannot be accessed during the
+.Sy receive
+operation.
+.Pp
 When a snapshot replication package stream that is generated by using the
-\fBzfs send\fR \fB-R\fR command is  received, any snapshots that do not exist
-on the sending location are destroyed by using the \fBzfs destroy\fR \fB-d\fR
+.Qq Nm Cm send Fl R
+command is received, any snapshots that do not exist on the sending location
+are destroyed by using the
+.Qq Nm Cm destroy Fl d
 command.
-.sp
+.Pp
 The name of the snapshot (and file system, if a full stream is received) that
-this subcommand creates depends on the argument type and the \fB-d\fR option.
-.sp
-If the argument is a snapshot name, the specified \fIsnapshot\fR is created. If
-the argument is a file system or volume name, a snapshot with the same name as
-the sent snapshot is created within the specified \fIfilesystem\fR or
-\fIvolume\fR. If the \fB-d\fR option is specified, the snapshot name is
-determined by appending the sent snapshot's name to the specified
-\fIfilesystem\fR. If the \fB-d\fR option is specified, any required file
-systems within the specified one are created.
-.sp
-.ne 2
-.na
-\fB\fB-d\fR\fR
-.ad
-.sp .6
-.RS 4n
-Use the name of the sent snapshot to determine the name of the new snapshot as
-described in the paragraph above.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-u\fR\fR
-.ad
-.sp .6
-.RS 4n
+this subcommand creates depends on the argument type and the
+.Fl d
+or
+.Fl e
+option.
+.Pp
+If the argument is a snapshot name, the specified
+.Ar snapshot
+is created. If the argument is a file system or volume name, a snapshot with
+the same name as the sent snapshot is created within the specified
+.Ar filesystem
+or
+.Ar volume .
+If the
+.Fl d
+or
+.Fl e
+option is specified, the snapshot name is determined by appending the sent
+snapshot's name to the specified
+.Ar filesystem .
+If the
+.Fl d
+option is specified, all but the pool name of the sent snapshot path is
+appended (for example,
+.Sy b/c at 1
+appended from sent snapshot
+.Sy a/b/c at 1 Ns ),
+and if the
+.Fl e
+option is specified, only the tail of the sent snapshot path is appended (for
+example,
+.Sy c at 1
+appended from sent snapshot
+.Sy a/b/c at 1 Ns ).
+In the case of
+.Fl d ,
+any file systems needed to replicate the path of the sent snapshot are created
+within the specified file system.
+.Bl -tag -width indent
+.It Fl d
+Use the full sent snapshot path without the first element (without pool name)
+to determine the name of the new snapshot as described in the paragraph above.
+.It Fl e
+Use only the last element of the sent snapshot path to determine the name of
+the new snapshot as described in the paragraph above.
+.It Fl u
 File system that is associated with the received stream is not mounted.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-v\fR\fR
-.ad
-.sp .6
-.RS 4n
+.It Fl v
 Print verbose information about the stream and the time required to perform the
 receive operation.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-n\fR\fR
-.ad
-.sp .6
-.RS 4n
+.It Fl n
 Do not actually receive the stream. This can be useful in conjunction with the
-\fB-v\fR option to verify the name the receive operation would use.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-F\fR\fR
-.ad
-.sp .6
-.RS 4n
+.It Fl v
+option to verify the name the receive operation would use.
+.It Fl F
 Force a rollback of the file system to the most recent snapshot before
 performing the receive operation. If receiving an incremental replication
-stream (for example, one generated by \fBzfs send -R -[iI]\fR), destroy
-snapshots and file systems that do not exist on the sending side.
-.RE
-
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzfs allow\fR \fIfilesystem\fR | \fIvolume\fR\fR
-.ad
-.sp .6
-.RS 4n
+stream (for example, one generated by
+.Qq Nm Cm send Fl R Fi iI Ns ) ,
+destroy snapshots and file systems that do not exist on the sending side.
+.El
+.It Xo
+.Nm
+.Cm allow
+.Ar filesystem Ns | Ns Ar volume
+.Xc
+.Pp
 Displays permissions that have been delegated on the specified filesystem or
-volume. See the other forms of \fBzfs allow\fR for more information.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzfs allow\fR [\fB-ldug\fR] "\fIeveryone\fR"|\fIuser\fR|\fIgroup\fR[,...]
-\fIperm\fR|@\fIsetname\fR[,...] \fIfilesystem\fR| \fIvolume\fR\fR
-.ad
-.br
-.na
-\fB\fBzfs allow\fR [\fB-ld\fR] \fB-e\fR \fIperm\fR|@\fIsetname\fR[,...]
-\fIfilesystem\fR | \fIvolume\fR\fR
-.ad
-.sp .6
-.RS 4n
-Delegates \fBZFS\fR administration permission for the file systems to
-non-privileged users.
-.sp
-.ne 2
-.na
-\fB[\fB-ug\fR] "\fIeveryone\fR"|\fIuser\fR|\fIgroup\fR[,...]\fR
-.ad
-.sp .6
-.RS 4n
+volume. See the other forms of
+.Qq Nm Cm allow
+for more information.
+.It Xo
+.Nm
+.Cm allow
+.Op Fl ldug
+.Cm everyone Ns | Ns Ar user Ns | Ns Ar group Ns Op , Ns Ar ...
+.Ar perm Ns | Ns Ar @setname Ns Op , Ns Ar ...
+.Ar filesystem Ns | Ns Ar volume
+.Xc
+.It Xo
+.Nm
+.Cm allow
+.Op Fl ld
+.Fl e
+.Ar perm Ns | Ns Ar @setname Ns Op , Ns Ar ...
+.Ar filesystem Ns | Ns Ar volume
+.Xc
+.Pp
+Delegates
+.Tn ZFS
+administration permission for the file systems to non-privileged users.
+.Bl -tag -width indent
+.It Xo
+.Op Fl ug
+.Cm everyone Ns | Ns Ar user Ns | Ns Ar group Ns Op , Ns Ar ...
+.Xc
 Specifies to whom the permissions are delegated. Multiple entities can be
-specified as a comma-separated list. If neither of the \fB-ug\fR options are
-specified, then the argument is interpreted preferentially as the keyword
-"everyone", then as a user name, and lastly as a group name. To specify a user
-or group named "everyone", use the \fB-u\fR or \fB-g\fR options. To specify a
-group with the same name as a user, use the \fB-g\fR options.
-.RE
-
-.sp
-.ne 2
-.na
-\fB[\fB-e\fR] \fIperm\fR|@\fIsetname\fR[,...]\fR
-.ad
-.sp .6
-.RS 4n
+specified as a comma-separated list. If neither of the
+.Fl ug
+options are specified, then the argument is interpreted preferentially as the
+keyword "everyone", then as a user name, and lastly as a group name. To specify
+a user or group named "everyone", use the
+.Fl u
+or
+.Fl g
+options. To specify a group with the same name as a user, use the
+.Fl g
+option.
+.It Xo
+.Op Fl e
+.Ar perm Ns | Ns Ar @setname Ns Op , Ns Ar ...
+.Xc
 Specifies that the permissions be delegated to "everyone." Multiple permissions
 may be specified as a comma-separated list. Permission names are the same as
-\fBZFS\fR subcommand and property names. See the property list below. Property
-set names, which begin with an at sign (\fB@\fR) , may be specified. See the
-\fB-s\fR form below for details.
-.RE
-
-.sp
-.ne 2
-.na
-\fB[\fB-ld\fR] \fIfilesystem\fR|\fIvolume\fR\fR
-.ad
-.sp .6
-.RS 4n
-Specifies where the permissions are delegated. If neither of the \fB-ld\fR
+.Tn ZFS
+subcommand and property names. See the property list below. Property set names,
+which begin with an at sign
+.Pq Sy @ ,
+may be specified. See the
+.Fl s
+form below for details.
+.It Xo
+.Op Fl ld
+.Ar filesystem Ns | Ns Ar volume
+.Xc
+Specifies where the permissions are delegated. If neither of the
+.Fl ld
 options are specified, or both are, then the permissions are allowed for the
-file system or volume, and all of its descendents. If only the \fB-l\fR option
-is used, then is allowed "locally" only for the specified file system. If only
-the \fB-d\fR option is used, then is allowed only for the descendent file
-systems.
-.RE
-
-.RE
-
-.sp
-.LP
-Permissions are generally the ability to use a \fBZFS\fR subcommand or change a
-\fBZFS\fR property. The following permissions are available:
-.sp
-.in +2
-.nf
-NAME             TYPE           NOTES
-allow            subcommand     Must also have the permission that is being
-                                allowed
-clone            subcommand     Must also have the 'create' ability and 'mount'
-                                ability in the origin file system
-create           subcommand     Must also have the 'mount' ability
-destroy          subcommand     Must also have the 'mount' ability
-mount            subcommand     Allows mount/umount of ZFS datasets
-promote          subcommand     Must also have the 'mount'
-                                and 'promote' ability in the origin file system
-receive          subcommand     Must also have the 'mount' and 'create' ability
-rename           subcommand     Must also have the 'mount' and 'create'
-                                ability in the new parent
-rollback         subcommand     Must also have the 'mount' ability
-send             subcommand
-share            subcommand     Allows sharing file systems over NFS or SMB
-                                protocols
-snapshot         subcommand     Must also have the 'mount' ability
-groupquota       other          Allows accessing any groupquota at ... property
-groupused        other          Allows reading any groupused at ... property
-userprop         other          Allows changing any user property
-userquota        other          Allows accessing any userquota at ... property
-userused         other          Allows reading any userused at ... property
-
-aclinherit       property
-aclmode          property
-atime            property
-canmount         property
-casesensitivity  property
-checksum         property
-compression      property
-copies           property
-devices          property
-exec             property
-jailed           property
-mountpoint       property
-nbmand           property
-normalization    property
-primarycache     property
-quota            property
-readonly         property
-recordsize       property
-refquota         property
-refreservation   property
-reservation      property
-secondarycache   property
-setuid           property
-sharenfs         property
-sharesmb         property
-snapdir          property
-utf8only         property
-version          property
-volblocksize     property
-volsize          property
-vscan            property
-xattr            property
-.fi
-.in -2
-.sp
-
-.sp
-.ne 2
-.na
-\fB\fBzfs allow\fR \fB-c\fR \fIperm\fR|@\fIsetname\fR[,...]
-\fIfilesystem\fR|\fIvolume\fR\fR
-.ad
-.sp .6
-.RS 4n
+file system or volume, and all of its descendents. If only the
+.Fl l
+option is used, then is allowed "locally" only for the specified file system.
+If only the
+.Fl d
+option is used, then is allowed only for the descendent file systems.
+.El
+.Pp
+Permissions are generally the ability to use a
+.Tn ZFS
+subcommand or change a
+.Tn ZFS
+property. The following permissions are available:
+.Bl -column -offset 4n "secondarycache" "subcommand"
+.It NAME Ta TYPE Ta NOTES
+.It Xo allow Ta subcommand Ta Must
+also have the permission that is being allowed
+.Xc
+.It Xo clone Ta subcommand Ta Must
+also have the 'create' ability and 'mount' ability in the origin file system
+.Xc
+.It create Ta subcommand Ta Must also have the 'mount' ability
+.It destroy Ta subcommand Ta Must also have the 'mount' ability
+.It hold Ta subcommand Ta Allows adding a user hold to a snapshot
+.It mount Ta subcommand Ta Allows mount/umount of Tn ZFS No datasets
+.It Xo promote Ta subcommand Ta Must
+also have the 'mount' and 'promote' ability in the origin file system
+.Xc
+.It receive Ta subcommand Ta Must also have the 'mount' and 'create' ability
+.It Xo release Ta subcommand Ta Allows
+releasing a user hold which might destroy the snapshot
+.Xc
+.It Xo rename Ta subcommand Ta Must
+also have the 'mount' and 'create' ability in the new parent
+.Xc
+.It rollback Ta subcommand Ta Must also have the 'mount' ability
+.It send Ta subcommand
+.It share Ta subcommand Ta Allows Xo
+sharing file systems over the
+.Tn NFS
+protocol
+.Xc
+.It snapshot Ta subcommand Ta Must also have the 'mount' ability
+.It groupquota Ta other Ta Allows accessing any groupquota at ... property
+.It groupused Ta other Ta Allows reading any groupused at ... property
+.It userprop Ta other Ta Allows changing any user property
+.It userquota Ta other Ta Allows accessing any userquota at ... property
+.It userused Ta other Ta Allows reading any userused at ... property
+.It  Ta 
+.It aclinherit Ta property
+.It aclmode Ta property
+.It atime Ta property
+.It canmount Ta property
+.It casesensitivity Ta property
+.It checksum Ta property
+.It compression Ta property
+.It copies Ta property
+.It dedup Ta property
+.It devices Ta property
+.It exec Ta property
+.It logbias Ta property
+.It jailed Ta property
+.It mlslabel Ta property
+.It mountpoint Ta property
+.It nbmand Ta property
+.It normalization Ta property
+.It primarycache Ta property
+.It quota Ta property
+.It readonly Ta property
+.It recordsize Ta property
+.It refquota Ta property
+.It refreservation Ta property
+.It reservation Ta property
+.It secondarycache Ta property
+.It setuid Ta property
+.It sharenfs Ta property
+.It sharesmb Ta property
+.It snapdir Ta property
+.It sync Ta property
+.It utf8only Ta property
+.It version Ta property
+.It volblocksize Ta property
+.It volsize Ta property
+.It vscan Ta property
+.It xattr Ta property
+.El
+.It Xo
+.Nm
+.Cm allow
+.Fl c
+.Ar perm Ns | Ns Ar @setname Ns Op , Ns Ar ...
+.Ar filesystem Ns | Ns Ar volume
+.Xc
+.Pp
 Sets "create time" permissions. These permissions are granted (locally) to the
 creator of any newly-created descendent file system.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzfs allow\fR \fB-s\fR @\fIsetname\fR \fIperm\fR|@\fIsetname\fR[,...]
-\fIfilesystem\fR|\fIvolume\fR\fR
-.ad
-.sp .6
-.RS 4n
+.It Xo
+.Nm
+.Cm allow
+.Fl s
+.Ar @setname
+.Ar perm Ns | Ns Ar @setname Ns Op , Ns Ar ...
+.Ar filesystem Ns | Ns Ar volume
+.Xc
+.Pp
 Defines or adds permissions to a permission set. The set can be used by other
-\fBzfs allow\fR commands for the specified file system and its descendents.
-Sets are evaluated dynamically, so changes to a set are immediately reflected.
-Permission sets follow the same naming restrictions as ZFS file systems, but
-the name must begin with an "at sign" (\fB@\fR), and can be no more than 64
-characters long.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzfs unallow\fR [\fB-rldug\fR]
-"\fIeveryone\fR"|\fIuser\fR|\fIgroup\fR[,...]
-[\fIperm\fR|@\fIsetname\fR[, ...]] \fIfilesystem\fR|\fIvolume\fR\fR
-.ad
-.br
-.na
-\fB\fBzfs unallow\fR [\fB-rld\fR] \fB-e\fR [\fIperm\fR|@\fIsetname\fR [,...]]
-\fIfilesystem\fR|\fIvolume\fR\fR
-.ad
-.br
-.na
-\fB\fBzfs unallow\fR [\fB-r\fR] \fB-c\fR [\fIperm\fR|@\fIsetname\fR[,...]]\fR
-.ad
-.br
-.na
-\fB\fIfilesystem\fR|\fIvolume\fR\fR
-.ad
-.sp .6
-.RS 4n
-Removes permissions that were granted with the \fBzfs allow\fR command. No
-permissions are explicitly denied, so other permissions granted are still in
-effect. For example, if the permission is granted by an ancestor. If no
-permissions are specified, then all permissions for the specified \fIuser\fR,
-\fIgroup\fR, or \fIeveryone\fR are removed. Specifying "everyone" (or using the
-\fB-e\fR option) only removes the permissions that were granted to "everyone",
-not all permissions for every user and group. See the \fBzfs allow\fR command
-for a description of the \fB-ldugec\fR options.
-.sp
-.ne 2
-.na
-\fB\fB-r\fR\fR
-.ad
-.sp .6
-.RS 4n
+.Qq Nm Cm allow
+commands for the specified file system and its descendents. Sets are evaluated
+dynamically, so changes to a set are immediately reflected. Permission sets
+follow the same naming restrictions as ZFS file systems, but the name must
+begin with an "at sign"
+.Pq Sy @ ,
+and can be no more than 64 characters long.
+.It Xo
+.Nm
+.Cm unallow
+.Op Fl rldug
+.Cm everyone Ns | Ns Ar user Ns | Ns Ar group Ns Op , Ns Ar ...
+.Op Ar perm Ns | Ns Ar @setname Ns Op , Ns Ar ...
+.Ar filesystem Ns | Ns Ar volume
+.Xc
+.It Xo
+.Nm
+.Cm unallow
+.Op Fl rld
+.Fl e
+.Op Ar perm Ns | Ns Ar @setname Ns Op , Ns Ar ...
+.Ar filesystem Ns | Ns Ar volume
+.Xc
+.It Xo
+.Nm
+.Cm unallow
+.Op Fl r
+.Fl c
+.Op Ar perm Ns | Ns Ar @setname Ns Op , Ns Ar ...
+.Ar filesystem Ns | Ns Ar volume
+.Xc
+.Pp
+Removes permissions that were granted with the
+.Qq Nm Cm allow
+command. No permissions are explicitly denied, so other permissions granted are
+still in effect. For example, if the permission is granted by an ancestor. If
+no permissions are specified, then all permissions for the specified
+.Ar user , group , No or Ar everyone
+are removed. Specifying "everyone" (or using the
+.Fl e
+option) only removes the permissions that were granted to "everyone",
+not all permissions for every user and group. See the
+.Qq Nm Cm allow
+command for a description of the
+.Fl ldugec
+options.
+.Bl -tag -width indent
+.It Fl r
 Recursively remove the permissions from this file system and all descendents.
-.RE
-
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzfs unallow\fR [\fB-r\fR] \fB-s\fR @\fIsetname\fR
-[\fIperm\fR|@\fIsetname\fR[,...]]\fR
-.ad
-.br
-.na
-\fB\fIfilesystem\fR|\fIvolume\fR\fR
-.ad
-.sp .6
-.RS 4n
+.El
+.It Xo
+.Nm
+.Cm unallow
+.Op Fl r
+.Fl s
+.Ar @setname
+.Ar perm Ns | Ns Ar @setname Ns Op , Ns Ar ...
+.Ar filesystem Ns | Ns Ar volume
+.Xc
+.Pp
 Removes permissions from a permission set. If no permissions are specified,
 then all permissions are removed, thus removing the set entirely.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzfs hold\fR [\fB-r\fR] \fItag\fR \fIsnapshot\fR...\fR
-.ad
-.sp .6
-.RS 4n
-Adds a single reference, named with the \fItag\fR argument, to the specified
-snapshot or snapshots. Each snapshot has its own tag namespace, and tags must
-be unique within that space.
-.sp
+.It Xo
+.Nm
+.Cm hold
+.Op Fl r
+.Ar tag snapshot ...
+.Xc
+.Pp
+Adds a single reference, named with the
+.Ar tag
+argument, to the specified snapshot or snapshots. Each snapshot has its own tag
+namespace, and tags must be unique within that space.
+.Pp
 If a hold exists on a snapshot, attempts to destroy that snapshot by using the
-\fBzfs destroy\fR command return \fBEBUSY\fR.
-.sp
-.ne 2
-.na
-\fB\fB-r\fR\fR
-.ad
-.sp .6
-.RS 4n
+.Qq Nm Cm destroy
+command returns
+.Em EBUSY .
+.Bl -tag -width indent
+.It Fl r
 Specifies that a hold with the given tag is applied recursively to the
 snapshots of all descendent file systems.
-.RE
-
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzfs holds\fR [\fB-r\fR] \fIsnapshot\fR...\fR
-.ad
-.sp .6
-.RS 4n
+.El
+.It Xo
+.Nm
+.Cm holds
+.Op Fl r
+.Ar snapshot ...
+.Xc
+.Pp
 Lists all existing user references for the given snapshot or snapshots.
-.sp
-.ne 2
-.na
-\fB\fB-r\fR\fR
-.ad
-.sp .6
-.RS 4n
+.Bl -tag -width indent
+.It Fl r
 Lists the holds that are set on the named descendent snapshots, in addition to
 listing the holds on the named snapshot.
-.RE
-
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzfs release\fR [\fB-r\fR] \fItag\fR \fIsnapshot\fR...\fR
-.ad
-.sp .6
-.RS 4n
-Removes a single reference, named with the \fItag\fR argument, from the
-specified snapshot or snapshots. The tag must already exist for each snapshot.
-.sp
-If a hold exists on a snapshot, attempts to destroy that snapshot by using the
-\fBzfs destroy\fR command return \fBEBUSY\fR.
-.sp
-.ne 2
-.na
-\fB\fB-r\fR\fR
-.ad
-.sp .6
-.RS 4n
+.El
+.It Xo
+.Nm
+.Cm release
+.Op Fl r
+.Ar tag snapshot ...
+.Xc
+.Pp
+Removes a single reference, named with the
+.Ar tag
+argument, from the specified snapshot or snapshots. The tag must already exist
+for each snapshot.
+.Bl -tag -width indent
+.It Fl r
 Recursively releases a hold with the given tag on the snapshots of all
 descendent file systems.
-.RE
-
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzfs jail\fR \fIjailid\fR \fIfilesystem\fR\fR
-.ad
-.sp .6
-.RS 4n
-Attaches the given file system to the given jail. From now on this file system
-tree can be managed from within a jail if the "\fBjailed\fR" property has been
-set. To use this functionality, sysctl \fBsecurity.jail.enforce_statfs\fR
-should be set to 0 and sysctl \fBsecurity.jail.mount_allowed\fR should be set
-to 1.
-.RE
-
-.sp
-.ne 2
-.mk
-.na
-\fB\fBzfs unjail\fR \fIjailid\fR \fIfilesystem\fR\fR
-.ad
-.sp .6
-.RS 4n
-Detaches the given file system from the given jail.
-.RE
-
-.RE
-
-.SH EXAMPLES
-.LP
-\fBExample 1 \fRCreating a ZFS File System Hierarchy
-.sp
-.LP
-The following commands create a file system named \fBpool/home\fR and a file
-system named \fBpool/home/bob\fR. The mount point \fB/export/home\fR is set for
-the parent file system, and is automatically inherited by the child file
-system.
-
-.sp
-.in +2
-.nf
-# \fBzfs create pool/home\fR
-# \fBzfs set mountpoint=/export/home pool/home\fR
-# \fBzfs create pool/home/bob\fR
-.fi
-.in -2
-.sp
-
-.LP
-\fBExample 2 \fRCreating a ZFS Snapshot
-.sp
-.LP
-The following command creates a snapshot named \fByesterday\fR. This snapshot
-is mounted on demand in the \fB\&.zfs/snapshot\fR directory at the root of the
-\fBpool/home/bob\fR file system.
-
-.sp
-.in +2
-.nf
-# \fBzfs snapshot pool/home/bob at yesterday\fR
-.fi
-.in -2
-.sp
-
-.LP
-\fBExample 3 \fRCreating and Destroying Multiple Snapshots
-.sp
-.LP
-The following command creates snapshots named \fByesterday\fR of
-\fBpool/home\fR and all of its descendent file systems. Each snapshot is
-mounted on demand in the \fB\&.zfs/snapshot\fR directory at the root of its
-file system. The second command destroys the newly created snapshots.
-
-.sp
-.in +2
-.nf
-# \fBzfs snapshot -r pool/home at yesterday\fR
-# \fBzfs destroy -r pool/home at yesterday\fR
-.fi
-.in -2
-.sp
-
-.LP
-\fBExample 4 \fRDisabling and Enabling File System Compression
-.sp
-.LP
-The following command disables the \fBcompression\fR property for all file
-systems under \fBpool/home\fR. The next command explicitly enables
-\fBcompression\fR for \fBpool/home/anne\fR.
-
-.sp
-.in +2
-.nf
-# \fBzfs set compression=off pool/home\fR
-# \fBzfs set compression=on pool/home/anne\fR
-.fi
-.in -2
-.sp
-
-.LP
-\fBExample 5 \fRListing ZFS Datasets
-.sp
-.LP
+.El
+.It Xo
+.Nm
+.Cm diff
+.Op Fl FHt
+.Ar snapshot
+.Op Ar snapshot Ns | Ns Ar filesystem
+.Xc
+.Pp
+Describes differences between a snapshot and a successor dataset. The
+successor dataset can be a later snapshot or the current filesystem.
+.Pp
+The changed files are displayed including the change type. The change type
+is displayed ussing a single character. If a file or directory was renamed,
+the old and the new names are displayed.
+.Pp
+The following change types can be displayed:
+.Pp
+.Bl -column -offset indent "CHARACTER" "CHANGE TYPE"
+.It CHARACTER Ta CHANGE TYPE
+.It \&+ Ta file was added
+.It \&- Ta file was removed
+.It \&M Ta file was modified
+.It \&R Ta file was renamed
+.El
+.Bl -tag -width indent
+.It Fl F
+Display a single letter for the file type in second to last column.
+.Pp
+The following file types can be displayed:
+.Pp
+.Bl -column -offset indent "CHARACTER" "FILE TYPE"
+.It CHARACTER Ta FILE TYPE
+.It \&F Ta file
+.It \&/ Ta directory
+.It \&B Ta block device
+.It \&@ Ta symbolic link
+.It \&= Ta socket
+.It \&> Ta door (not supported on Fx Ns )
+.It \&| Ta FIFO (not supported on Fx Ns )
+.It \&P Ta event portal (not supported on Fx Ns )
+.El
+.It Fl H
+Machine-parseable output, fields separated a tab character.
+.It Fl t
+Display a change timestamp in the first column.
+.El
+.It Xo
+.Nm
+.Cm jail
+.Ar jailid filesystem
+.Xc
+.Pp
+Attaches the specified
+.Ar filesystem
+to the jail identified by JID
+.Ar jailid .
+From now on this file system tree can be managed from within a jail if the
+.Sy jailed
+property has been set. To use this functionality, the jail needs the
+.Va enforce_statfs
+parameter set to
+.Sy 0
+and the
+.Va allow.mount
+parameter set to
+.Sy 1 .
+.Pp
+See
+.Xr jail 8
+for more information on managing jails and configuring the parameters above.
+.It Xo
+.Nm
+.Cm unjail
+.Ar jailid filesystem
+.Xc
+.Pp
+Detaches the specified
+.Ar filesystem
+from the jail identified by JID
+.Ar jailid .
+.El
+.Sh EXAMPLES
+.Bl -tag -width 0n
+.It Sy Example 1 No Creating a Tn ZFS No File System Hierarchy
+.Pp
+The following commands create a file system named
+.Em pool/home
+and a file system named
+.Em pool/home/bob .
+The mount point
+.Pa /home
+is set for the parent file system, and is automatically inherited by the child
+file system.
+.Bd -literal -offset 2n
+.Li # Ic zfs create pool/home
+.Li # Ic zfs set mountpoint=/home pool/home
+.Li # Ic zfs create pool/home/bob
+.Ed
+.It Sy Example 2 No Creating a Tn ZFS No Snapshot
+.Pp
+The following command creates a snapshot named
+.Sy yesterday .
+This snapshot is mounted on demand in the
+.Pa \&.zfs/snapshot
+directory at the root of the
+.Em pool/home/bob
+file system.
+.Bd -literal -offset 2n
+.Li # Ic zfs snapshot pool/home/bob at yesterday
+.Ed
+.It Sy Example 3 No Creating and Destroying Multiple Snapshots
+.Pp
+The following command creates snapshots named
+.Em yesterday
+of
+.Em pool/home
+and all of its descendent file systems. Each snapshot is mounted on demand in
+the
+.Pa \&.zfs/snapshot
+directory at the root of its file system. The second command destroys the newly
+created snapshots.
+.Bd -literal -offset 2n
+.Li # Ic zfs snapshot -r pool/home at yesterday
+.Li # Ic zfs destroy -r pool/home at yesterday
+.Ed
+.It Sy Example 4 No Disabling and Enabling File System Compression
+.Pp
+The following command disables the
+.Sy compression
+property for all file systems under
+.Em pool/home .
+The next command explicitly enables
+.Sy compression
+for
+.Em pool/home/anne .
+.Bd -literal -offset 2n
+.Li # Ic zfs set compression=off pool/home
+.Li # Ic zfs set compression=on pool/home/anne
+.Ed
+.It Sy Example 5 No Listing Tn ZFS No Datasets
+.Pp
 The following command lists all active file systems and volumes in the system.
-Snapshots are displayed if the \fBlistsnaps\fR property is \fBon\fR. The
-default is \fBoff\fR. See \fBzpool\fR(8) for more information on pool
-properties.
-
-.sp
-.in +2
-.nf
-# \fBzfs list\fR
+Snapshots are displayed if the
+.Sy listsnaps
+property is
+.Cm on .
+The default is 
+.Cm off .
+See
+.Xr zpool 8
+for more information on pool properties.
+.Bd -literal -offset 2n
+.Li # Ic zfs list
    NAME                      USED  AVAIL  REFER  MOUNTPOINT
    pool                      450K   457G    18K  /pool
-   pool/home                 315K   457G    21K  /export/home
-   pool/home/anne             18K   457G    18K  /export/home/anne
-   pool/home/bob             276K   457G   276K  /export/home/bob
-.fi
-.in -2
-.sp
-
-.LP
-\fBExample 6 \fRSetting a Quota on a ZFS File System
-.sp
-.LP
-The following command sets a quota of 50 Gbytes for \fBpool/home/bob\fR.
-
-.sp
-.in +2
-.nf
-# \fBzfs set quota=50G pool/home/bob\fR
-.fi
-.in -2
-.sp
-
-.LP
-\fBExample 7 \fRListing ZFS Properties
-.sp
-.LP
-The following command lists all properties for \fBpool/home/bob\fR.
-
-.sp
-.in +2
-.nf
-# \fBzfs get all pool/home/bob\fR
+   pool/home                 315K   457G    21K  /home
+   pool/home/anne             18K   457G    18K  /home/anne
+   pool/home/bob             276K   457G   276K  /home/bob
+.Ed
+.It Sy Example 6 No Setting a Quota on a Tn ZFS No File System
+.Pp
+The following command sets a quota of 50 Gbytes for
+.Em pool/home/bob .
+.Bd -literal -offset 2n
+.Li # Ic zfs set quota=50G pool/home/bob
+.Ed
+.It Sy Example 7 No Listing Tn ZFS No Properties
+.Pp
+The following command lists all properties for
+.Em pool/home/bob .
+.Bd -literal -offset 2n
+.Li # Ic zfs get all pool/home/bob
 NAME           PROPERTY              VALUE                  SOURCE
 pool/home/bob  type                  filesystem             -
 pool/home/bob  creation              Tue Jul 21 15:53 2009  -
@@ -3123,7 +2826,7 @@
 pool/home/bob  quota                 20G                    local
 pool/home/bob  reservation           none                   default
 pool/home/bob  recordsize            128K                   default
-pool/home/bob  mountpoint            /pool/home/bob         default
+pool/home/bob  mountpoint            /home/bob              default
 pool/home/bob  sharenfs              off                    default
 pool/home/bob  checksum              on                     default
 pool/home/bob  compression           on                     local
@@ -3139,7 +2842,7 @@
 pool/home/bob  canmount              on                     default
 pool/home/bob  xattr                 on                     default
 pool/home/bob  copies                1                      default
-pool/home/bob  version               4                      -
+pool/home/bob  version               5                      -
 pool/home/bob  utf8only              off                    -
 pool/home/bob  normalization         none                   -
 pool/home/bob  casesensitivity       sensitive              -
@@ -3154,284 +2857,238 @@
 pool/home/bob  usedbydataset         21K                    -
 pool/home/bob  usedbychildren        0                      -
 pool/home/bob  usedbyrefreservation  0                      -
-.fi
-.in -2
-.sp
-
-.sp
-.LP
+pool/home/bob  logbias               latency                default
+pool/home/bob  dedup                 off                    default
+pool/home/bob  mlslabel                                     -
+pool/home/bob  sync                  standard               default
+pool/home/bob  refcompressratio      1.00x                  -
+.Ed
+.Pp
 The following command gets a single property value.
-
-.sp
-.in +2
-.nf
-# \fBzfs get -H -o value compression pool/home/bob\fR
+.Bd -literal -offset 2n
+.Li # Ic zfs get -H -o value compression pool/home/bob
 on
-.fi
-.in -2
-.sp
-
-.sp
-.LP
+.Ed
+.Pp
 The following command lists all properties with local settings for
-\fBpool/home/bob\fR.
-
-.sp
-.in +2
-.nf
-# \fBzfs get -r -s local -o name,property,value all pool/home/bob\fR
+.Em pool/home/bob .
+.Bd -literal -offset 2n
+.Li # Ic zfs get -s local -o name,property,value all pool/home/bob
 NAME           PROPERTY              VALUE
 pool/home/bob  quota                 20G
 pool/home/bob  compression           on
-.fi
-.in -2
-.sp
-
-.LP
-\fBExample 8 \fRRolling Back a ZFS File System
-.sp
-.LP
-The following command reverts the contents of \fBpool/home/anne\fR to the
-snapshot named \fByesterday\fR, deleting all intermediate snapshots.
-
-.sp
-.in +2
-.nf
-# \fBzfs rollback -r pool/home/anne at yesterday\fR
-.fi
-.in -2
-.sp
-
-.LP
-\fBExample 9 \fRCreating a ZFS Clone
-.sp
-.LP
+.Ed
+.It Sy Example 8 No Rolling Back a Tn ZFS No File System
+.Pp
+The following command reverts the contents of
+.Em pool/home/anne
+to the snapshot named
+.Em yesterday ,
+deleting all intermediate snapshots.
+.Bd -literal -offset 2n
+.Li # Ic zfs rollback -r pool/home/anne at yesterday
+.Ed
+.It Sy Example 9 No Creating a Tn ZFS No Clone
+.Pp
 The following command creates a writable file system whose initial contents are
-the same as \fBpool/home/bob at yesterday\fR.
-
-.sp
-.in +2
-.nf
-# \fBzfs clone pool/home/bob at yesterday pool/clone\fR
-.fi
-.in -2
-.sp
-
-.LP
-\fBExample 10 \fRPromoting a ZFS Clone
-.sp
-.LP
+the same as
+.Em pool/home/bob at yesterday .
+.Bd -literal -offset 2n
+.Li # Ic zfs clone pool/home/bob at yesterday pool/clone
+.Ed
+.It Sy Example 10 No Promoting a Tn ZFS No Clone
+.Pp
 The following commands illustrate how to test out changes to a file system, and
 then replace the original file system with the changed one, using clones, clone
 promotion, and renaming:
-
-.sp
-.in +2
-.nf
-# \fBzfs create pool/project/production\fR
-  populate /pool/project/production with data
-# \fBzfs snapshot pool/project/production at today\fR
-# \fBzfs clone pool/project/production at today pool/project/beta\fR
-make changes to /pool/project/beta and test them
-# \fBzfs promote pool/project/beta\fR
-# \fBzfs rename pool/project/production pool/project/legacy\fR
-# \fBzfs rename pool/project/beta pool/project/production\fR
-once the legacy version is no longer needed, it can be destroyed
-# \fBzfs destroy pool/project/legacy\fR
-.fi
-.in -2
-.sp
-
-.LP
-\fBExample 11 \fRInheriting ZFS Properties
-.sp
-.LP
-The following command causes \fBpool/home/bob\fR and \fBpool/home/anne\fR to
-inherit the \fBchecksum\fR property from their parent.
-
-.sp
-.in +2
-.nf
-# \fBzfs inherit checksum pool/home/bob pool/home/anne\fR
-.fi
-.in -2
-.sp
-
-.LP
-\fBExample 12 \fRRemotely Replicating ZFS Data
-.sp
-.LP
+.Bd -literal -offset 2n
+.Li # Ic zfs create pool/project/production
+.Ed
+.Pp
+Populate
+.Pa /pool/project/production
+with data and continue with the following commands:
+.Bd -literal -offset 2n
+.Li # Ic zfs snapshot pool/project/production at today
+.Li # Ic zfs clone pool/project/production at today pool/project/beta
+.Ed
+.Pp
+Now make changes to
+.Pa /pool/project/beta
+and continue with the following commands:
+.Bd -literal -offset 2n
+.Li # Ic zfs promote pool/project/beta
+.Li # Ic zfs rename pool/project/production pool/project/legacy
+.Li # Ic zfs rename pool/project/beta pool/project/production
+.Ed
+.Pp
+Once the legacy version is no longer needed, it can be destroyed.
+.Bd -literal -offset 2n
+.Li # Ic zfs destroy pool/project/legacy
+.Ed
+.It Sy Example 11 No Inheriting Tn ZFS No Properties
+.Pp
+The following command causes
+.Em pool/home/bob
+and
+.Em pool/home/anne
+to inherit the
+.Sy checksum
+property from their parent.
+.Bd -literal -offset 2n
+.Li # Ic zfs inherit checksum pool/home/bob pool/home/anne
+.Ed
+.It Sy Example 12 No Remotely Replicating Tn ZFS No Data
+.Pp
 The following commands send a full stream and then an incremental stream to a
-remote machine, restoring them into \fBpoolB/received/fs at a\fRand
-\fBpoolB/received/fs at b\fR, respectively. \fBpoolB\fR must contain the file
-system \fBpoolB/received\fR, and must not initially contain
-\fBpoolB/received/fs\fR.
-
-.sp
-.in +2
-.nf
-# \fBzfs send pool/fs at a | \e\fR
-   \fBssh host zfs receive poolB/received/fs at a\fR
-# \fBzfs send -i a pool/fs at b | ssh host \e\fR
-   \fBzfs receive poolB/received/fs\fR
-.fi
-.in -2
-.sp
-
-.LP
-\fBExample 13 \fRUsing the \fBzfs receive\fR \fB-d\fR Option
-.sp
-.LP
-The following command sends a full stream of \fBpoolA/fsA/fsB at snap\fR to a
-remote machine, receiving it into \fBpoolB/received/fsA/fsB at snap\fR. The
-\fBfsA/fsB at snap\fR portion of the received snapshot's name is determined from
-the name of the sent snapshot. \fBpoolB\fR must contain the file system
-\fBpoolB/received\fR. If \fBpoolB/received/fsA\fR does not exist, it is created
-as an empty file system.
-
-.sp
-.in +2
-.nf
-# \fBzfs send poolA/fsA/fsB at snap | \e
-   ssh host zfs receive -d poolB/received\fR
-.fi
-.in -2
-.sp
-
-.LP
-\fBExample 14 \fRSetting User Properties
-.sp
-.LP
-The following example sets the user-defined \fBcom.example:department\fR
+remote machine, restoring them into
+.Sy poolB/received/fs at a
+and
+.Sy poolB/received/fs at b ,
+respectively.
+.Sy poolB
+must contain the file system
+.Sy poolB/received ,
+and must not initially contain
+.Sy poolB/received/fs .
+.Bd -literal -offset 2n
+.Li # Ic zfs send pool/fs at a | ssh host zfs receive poolB/received/fs at a
+.Li # Ic zfs send -i a pool/fs at b | ssh host zfs receive poolB/received/fs
+.Ed
+.It Xo
+.Sy Example 13
+Using the
+.Qq zfs receive -d
+Option
+.Xc
+.Pp
+The following command sends a full stream of
+.Sy poolA/fsA/fsB at snap
+to a remote machine, receiving it into
+.Sy poolB/received/fsA/fsB at snap .
+The
+.Sy fsA/fsB at snap
+portion of the received snapshot's name is determined from the name of the sent
+snapshot.
+.Sy poolB
+must contain the file system
+.Sy poolB/received .
+If
+.Sy poolB/received/fsA
+does not exist, it is created as an empty file system.
+.Bd -literal -offset 2n
+.Li # Ic zfs send poolA/fsA/fsB at snap | ssh host zfs receive -d poolB/received
+.Ed
+.It Sy Example 14 No Setting User Properties
+.Pp
+The following example sets the user-defined
+.Sy com.example:department
 property for a dataset.
-
-.sp
-.in +2
-.nf
-# \fBzfs set com.example:department=12345 tank/accounting\fR
-.fi
-.in -2
-.sp
-
-.LP
-\fBExample 16 \fRPerforming a Rolling Snapshot
-.sp
-.LP
+.Bd -literal -offset 2n
+.Li # Ic zfs set com.example:department=12345 tank/accounting
+.Ed
+.It Sy Example 15 No Performing a Rolling Snapshot
+.Pp
 The following example shows how to maintain a history of snapshots with a
 consistent naming scheme. To keep a week's worth of snapshots, the user
 destroys the oldest snapshot, renames the remaining snapshots, and then creates
 a new snapshot, as follows:
-
-.sp
-.in +2
-.nf
-# \fBzfs destroy -r pool/users at 7daysago\fR
-# \fBzfs rename -r pool/users at 6daysago @7daysago\fR
-# \fBzfs rename -r pool/users at 5daysago @6daysago\fR
-# \fBzfs rename -r pool/users at yesterday @5daysago\fR
-# \fBzfs rename -r pool/users at yesterday @4daysago\fR
-# \fBzfs rename -r pool/users at yesterday @3daysago\fR
-# \fBzfs rename -r pool/users at yesterday @2daysago\fR
-# \fBzfs rename -r pool/users at today @yesterday\fR
-# \fBzfs snapshot -r pool/users at today\fR
-.fi
-.in -2
-.sp
-
-.LP
-\fBExample 17 \fRSetting \fBsharenfs\fR Property Options on a ZFS File System
-.sp
-.LP
-The following commands show how to set \fBsharenfs\fR property options to
-enable \fBrw\fR access for a set of \fBIP\fR addresses and to enable root
-access for system \fBneo\fR on the \fBtank/home\fR file system.
-
-.sp
-.in +2
-.nf
-# \fB# zfs set sharenfs='[email protected]/16,root=neo' tank/home\fR
-.fi
-.in -2
-.sp
-
-.sp
-.LP
-If you are using \fBDNS\fR for host name resolution, specify the fully
-qualified hostname.
-
-.LP
-\fBExample 18 \fRDelegating ZFS Administration Permissions on a ZFS Dataset
-.sp
-.LP
-The following example shows how to set permissions so that user \fBcindys\fR
-can create, destroy, mount, and take snapshots on \fBtank/cindys\fR. The
-permissions on \fBtank/cindys\fR are also displayed.
-
-.sp
-.in +2
-.nf
-# \fBzfs allow cindys create,destroy,mount,snapshot tank/cindys\fR
-# \fBzfs allow tank/cindys\fR
+.Bd -literal -offset 2n
+.Li # Ic zfs destroy -r pool/users at 7daysago
+.Li # Ic zfs rename -r pool/users at 6daysago @7daysago
+.Li # Ic zfs rename -r pool/users at 5daysago @6daysago
+.Li # Ic zfs rename -r pool/users at yesterday @5daysago
+.Li # Ic zfs rename -r pool/users at yesterday @4daysago
+.Li # Ic zfs rename -r pool/users at yesterday @3daysago
+.Li # Ic zfs rename -r pool/users at yesterday @2daysago
+.Li # Ic zfs rename -r pool/users at today @yesterday
+.Li # Ic zfs snapshot -r pool/users at today
+.Ed
+.It Xo
+.Sy Example 16
+Setting
+.Qq sharenfs
+Property Options on a ZFS File System
+.Xc
+.Pp
+The following command shows how to set
+.Sy sharenfs
+property options to enable root access for a specific network on the
+.Em tank/home
+file system. The contents of the
+.Sy sharenfs
+property are valid
+.Xr exports 5
+options.
+.Bd -literal -offset 2n
+.Li # Ic zfs set sharenfs="maproot=root,network 192.168.0.0/24" tank/home
+.Ed
+.Pp
+Another way to write this command with the same result is:
+.Bd -literal -offset 2n
+.Li # Ic set zfs sharenfs="-maproot=root -network 192.168.0.0/24" tank/home
+.Ed
+.It Xo
+.Sy Example 17
+Delegating
+.Tn ZFS
+Administration Permissions on a
+.Tn ZFS
+Dataset
+.Xc
+.Pp
+The following example shows how to set permissions so that user
+.Em cindys
+can create, destroy, mount, and take snapshots on
+.Em tank/cindys .
+The permissions on
+.Em tank/cindys
+are also displayed.
+.Bd -literal -offset 2n
+.Li # Ic zfs allow cindys create,destroy,mount,snapshot tank/cindys
+.Li # Ic zfs allow tank/cindys
 -------------------------------------------------------------
 Local+Descendent permissions on (tank/cindys)
           user cindys create,destroy,mount,snapshot
 -------------------------------------------------------------
-.fi
-.in -2
-.sp
-
-.sp
-.LP
-Because the \fBtank/cindys\fR mount point permission is set to 755 by default,
-user \fBcindys\fR will be unable to mount file systems under \fBtank/cindys\fR.
-Set an \fBACL\fR similar to the following syntax to provide mount point access:
-.sp
-.in +2
-.nf
-# \fBchmod A+user:cindys:add_subdirectory:allow /tank/cindys\fR
-.fi
-.in -2
-.sp
-
-.LP
-\fBExample 19 \fRDelegating Create Time Permissions on a ZFS Dataset
-.sp
-.LP
-The following example shows how to grant anyone in the group \fBstaff\fR to
-create file systems in \fBtank/users\fR. This syntax also allows staff members
-to destroy their own file systems, but not destroy anyone else's file system.
-The permissions on \fBtank/users\fR are also displayed.
-
-.sp
-.in +2
-.nf
-# \fB# zfs allow staff create,mount tank/users\fR
-# \fBzfs allow -c destroy tank/users\fR
-# \fBzfs allow tank/users\fR
+.Ed
+.It Sy Example 18 No Delegating Create Time Permissions on a Tn ZFS No Dataset
+.Pp
+The following example shows how to grant anyone in the group
+.Em staff
+to create file systems in
+.Em tank/users .
+This syntax also allows staff members to destroy their own file systems, but
+not destroy anyone else's file system. The permissions on
+.Em tank/users
+are also displayed.
+.Bd -literal -offset 2n
+.Li # Ic zfs allow staff create,mount tank/users
+.Li # Ic zfs allow -c destroy tank/users
+.Li # Ic zfs allow tank/users
 -------------------------------------------------------------
 Create time permissions on (tank/users)
           create,destroy
 Local+Descendent permissions on (tank/users)
           group staff create,mount
 -------------------------------------------------------------
-.fi
-.in -2
-.sp
-
-.LP
-\fBExample 20 \fRDefining and Granting a Permission Set on a ZFS Dataset
-.sp
-.LP
+.Ed
+.It Xo
+.Sy Example 19
+Defining and Granting a Permission Set on a
+.Tn ZFS
+Dataset
+.Xc
+.Pp
 The following example shows how to define and grant a permission set on the
-\fBtank/users\fR file system. The permissions on \fBtank/users\fR are also
-displayed.
-
-.sp
-.in +2
-.nf
-# \fBzfs allow -s @pset create,destroy,snapshot,mount tank/users\fR
-# \fBzfs allow staff @pset tank/users\fR
-# \fBzfs allow tank/users\fR
+.Em tank/users
+file system. The permissions on
+.Em tank/users
+are also displayed.
+.Bd -literal -offset 2n
+.Li # Ic zfs allow -s @pset create,destroy,snapshot,mount tank/users
+.Li # Ic zfs allow staff @pset tank/users
+.Li # Ic zfs allow tank/users
 -------------------------------------------------------------
 Permission sets on (tank/users)
         @pset create,destroy,mount,snapshot
@@ -3440,48 +3097,40 @@
 Local+Descendent permissions on (tank/users)
         group staff @pset,create,mount
 -------------------------------------------------------------
-.fi
-.in -2
-.sp
-
-.LP
-\fBExample 21 \fRDelegating Property Permissions on a ZFS Dataset
-.sp
-.LP
+.Ed
+.It Sy Example 20 No Delegating Property Permissions on a Tn ZFS No Dataset
+.Pp
 The following example shows to grant the ability to set quotas and reservations
-on the \fBusers/home\fR file system. The permissions on \fBusers/home\fR are
-also displayed.
-
-.sp
-.in +2
-.nf
-# \fBzfs allow cindys quota,reservation users/home\fR
-# \fBzfs allow users/home\fR
+on the
+.Sy users/home
+file system. The permissions on
+.Sy users/home
+are also displayed.
+.Bd -literal -offset 2n
+.Li # Ic zfs allow cindys quota,reservation users/home
+.Li # Ic zfs allow cindys
 -------------------------------------------------------------
 Local+Descendent permissions on (users/home)
         user cindys quota,reservation
 -------------------------------------------------------------
-cindys% \fBzfs set quota=10G users/home/marks\fR
-cindys% \fBzfs get quota users/home/marks\fR
+.Li # Ic su - cindys
+.Li cindys% Ic zfs set quota=10G users/home/marks
+.Li cindys% Ic zfs get quota users/home/marks
 NAME              PROPERTY  VALUE             SOURCE
 users/home/marks  quota     10G               local
-.fi
-.in -2
-.sp
-
-.LP
-\fBExample 22 \fRRemoving ZFS Delegated Permissions on a ZFS Dataset
-.sp
-.LP
+.Ed
+.It Sy Example 21 No Removing ZFS Delegated Permissions on a Tn ZFS No Dataset
+.Pp
 The following example shows how to remove the snapshot permission from the
-\fBstaff\fR group on the \fBtank/users\fR file system. The permissions on
-\fBtank/users\fR are also displayed.
-
-.sp
-.in +2
-.nf
-# \fBzfs unallow staff snapshot tank/users\fR
-# \fBzfs allow tank/users\fR
+.Em staff
+group on the
+.Em tank/users
+file system. The permissions on
+.Em tank/users
+are also displayed.
+.Bd -literal -offset 2n
+.Li # Ic zfs unallow staff snapshot tank/users
+.Li # Ic zfs allow tank/users
 -------------------------------------------------------------
 Permission sets on (tank/users)
         @pset create,destroy,mount,snapshot
@@ -3490,45 +3139,42 @@
 Local+Descendent permissions on (tank/users)
         group staff @pset,create,mount
 -------------------------------------------------------------
-.fi
-.in -2
-.sp
-
-.SH EXIT STATUS
-.sp
-.LP
+.Ed
+.El
+.Sh EXIT STATUS
 The following exit values are returned:
-.sp
-.ne 2
-.na
-\fB\fB0\fR\fR
-.ad
-.sp .6
-.RS 4n
+.Bl -tag -offset 2n -width 2n
+.It 0
 Successful completion.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB1\fR\fR
-.ad
-.sp .6
-.RS 4n
+.It 1
 An error occurred.
-
-.RE
-.sp
-.ne 2
-.na
-\fB\fB2\fR\fR
-.ad
-.sp .6
-.RS 4n
+.It 2
 Invalid command line options were specified.
-.RE
-
-.SH SEE ALSO
-.sp
-.LP
-chmod(2), fsync(2), exports(5), fstab(5), jail(8), mount(8), zpool(8)
+.El
+.Sh SEE ALSO
+.Xr chmod 2 ,
+.Xr fsync 2 ,
+.Xr exports 5 ,
+.Xr fstab 5 ,
+.Xr rc.conf 5 ,
+.Xr jail 8 ,
+.Xr mount 8 ,
+.Xr umount 8 ,
+.Xr zpool 8
+.Sh AUTHORS
+This manual page is a
+.Xr mdoc 7
+reimplementation of the
+.Tn OpenSolaris
+manual page
+.Em zfs(1M) ,
+modified and customized for
+.Fx
+and licensed under the
+Common Development and Distribution License
+.Pq Tn CDDL .
+.Pp
+The
+.Xr mdoc 7
+implementation of this manual page was initially written by
+.An Martin Matuska Aq mm at FreeBSD.org .
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/cddl/contrib/opensolaris/cmd/zfs/zfs_main.c
--- a/head/cddl/contrib/opensolaris/cmd/zfs/zfs_main.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/cddl/contrib/opensolaris/cmd/zfs/zfs_main.c	Tue Dec 06 20:26:16 2011 +0200
@@ -22,8 +22,9 @@
 /*
  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
  * Copyright 2011 Nexenta Systems, Inc. All rights reserved.
+ * Copyright (c) 2011 by Delphix. All rights reserved.
  * Copyright (c) 2011 Pawel Jakub Dawidek <pawel at dawidek.net>.
- * All rights reserved.
+ * Copyright (c) 2011 Martin Matuska <mm at FreeBSD.org>. All rights reserved.
  */
 
 #include <assert.h>
@@ -145,7 +146,7 @@
 	HELP_HOLD,
 	HELP_HOLDS,
 	HELP_RELEASE,
-	HELP_DIFF
+	HELP_DIFF,
 } zfs_help_t;
 
 typedef struct zfs_command {
@@ -220,8 +221,9 @@
 		    "\tcreate [-ps] [-b blocksize] [-o property=value] ... "
 		    "-V <size> <volume>\n"));
 	case HELP_DESTROY:
-		return (gettext("\tdestroy [-rRf] <filesystem|volume>\n"
-		    "\tdestroy [-rRd] <snapshot>\n"));
+		return (gettext("\tdestroy [-fnpRrv] <filesystem|volume>\n"
+		    "\tdestroy [-dnpRrv] "
+		    "<snapshot>[%<snapname>][,...]\n"));
 	case HELP_GET:
 		return (gettext("\tget [-rHp] [-d max] "
 		    "[-o \"all\" | field[,...]] [-s source[,...]]\n"
@@ -260,7 +262,8 @@
 	case HELP_ROLLBACK:
 		return (gettext("\trollback [-rRf] <snapshot>\n"));
 	case HELP_SEND:
-		return (gettext("\tsend [-RDp] [-[iI] snapshot] <snapshot>\n"));
+		return (gettext("\tsend [-DnPpRrv] "
+		    "[-i snapshot | -I snapshot] <snapshot>\n"));
 	case HELP_SET:
 		return (gettext("\tset <property=value> "
 		    "<filesystem|volume|snapshot> ...\n"));
@@ -296,11 +299,11 @@
 		    "\tunallow [-r] -s @setname [<perm|@setname>[,...]] "
 		    "<filesystem|volume>\n"));
 	case HELP_USERSPACE:
-		return (gettext("\tuserspace [-hniHp] [-o field[,...]] "
+		return (gettext("\tuserspace [-niHp] [-o field[,...]] "
 		    "[-sS field] ... [-t type[,...]]\n"
 		    "\t    <filesystem|snapshot>\n"));
 	case HELP_GROUPSPACE:
-		return (gettext("\tgroupspace [-hniHpU] [-o field[,...]] "
+		return (gettext("\tgroupspace [-niHp] [-o field[,...]] "
 		    "[-sS field] ... [-t type[,...]]\n"
 		    "\t    <filesystem|snapshot>\n"));
 	case HELP_HOLD:
@@ -439,6 +442,8 @@
 		(void) fprintf(fp, "YES       NO   <size> | none\n");
 		(void) fprintf(fp, "\t%-15s ", "groupquota at ...");
 		(void) fprintf(fp, "YES       NO   <size> | none\n");
+		(void) fprintf(fp, "\t%-15s ", "written@<snap>");
+		(void) fprintf(fp, " NO       NO   <size>\n");
 
 		(void) fprintf(fp, gettext("\nSizes are specified in bytes "
 		    "with standard units such as K, M, G, etc.\n"));
@@ -884,15 +889,23 @@
  */
 typedef struct destroy_cbdata {
 	boolean_t	cb_first;
-	int		cb_force;
-	int		cb_recurse;
-	int		cb_error;
-	int		cb_needforce;
-	int		cb_doclones;
-	boolean_t	cb_closezhp;
+	boolean_t	cb_force;
+	boolean_t	cb_recurse;
+	boolean_t	cb_error;
+	boolean_t	cb_doclones;
 	zfs_handle_t	*cb_target;
-	char		*cb_snapname;
 	boolean_t	cb_defer_destroy;
+	boolean_t	cb_verbose;
+	boolean_t	cb_parsable;
+	boolean_t	cb_dryrun;
+	nvlist_t	*cb_nvl;
+
+	/* first snap in contiguous run */
+	zfs_handle_t	*cb_firstsnap;
+	/* previous snap in contiguous run */
+	zfs_handle_t	*cb_prevsnap;
+	int64_t		cb_snapused;
+	char		*cb_snapspec;
 } destroy_cbdata_t;
 
 /*
@@ -922,7 +935,7 @@
 			(void) fprintf(stderr, gettext("use '-r' to destroy "
 			    "the following datasets:\n"));
 			cbp->cb_first = B_FALSE;
-			cbp->cb_error = 1;
+			cbp->cb_error = B_TRUE;
 		}
 
 		(void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
@@ -943,7 +956,8 @@
 			(void) fprintf(stderr, gettext("use '-R' to destroy "
 			    "the following datasets:\n"));
 			cbp->cb_first = B_FALSE;
-			cbp->cb_error = 1;
+			cbp->cb_error = B_TRUE;
+			cbp->cb_dryrun = B_TRUE;
 		}
 
 		(void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
@@ -957,7 +971,20 @@
 static int
 destroy_callback(zfs_handle_t *zhp, void *data)
 {
-	destroy_cbdata_t *cbp = data;
+	destroy_cbdata_t *cb = data;
+	const char *name = zfs_get_name(zhp);
+
+	if (cb->cb_verbose) {
+		if (cb->cb_parsable) {
+			(void) printf("destroy\t%s\n", name);
+		} else if (cb->cb_dryrun) {
+			(void) printf(gettext("would destroy %s\n"),
+			    name);
+		} else {
+			(void) printf(gettext("will destroy %s\n"),
+			    name);
+		}
+	}
 
 	/*
 	 * Ignore pools (which we've already flagged as an error before getting
@@ -969,13 +996,12 @@
 		return (0);
 	}
 
-	/*
-	 * Bail out on the first error.
-	 */
-	if (zfs_unmount(zhp, NULL, cbp->cb_force ? MS_FORCE : 0) != 0 ||
-	    zfs_destroy(zhp, cbp->cb_defer_destroy) != 0) {
-		zfs_close(zhp);
-		return (-1);
+	if (!cb->cb_dryrun) {
+		if (zfs_unmount(zhp, NULL, cb->cb_force ? MS_FORCE : 0) != 0 ||
+		    zfs_destroy(zhp, cb->cb_defer_destroy) != 0) {
+			zfs_close(zhp);
+			return (-1);
+		}
 	}
 
 	zfs_close(zhp);
@@ -983,39 +1009,142 @@
 }
 
 static int
-destroy_snap_clones(zfs_handle_t *zhp, void *arg)
+destroy_print_cb(zfs_handle_t *zhp, void *arg)
 {
-	destroy_cbdata_t *cbp = arg;
-	char thissnap[MAXPATHLEN];
-	zfs_handle_t *szhp;
-	boolean_t closezhp = cbp->cb_closezhp;
-	int rv;
-
-	(void) snprintf(thissnap, sizeof (thissnap),
-	    "%s@%s", zfs_get_name(zhp), cbp->cb_snapname);
-
-	libzfs_print_on_error(g_zfs, B_FALSE);
-	szhp = zfs_open(g_zfs, thissnap, ZFS_TYPE_SNAPSHOT);
-	libzfs_print_on_error(g_zfs, B_TRUE);
-	if (szhp) {
-		/*
-		 * Destroy any clones of this snapshot
-		 */
-		if (zfs_iter_dependents(szhp, B_FALSE, destroy_callback,
-		    cbp) != 0) {
-			zfs_close(szhp);
-			if (closezhp)
-				zfs_close(zhp);
-			return (-1);
+	destroy_cbdata_t *cb = arg;
+	const char *name = zfs_get_name(zhp);
+	int err = 0;
+
+	if (nvlist_exists(cb->cb_nvl, name)) {
+		if (cb->cb_firstsnap == NULL)
+			cb->cb_firstsnap = zfs_handle_dup(zhp);
+		if (cb->cb_prevsnap != NULL)
+			zfs_close(cb->cb_prevsnap);
+		/* this snap continues the current range */
+		cb->cb_prevsnap = zfs_handle_dup(zhp);
+		if (cb->cb_verbose) {
+			if (cb->cb_parsable) {
+				(void) printf("destroy\t%s\n", name);
+			} else if (cb->cb_dryrun) {
+				(void) printf(gettext("would destroy %s\n"),
+				    name);
+			} else {
+				(void) printf(gettext("will destroy %s\n"),
+				    name);
+			}
 		}
-		zfs_close(szhp);
-	}
-
-	cbp->cb_closezhp = B_TRUE;
-	rv = zfs_iter_filesystems(zhp, destroy_snap_clones, arg);
-	if (closezhp)
-		zfs_close(zhp);
-	return (rv);
+	} else if (cb->cb_firstsnap != NULL) {
+		/* end of this range */
+		uint64_t used = 0;
+		err = zfs_get_snapused_int(cb->cb_firstsnap,
+		    cb->cb_prevsnap, &used);
+		cb->cb_snapused += used;
+		zfs_close(cb->cb_firstsnap);
+		cb->cb_firstsnap = NULL;
+		zfs_close(cb->cb_prevsnap);
+		cb->cb_prevsnap = NULL;
+	}
+	zfs_close(zhp);
+	return (err);
+}
+
+static int
+destroy_print_snapshots(zfs_handle_t *fs_zhp, destroy_cbdata_t *cb)
+{
+	int err;
+	assert(cb->cb_firstsnap == NULL);
+	assert(cb->cb_prevsnap == NULL);
+	err = zfs_iter_snapshots_sorted(fs_zhp, destroy_print_cb, cb);
+	if (cb->cb_firstsnap != NULL) {
+		uint64_t used = 0;
+		if (err == 0) {
+			err = zfs_get_snapused_int(cb->cb_firstsnap,
+			    cb->cb_prevsnap, &used);
+		}
+		cb->cb_snapused += used;
+		zfs_close(cb->cb_firstsnap);
+		cb->cb_firstsnap = NULL;
+		zfs_close(cb->cb_prevsnap);
+		cb->cb_prevsnap = NULL;
+	}
+	return (err);
+}
+
+static int
+snapshot_to_nvl_cb(zfs_handle_t *zhp, void *arg)
+{
+	destroy_cbdata_t *cb = arg;
+	int err = 0;
+
+	/* Check for clones. */
+	if (!cb->cb_doclones) {
+		cb->cb_target = zhp;
+		cb->cb_first = B_TRUE;
+		err = zfs_iter_dependents(zhp, B_TRUE,
+		    destroy_check_dependent, cb);
+	}
+
+	if (err == 0) {
+		if (nvlist_add_boolean(cb->cb_nvl, zfs_get_name(zhp)))
+			nomem();
+	}
+	zfs_close(zhp);
+	return (err);
+}
+
+static int
+gather_snapshots(zfs_handle_t *zhp, void *arg)
+{
+	destroy_cbdata_t *cb = arg;
+	int err = 0;
+
+	err = zfs_iter_snapspec(zhp, cb->cb_snapspec, snapshot_to_nvl_cb, cb);
+	if (err == ENOENT)
+		err = 0;
+	if (err != 0)
+		goto out;
+
+	if (cb->cb_verbose) {
+		err = destroy_print_snapshots(zhp, cb);
+		if (err != 0)
+			goto out;
+	}
+
+	if (cb->cb_recurse)
+		err = zfs_iter_filesystems(zhp, gather_snapshots, cb);
+
+out:
+	zfs_close(zhp);
+	return (err);
+}
+
+static int
+destroy_clones(destroy_cbdata_t *cb)
+{
+	nvpair_t *pair;
+	for (pair = nvlist_next_nvpair(cb->cb_nvl, NULL);
+	    pair != NULL;
+	    pair = nvlist_next_nvpair(cb->cb_nvl, pair)) {
+		zfs_handle_t *zhp = zfs_open(g_zfs, nvpair_name(pair),
+		    ZFS_TYPE_SNAPSHOT);
+		if (zhp != NULL) {
+			boolean_t defer = cb->cb_defer_destroy;
+			int err;
+
+			/*
+			 * We can't defer destroy non-snapshots, so set it to
+			 * false while destroying the clones.
+			 */
+			cb->cb_defer_destroy = B_FALSE;
+			err = zfs_iter_dependents(zhp, B_FALSE,
+			    destroy_callback, cb);
+			cb->cb_defer_destroy = defer;
+			zfs_close(zhp);
+			if (err != 0)
+				return (err);
+		}
+	}
+	return (0);
 }
 
 static int
@@ -1024,25 +1153,35 @@
 	destroy_cbdata_t cb = { 0 };
 	int c;
 	zfs_handle_t *zhp;
-	char *cp;
+	char *at;
 	zfs_type_t type = ZFS_TYPE_DATASET;
 
 	/* check options */
-	while ((c = getopt(argc, argv, "dfrR")) != -1) {
+	while ((c = getopt(argc, argv, "vpndfrR")) != -1) {
 		switch (c) {
+		case 'v':
+			cb.cb_verbose = B_TRUE;
+			break;
+		case 'p':
+			cb.cb_verbose = B_TRUE;
+			cb.cb_parsable = B_TRUE;
+			break;
+		case 'n':
+			cb.cb_dryrun = B_TRUE;
+			break;
 		case 'd':
 			cb.cb_defer_destroy = B_TRUE;
 			type = ZFS_TYPE_SNAPSHOT;
 			break;
 		case 'f':
-			cb.cb_force = 1;
+			cb.cb_force = B_TRUE;
 			break;
 		case 'r':
-			cb.cb_recurse = 1;
+			cb.cb_recurse = B_TRUE;
 			break;
 		case 'R':
-			cb.cb_recurse = 1;
-			cb.cb_doclones = 1;
+			cb.cb_recurse = B_TRUE;
+			cb.cb_doclones = B_TRUE;
 			break;
 		case '?':
 		default:
@@ -1057,7 +1196,7 @@
 
 	/* check number of arguments */
 	if (argc == 0) {
-		(void) fprintf(stderr, gettext("missing path argument\n"));
+		(void) fprintf(stderr, gettext("missing dataset argument\n"));
 		usage(B_FALSE);
 	}
 	if (argc > 1) {
@@ -1065,91 +1204,117 @@
 		usage(B_FALSE);
 	}
 
-	/*
-	 * If we are doing recursive destroy of a snapshot, then the
-	 * named snapshot may not exist.  Go straight to libzfs.
-	 */
-	if (cb.cb_recurse && (cp = strchr(argv[0], '@'))) {
-		int ret;
-
-		*cp = '\0';
-		if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_DATASET)) == NULL)
+	at = strchr(argv[0], '@');
+	if (at != NULL) {
+		int err;
+
+		/* Build the list of snaps to destroy in cb_nvl. */
+		if (nvlist_alloc(&cb.cb_nvl, NV_UNIQUE_NAME, 0) != 0)
+			nomem();
+
+		*at = '\0';
+		zhp = zfs_open(g_zfs, argv[0],
+		    ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
+		if (zhp == NULL)
 			return (1);
-		*cp = '@';
-		cp++;
-
-		if (cb.cb_doclones) {
-			boolean_t defer = cb.cb_defer_destroy;
-
-			/*
-			 * Temporarily ignore the defer_destroy setting since
-			 * it's not supported for clones.
-			 */
-			cb.cb_defer_destroy = B_FALSE;
-			cb.cb_snapname = cp;
-			if (destroy_snap_clones(zhp, &cb) != 0) {
-				zfs_close(zhp);
-				return (1);
+
+		cb.cb_snapspec = at + 1;
+		if (gather_snapshots(zfs_handle_dup(zhp), &cb) != 0 ||
+		    cb.cb_error) {
+			zfs_close(zhp);
+			nvlist_free(cb.cb_nvl);
+			return (1);
+		}
+
+		if (nvlist_empty(cb.cb_nvl)) {
+			(void) fprintf(stderr, gettext("could not find any "
+			    "snapshots to destroy; check snapshot names.\n"));
+			zfs_close(zhp);
+			nvlist_free(cb.cb_nvl);
+			return (1);
+		}
+
+		if (cb.cb_verbose) {
+			char buf[16];
+			zfs_nicenum(cb.cb_snapused, buf, sizeof (buf));
+			if (cb.cb_parsable) {
+				(void) printf("reclaim\t%llu\n",
+				    cb.cb_snapused);
+			} else if (cb.cb_dryrun) {
+				(void) printf(gettext("would reclaim %s\n"),
+				    buf);
+			} else {
+				(void) printf(gettext("will reclaim %s\n"),
+				    buf);
 			}
-			cb.cb_defer_destroy = defer;
 		}
 
-		ret = zfs_destroy_snaps(zhp, cp, cb.cb_defer_destroy);
+		if (!cb.cb_dryrun) {
+			if (cb.cb_doclones)
+				err = destroy_clones(&cb);
+			if (err == 0) {
+				err = zfs_destroy_snaps_nvl(zhp, cb.cb_nvl,
+				    cb.cb_defer_destroy);
+			}
+		}
+
 		zfs_close(zhp);
-		if (ret) {
-			(void) fprintf(stderr,
-			    gettext("no snapshots destroyed\n"));
+		nvlist_free(cb.cb_nvl);
+		if (err != 0)
+			return (1);
+	} else {
+		/* Open the given dataset */
+		if ((zhp = zfs_open(g_zfs, argv[0], type)) == NULL)
+			return (1);
+
+		cb.cb_target = zhp;
+
+		/*
+		 * Perform an explicit check for pools before going any further.
+		 */
+		if (!cb.cb_recurse && strchr(zfs_get_name(zhp), '/') == NULL &&
+		    zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) {
+			(void) fprintf(stderr, gettext("cannot destroy '%s': "
+			    "operation does not apply to pools\n"),
+			    zfs_get_name(zhp));
+			(void) fprintf(stderr, gettext("use 'zfs destroy -r "
+			    "%s' to destroy all datasets in the pool\n"),
+			    zfs_get_name(zhp));
+			(void) fprintf(stderr, gettext("use 'zpool destroy %s' "
+			    "to destroy the pool itself\n"), zfs_get_name(zhp));
+			zfs_close(zhp);
+			return (1);
 		}
-		return (ret != 0);
-	}
-
-	/* Open the given dataset */
-	if ((zhp = zfs_open(g_zfs, argv[0], type)) == NULL)
-		return (1);
-
-	cb.cb_target = zhp;
-
-	/*
-	 * Perform an explicit check for pools before going any further.
-	 */
-	if (!cb.cb_recurse && strchr(zfs_get_name(zhp), '/') == NULL &&
-	    zfs_get_type(zhp) == ZFS_TYPE_FILESYSTEM) {
-		(void) fprintf(stderr, gettext("cannot destroy '%s': "
-		    "operation does not apply to pools\n"),
-		    zfs_get_name(zhp));
-		(void) fprintf(stderr, gettext("use 'zfs destroy -r "
-		    "%s' to destroy all datasets in the pool\n"),
-		    zfs_get_name(zhp));
-		(void) fprintf(stderr, gettext("use 'zpool destroy %s' "
-		    "to destroy the pool itself\n"), zfs_get_name(zhp));
-		zfs_close(zhp);
-		return (1);
-	}
-
-	/*
-	 * Check for any dependents and/or clones.
-	 */
-	cb.cb_first = B_TRUE;
-	if (!cb.cb_doclones && !cb.cb_defer_destroy &&
-	    zfs_iter_dependents(zhp, B_TRUE, destroy_check_dependent,
-	    &cb) != 0) {
-		zfs_close(zhp);
-		return (1);
-	}
-
-	if (cb.cb_error || (!cb.cb_defer_destroy &&
-	    (zfs_iter_dependents(zhp, B_FALSE, destroy_callback, &cb) != 0))) {
-		zfs_close(zhp);
-		return (1);
-	}
-
-	/*
-	 * Do the real thing.  The callback will close the handle regardless of
-	 * whether it succeeds or not.
-	 */
-
-	if (destroy_callback(zhp, &cb) != 0)
-		return (1);
+
+		/*
+		 * Check for any dependents and/or clones.
+		 */
+		cb.cb_first = B_TRUE;
+		if (!cb.cb_doclones &&
+		    zfs_iter_dependents(zhp, B_TRUE, destroy_check_dependent,
+		    &cb) != 0) {
+			zfs_close(zhp);
+			return (1);
+		}
+
+		if (cb.cb_error) {
+			zfs_close(zhp);
+			return (1);
+		}
+
+		if (zfs_iter_dependents(zhp, B_FALSE, destroy_callback,
+		    &cb) != 0) {
+			zfs_close(zhp);
+			return (1);
+		}
+
+		/*
+		 * Do the real thing.  The callback will close the
+		 * handle regardless of whether it succeeds or not.
+		 */
+		if (destroy_callback(zhp, &cb) != 0)
+			return (1);
+	}
 
 	return (0);
 }
@@ -1251,6 +1416,17 @@
 
 			zprop_print_one_property(zfs_get_name(zhp), cbp,
 			    pl->pl_user_prop, buf, sourcetype, source, NULL);
+		} else if (zfs_prop_written(pl->pl_user_prop)) {
+			sourcetype = ZPROP_SRC_LOCAL;
+
+			if (zfs_prop_get_written(zhp, pl->pl_user_prop,
+			    buf, sizeof (buf), cbp->cb_literal) != 0) {
+				sourcetype = ZPROP_SRC_NONE;
+				(void) strlcpy(buf, "-", sizeof (buf));
+			}
+
+			zprop_print_one_property(zfs_get_name(zhp), cbp,
+			    pl->pl_user_prop, buf, sourcetype, source, NULL);
 		} else {
 			if (nvlist_lookup_nvlist(user_props,
 			    pl->pl_user_prop, &propval) != 0) {
@@ -1795,8 +1971,8 @@
 		    "---------------\n");
 		(void) printf(gettext(" 1   Initial ZFS filesystem version\n"));
 		(void) printf(gettext(" 2   Enhanced directory entries\n"));
-		(void) printf(gettext(" 3   Case insensitive and File system "
-		    "unique identifier (FUID)\n"));
+		(void) printf(gettext(" 3   Case insensitive and filesystem "
+		    "user identifier (FUID)\n"));
 		(void) printf(gettext(" 4   userquota, groupquota "
 		    "properties\n"));
 		(void) printf(gettext(" 5   System attributes\n"));
@@ -2676,6 +2852,13 @@
 			else
 				propstr = property;
 			right_justify = B_TRUE;
+		} else if (zfs_prop_written(pl->pl_user_prop)) {
+			if (zfs_prop_get_written(zhp, pl->pl_user_prop,
+			    property, sizeof (property), B_FALSE) != 0)
+				propstr = "-";
+			else
+				propstr = property;
+			right_justify = B_TRUE;
 		} else {
 			if (nvlist_lookup_nvlist(userprops,
 			    pl->pl_user_prop, &propval) != 0)
@@ -3302,9 +3485,6 @@
 }
 
 /*
- * zfs send [-vDp] -R [-i|-I <@snap>] <fs at snap>
- * zfs send [-vDp] [-i|-I <@snap>] <fs at snap>
- *
  * Send a backup stream to stdout.
  */
 static int
@@ -3316,11 +3496,11 @@
 	zfs_handle_t *zhp;
 	sendflags_t flags = { 0 };
 	int c, err;
-	nvlist_t *dbgnv;
+	nvlist_t *dbgnv = NULL;
 	boolean_t extraverbose = B_FALSE;
 
 	/* check options */
-	while ((c = getopt(argc, argv, ":i:I:RDpv")) != -1) {
+	while ((c = getopt(argc, argv, ":i:I:RDpvnP")) != -1) {
 		switch (c) {
 		case 'i':
 			if (fromname)
@@ -3339,6 +3519,10 @@
 		case 'p':
 			flags.props = B_TRUE;
 			break;
+		case 'P':
+			flags.parsable = B_TRUE;
+			flags.verbose = B_TRUE;
+			break;
 		case 'v':
 			if (flags.verbose)
 				extraverbose = B_TRUE;
@@ -3347,6 +3531,9 @@
 		case 'D':
 			flags.dedup = B_TRUE;
 			break;
+		case 'n':
+			flags.dryrun = B_TRUE;
+			break;
 		case ':':
 			(void) fprintf(stderr, gettext("missing argument for "
 			    "'%c' option\n"), optopt);
@@ -3372,7 +3559,7 @@
 		usage(B_FALSE);
 	}
 
-	if (isatty(STDOUT_FILENO)) {
+	if (!flags.dryrun && isatty(STDOUT_FILENO)) {
 		(void) fprintf(stderr,
 		    gettext("Error: Stream can not be written to a terminal.\n"
 		    "You must redirect standard output.\n"));
@@ -3426,10 +3613,10 @@
 	if (flags.replicate && fromname == NULL)
 		flags.doall = B_TRUE;
 
-	err = zfs_send(zhp, fromname, toname, flags, STDOUT_FILENO, NULL, 0,
+	err = zfs_send(zhp, fromname, toname, &flags, STDOUT_FILENO, NULL, 0,
 	    extraverbose ? &dbgnv : NULL);
 
-	if (extraverbose) {
+	if (extraverbose && dbgnv != NULL) {
 		/*
 		 * dump_nvlist prints to stdout, but that's been
 		 * redirected to a file.  Make it print to stderr
@@ -3510,7 +3697,7 @@
 		return (1);
 	}
 
-	err = zfs_receive(g_zfs, argv[0], flags, STDIN_FILENO, NULL);
+	err = zfs_receive(g_zfs, argv[0], &flags, STDIN_FILENO, NULL);
 
 	return (err != 0);
 }
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/cddl/contrib/opensolaris/cmd/zpool/zpool.8
--- a/head/cddl/contrib/opensolaris/cmd/zpool/zpool.8	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/cddl/contrib/opensolaris/cmd/zpool/zpool.8	Tue Dec 06 20:26:16 2011 +0200
@@ -1,492 +1,492 @@
 '\" te
-.\" Copyright (c) 2007, Sun Microsystems, Inc. All Rights Reserved.
-.\" The contents of this file are subject to the terms of the Common Development and Distribution License (the "License"). You may not use this file except in compliance with the License. You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE or http://www.opensolaris.org/os/licensing.
-.\" See the License for the specific language governing permissions and limitations under the License. When distributing Covered Code, include this CDDL HEADER in each file and include the License file at usr/src/OPENSOLARIS.LICENSE. If applicable, add the following below this CDDL HEADER, with the
-.\" fields enclosed by brackets "[]" replaced with your own identifying information: Portions Copyright [yyyy] [name of copyright owner]
-.\" Portions Copyright 2011 Justin T. Gibbs <gibbs at FreeBSD.org>
-.\" Portions Copyright 2011 Martin Matuska <mm at FreeBSD.org>
-.TH ZPOOL 8 "September 21, 2009" FreeBSD
-.SH NAME
-zpool \- configures ZFS storage pools
-.SH SYNOPSIS
-.LP
-.nf
-\fBzpool\fR [\fB-?\fR]
-.fi
-
-.LP
-.nf
-\fBzpool add\fR [\fB-fn\fR] \fIpool\fR \fIvdev\fR ...
-.fi
-
-.LP
-.nf
-\fBzpool attach\fR [\fB-f\fR] \fIpool\fR \fIdevice\fR \fInew_device\fR
-.fi
-
-.LP
-.nf
-\fBzpool clear\fR \fIpool\fR [\fIdevice\fR]
-.fi
-
-.LP
-.nf
-\fBzpool create\fR [\fB-fn\fR] [\fB-o\fR \fIproperty=value\fR] ... [\fB-O\fR \fIfile-system-property=value\fR]
-     ... [\fB-m\fR \fImountpoint\fR] [\fB-R\fR \fIroot\fR] \fIpool\fR \fIvdev\fR ...
-.fi
-
-.LP
-.nf
-\fBzpool destroy\fR [\fB-f\fR] \fIpool\fR
-.fi
-
-.LP
-.nf
-\fBzpool detach\fR \fIpool\fR \fIdevice\fR
-.fi
-
-.LP
-.nf
-\fBzpool export\fR [\fB-f\fR] \fIpool\fR ...
-.fi
-
-.LP
-.nf
-\fBzpool get\fR "\fIall\fR" | \fIproperty\fR[,...] \fIpool\fR ...
-.fi
-
-.LP
-.nf
-\fBzpool history\fR [\fB-il\fR] [\fIpool\fR] ...
-.fi
-
-.LP
-.nf
-\fBzpool import\fR [\fB-d\fR \fIdir\fR] [\fB-D\fR]
-.fi
-
-.LP
-.nf
-\fBzpool import\fR [\fB-o \fImntopts\fR\fR] [\fB-o\fR \fIproperty=value\fR] ... [\fB-d\fR \fIdir\fR | \fB-c\fR \fIcachefile\fR]
-     [\fB-D\fR] [\fB-f\fR] [\fB-R\fR \fIroot\fR] \fB-a\fR
-.fi
-
-.LP
-.nf
-\fBzpool import\fR [\fB-o \fImntopts\fR\fR] [\fB-o\fR \fIproperty=value\fR] ... [\fB-d\fR \fIdir\fR | \fB-c\fR \fIcachefile\fR]
-     [\fB-D\fR] [\fB-f\fR] [\fB-R\fR \fIroot\fR] \fIpool\fR |\fIid\fR [\fInewpool\fR]
-.fi
-
-.LP
-.nf
-\fBzpool iostat\fR [\fB-T\fR u | d ] [\fB-v\fR] [\fIpool\fR] ... [\fIinterval\fR[\fIcount\fR]]
-.fi
-
-.LP
-.nf
-\fBzpool labelclear\fR [\fB-f\fR] \fIdevice\fR
-.fi
-
-.LP
-.nf
-\fBzpool list\fR [\fB-H\fR] [\fB-o\fR \fIproperty\fR[,...]] [\fIpool\fR] ...
-.fi
-
-.LP
-.nf
-\fBzpool offline\fR [\fB-t\fR] \fIpool\fR \fIdevice\fR ...
-.fi
-
-.LP
-.nf
-\fBzpool online\fR \fIpool\fR \fIdevice\fR ...
-.fi
-
-.LP
-.nf
-\fBzpool remove\fR \fIpool\fR \fIdevice\fR ...
-.fi
-
-.LP
-.nf
-\fBzpool replace\fR [\fB-f\fR] \fIpool\fR \fIdevice\fR [\fInew_device\fR]
-.fi
-
-.LP
-.nf
-\fBzpool scrub\fR [\fB-s\fR] \fIpool\fR ...
-.fi
-
-.LP
-.nf
-\fBzpool set\fR \fIproperty\fR=\fIvalue\fR \fIpool\fR
-.fi
-
-.LP
-.nf
-\fBzpool status\fR [\fB-xv\fR] [\fIpool\fR] ...
-.fi
-
-.LP
-.nf
-\fBzpool upgrade\fR
-.fi
-
-.LP
-.nf
-\fBzpool upgrade\fR \fB-v\fR
-.fi
-
-.LP
-.nf
-\fBzpool upgrade\fR [\fB-V\fR \fIversion\fR] \fB-a\fR | \fIpool\fR ...
-.fi
-
-.SH DESCRIPTION
-.sp
-.LP
-The \fBzpool\fR command configures \fBZFS\fR storage pools. A storage pool is a
-collection of devices that provides physical storage and data replication for
-\fBZFS\fR datasets.
-.sp
-.LP
-All datasets within a storage pool share the same space. See \fBzfs\fR(8) for
-information on managing datasets.
-.SS "Virtual Devices (\fBvdev\fRs)"
-.sp
-.LP
-A "virtual device" describes a single device or a collection of devices
-organized according to certain performance and fault characteristics. The
-following virtual devices are supported:
-.sp
-.ne 2
-.na
-\fB\fBdisk\fR\fR
-.ad
-.RS 10n
-A block device, typically located under \fB/dev\fR. \fBZFS\fR can use
-individual slices, partitions or \fBgeom(4)\fR objects, though the recommended
-mode of operation is to use whole disks. A disk can be specified by a full
-path, or it can be a shorthand name (the relative portion of the path under
-"/dev"). For example, "da0" is equivalent to "/dev/da0".
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBfile\fR\fR
-.ad
-.RS 10n
+.\" Copyright (c) 2011, Martin Matuska <mm at FreeBSD.org>.
+.\" All Rights Reserved.
+.\"
+.\" The contents of this file are subject to the terms of the
+.\" Common Development and Distribution License (the "License").
+.\" You may not use this file except in compliance with the License.
+.\"
+.\" You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
+.\" or http://www.opensolaris.org/os/licensing.
+.\" See the License for the specific language governing permissions
+.\" and limitations under the License.
+.\"
+.\" When distributing Covered Code, include this CDDL HEADER in each
+.\" file and include the License file at usr/src/OPENSOLARIS.LICENSE.
+.\" If applicable, add the following below this CDDL HEADER, with the
+.\" fields enclosed by brackets "[]" replaced with your own identifying
+.\" information: Portions Copyright [yyyy] [name of copyright owner]
+.\"
+.\" Copyright (c) 2010, Sun Microsystems, Inc. All Rights Reserved.
+.\" Copyright 2011, Nexenta Systems, Inc. All Rights Reserved.
+.\" Copyright (c) 2011, Justin T. Gibbs <gibbs at FreeBSD.org>
+.\"
+.\" $FreeBSD: head/cddl/contrib/opensolaris/cmd/zpool/zpool.8 228206 2011-12-02 19:56:46Z mm $
+.\"
+.Dd November 28, 2011
+.Dt ZPOOL 8
+.Os
+.Sh NAME
+.Nm zpool
+.Nd configures ZFS storage pools
+.Sh SYNOPSIS
+.Nm
+.Op Fl \&?
+.Nm
+.Cm add
+.Op Fl fn
+.Ar pool vdev ...
+.Nm
+.Cm attach
+.Op Fl f
+.Ar pool device new_device
+.Nm
+.Cm clear
+.Op Fl F Op Fl n
+.Ar pool
+.Op Ar device
+.Nm
+.Cm create
+.Op Fl fn
+.Op Fl o Ar property Ns = Ns Ar value
+.Ar ...
+.Op Fl O Ar file-system-property Ns = Ns Ar value
+.Ar ...
+.Op Fl m Ar mountpoint
+.Op Fl R Ar root
+.Ar pool vdev ...
+.Nm
+.Cm destroy
+.Op Fl f
+.Ar pool
+.Nm
+.Cm detach
+.Ar pool device
+.Nm
+.Cm export
+.Op Fl f
+.Ar pool ...
+.Nm
+.Cm get
+.Ar all | property Ns Op , Ns Ar ...
+.Ar pool ...
+.Nm
+.Cm history
+.Op Fl il
+.Op Ar pool
+.Ar ...
+.Nm
+.Cm import
+.Op Fl d Ar dir | Fl c Ar cachefile
+.Op Fl D
+.Nm
+.Cm import
+.Op Fl o Ar mntopts
+.Op Fl o Ar property Ns = Ns Ar value
+.Ar ...
+.Op Fl d Ar dir | Fl c Ar cachefile
+.Op Fl D
+.Op Fl f
+.Op Fl m
+.Op Fl N
+.Op Fl R Ar root
+.Op Fl F Op Fl n
+.Fl a
+.Nm
+.Cm import
+.Op Fl o Ar mntopts
+.Op Fl o Ar property Ns = Ns Ar value
+.Ar ...
+.Op Fl d Ar dir | Fl c Ar cachefile
+.Op Fl D
+.Op Fl f
+.Op Fl m
+.Op Fl N
+.Op Fl R Ar root
+.Op Fl F Op Fl n
+.Ar pool | id
+.Op Ar newpool
+.Nm
+.Cm iostat
+.Op Fl T Cm d Ns | Ns Cm u
+.Op Fl v
+.Op Ar pool
+.Ar ...
+.Nm
+.Cm labelclear
+.Op Fl f
+.Ar device
+.Nm
+.Cm list
+.Op Fl H
+.Op Fl o Ar property Ns Op , Ns Ar ...
+.Op Fl T Cm d Ns | Ns Cm u
+.Op Ar pool
+.Ar ...
+.Op Ar inverval Op Ar count
+.Nm
+.Cm offline
+.Op Fl t
+.Ar pool device ...
+.Nm
+.Cm online
+.Op Fl e
+.Ar pool device ...
+.Nm
+.Cm reguid
+.Ar pool
+.Nm
+.Cm remove
+.Ar pool device ...
+.Nm
+.Cm replace
+.Op Fl f
+.Ar pool device
+.Op Ar new_device
+.Nm
+.Cm scrub
+.Op Fl s
+.Ar pool ...
+.Nm
+.Cm set
+.Ar property Ns = Ns Ar value pool
+.Nm
+.Cm split
+.Op Fl n
+.Op Fl R Ar altroot
+.Op Fl o Ar mntopts
+.Op Fl o Ar property Ns = Ns Ar value
+.Ar pool newpool
+.Op Ar device ...
+.Nm
+.Cm status
+.Op Fl vx
+.Op Fl T Cm d Ns | Ns Cm u
+.Op Ar pool
+.Ar ...
+.Op Ar interval Op Ar count
+.Nm
+.Cm upgrade
+.Op Fl v
+.Nm
+.Cm upgrade
+.Op Fl V Ar version
+.Fl a | Ar pool ...
+.Sh DESCRIPTION
+The
+.Nm
+command configures
+.Tn ZFS
+storage pools. A storage pool is a collection of devices that provides physical
+storage and data replication for
+.Tn ZFS
+datasets.
+.Pp
+All datasets within a storage pool share the same space. See
+.Xr zfs 8
+for information on managing datasets.
+.Ss Virtual Devices (vdevs)
+A
+.Qq virtual device
+.Pq No vdev
+describes a single device or a collection of devices organized according to 
+certain performance and fault characteristics. The following virtual devices
+are supported:
+.Bl -tag
+.It Sy disk
+A block device, typically located under
+.Pa /dev .
+.Tn ZFS
+can use individual slices or partitions, though the recommended mode of
+operation is to use whole disks. A disk can be specified by a full path to the
+device or the
+.Xr geom 4
+provider name. When given a whole disk,
+.Tn ZFS
+automatically labels the disk, if necessary.
+.It Sy file
 A regular file. The use of files as a backing store is strongly discouraged. It
 is designed primarily for experimental purposes, as the fault tolerance of a
-file is only as good as the file system of which it is a part. A file must be
+file is only as good the file system of which it is a part. A file must be
 specified by a full path.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBmirror\fR\fR
-.ad
-.RS 10n
+.It Sy mirror
 A mirror of two or more devices. Data is replicated in an identical fashion
-across all components of a mirror. A mirror with \fIN\fR disks of size \fIX\fR
-can hold \fIX\fR bytes and can withstand (\fIN-1\fR) devices failing before
-data integrity is compromised.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBraidz\fR\fR
-.ad
-.br
-.na
-\fB\fBraidz1\fR\fR
-.ad
-.br
-.na
-\fB\fBraidz2\fR\fR
-.ad
-.br
-.na
-\fB\fBraidz3\fR\fR
-.ad
-.RS 10n
-A variation on \fBRAID-5\fR that allows for better distribution of parity and
-eliminates the "\fBRAID-5\fR write hole" (in which data and parity become
-inconsistent after a power loss). Data and parity is striped across all disks
-within a \fBraidz\fR group.
-.sp
-A \fBraidz\fR group can have single-, double- , or triple parity, meaning that
-the \fBraidz\fR group can sustain one, two, or three failures, respectively,
-without losing any data. The \fBraidz1\fR \fBvdev\fR type specifies a
-single-parity \fBraidz\fR group; the \fBraidz2\fR \fBvdev\fR type specifies a
-double-parity \fBraidz\fR group; and the \fBraidz3\fR \fBvdev\fR type specifies
-a triple-parity \fBraidz\fR group. The \fBraidz\fR \fBvdev\fR type is an alias
-for \fBraidz1\fR.
-.sp
-A \fBraidz\fR group with \fIN\fR disks of size \fIX\fR with \fIP\fR parity
-disks can hold approximately (\fIN-P\fR)*\fIX\fR bytes and can withstand
-\fIP\fR device(s) failing before data integrity is compromised. The minimum
-number of devices in a \fBraidz\fR group is one more than the number of parity
-disks. The recommended number is between 3 and 9 to help increase performance.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBspare\fR\fR
-.ad
-.RS 10n
-A special pseudo-\fBvdev\fR which keeps track of available hot spares for a
-pool. For more information, see the "Hot Spares" section.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBlog\fR\fR
-.ad
-.RS 10n
+across all components of a mirror. A mirror with
+.Em N
+disks of size
+.Em X
+can hold
+.Em X
+bytes and can withstand
+.Pq Em N-1
+devices failing before data integrity is compromised.
+.It Sy raidz
+(or
+.Sy raidz1 raidz2 raidz3 ) .
+A variation on
+.Sy RAID-5
+that allows for better distribution of parity and eliminates the
+.Qq Sy RAID-5
+write hole (in which data and parity become inconsistent after a power loss).
+Data and parity is striped across all disks within a
+.No raidz
+group.
+.Pp
+A
+.No raidz
+group can have single-, double- , or triple parity, meaning that the
+.No raidz
+group can sustain one, two, or three failures, respectively, without
+losing any data. The 
+.Sy raidz1 No vdev
+type specifies a single-parity
+.No raidz
+group; the
+.Sy raidz2 No vdev
+type specifies a double-parity
+.No raidz
+group; and the
+.Sy raidz3 No vdev
+type specifies a triple-parity
+.No raidz
+group. The
+.Sy raidz No vdev
+type is an alias for
+.Sy raidz1 .
+.Pp
+A
+.No raidz
+group with
+.Em N
+disks of size
+.Em X
+with
+.Em P
+parity disks can hold approximately
+.Sm off
+.Pq Em N-P
+*X
+.Sm on
+bytes and can withstand
+.Em P
+device(s) failing before data integrity is compromised. The minimum number of
+devices in a
+.No raidz
+group is one more than the number of parity disks. The
+recommended number is between 3 and 9 to help increase performance.
+.It Sy spare
+A special
+.No pseudo- Ns No vdev
+which keeps track of available hot spares for a pool.
+For more information, see the
+.Qq Sx Hot Spares
+section.
+.It Sy log
 A separate-intent log device. If more than one log device is specified, then
 writes are load-balanced between devices. Log devices can be mirrored. However,
-\fBraidz\fR \fBvdev\fR types are not supported for the intent log. For more
-information, see the "Intent Log" section.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBcache\fR\fR
-.ad
-.RS 10n
-A device used to cache storage pool data. A cache device cannot be cannot be
-configured as a mirror or \fBraidz\fR group. For more information, see the
-"Cache Devices" section.
-.RE
-
-.sp
-.LP
-Virtual devices cannot be nested, so a mirror or \fBraidz\fR virtual device can
-only contain files or disks. Mirrors of mirrors (or other combinations) are not
+.No raidz
+.No vdev
+types are not supported for the intent log. For more information,
+see the 
+.Qq Sx Intent Log
+section.
+.It Sy cache
+A device used to cache storage pool data. A cache device cannot be configured
+as a mirror or
+.No raidz
+group. For more information, see the
+.Qq Sx Cache Devices
+section.
+.El
+.Pp
+Virtual devices cannot be nested, so a mirror or
+.No raidz
+virtual device can only
+contain files or disks. Mirrors of mirrors (or other combinations) are not
 allowed.
-.sp
-.LP
+.Pp
 A pool can have any number of virtual devices at the top of the configuration
-(known as "root vdevs"). Data is dynamically distributed across all top-level
-devices to balance data among devices. As new virtual devices are added,
-\fBZFS\fR automatically places data on the newly available devices.
-.sp
-.LP
+(known as
+.Qq root
+.No vdev Ns s).
+Data is dynamically distributed across all top-level devices to balance data 
+among devices. As new virtual devices are added,
+.Tn ZFS
+automatically places data on the newly available devices.
+.Pp
 Virtual devices are specified one at a time on the command line, separated by
-whitespace. The keywords "mirror" and "raidz" are used to distinguish where a
-group ends and another begins. For example, the following creates two root
-vdevs, each a mirror of two disks:
-.sp
-.in +2
-.nf
-# \fBzpool create mypool mirror da0 da1 mirror da2 da3\fR
-.fi
-.in -2
-.sp
-
-.SS "Device Failure and Recovery"
-.sp
-.LP
-\fBZFS\fR supports a rich set of mechanisms for handling device failure and
-data corruption. All metadata and data is checksummed, and \fBZFS\fR
+whitespace. The keywords 
+.Qq mirror
+and
+.Qq raidz
+are used to distinguish where a group ends and another begins. For example, the
+following creates two root
+.No vdev Ns s,
+each a mirror of two disks:
+.Bd -literal -offset 2n
+.Li # Ic zpool create mypool mirror da0 da1 mirror da2 da3
+.Ed
+.Ss Device Failure and Recovery
+.Tn ZFS
+supports a rich set of mechanisms for handling device failure and data
+corruption. All metadata and data is checksummed, and
+.Tn ZFS
 automatically repairs bad data from a good copy when corruption is detected.
-.sp
-.LP
+.Pp
 In order to take advantage of these features, a pool must make use of some form
-of redundancy, using either mirrored or \fBraidz\fR groups. While \fBZFS\fR
-supports running in a non-redundant configuration, where each root vdev is
-simply a disk or file, this is strongly discouraged. A single case of bit
+of redundancy, using either mirrored or
+.No raidz
+groups. While
+.Tn ZFS
+supports running in a non-redundant configuration, where each root
+.No vdev
+is simply a disk or file, this is strongly discouraged. A single case of bit
 corruption can render some or all of your data unavailable.
-.sp
-.LP
+.Pp
 A pool's health status is described by one of three states: online, degraded,
 or faulted. An online pool has all devices operating normally. A degraded pool
 is one in which one or more devices have failed, but the data is still
 available due to a redundant configuration. A faulted pool has corrupted
 metadata, or one or more faulted devices, and insufficient replicas to continue
 functioning.
-.sp
-.LP
-The health of the top-level vdev, such as mirror or \fBraidz\fR device, is
-potentially impacted by the state of its associated vdevs, or component
-devices. A top-level vdev or component device is in one of the following
-states:
-.sp
-.ne 2
-.na
-\fB\fBDEGRADED\fR\fR
-.ad
-.RS 12n
-One or more top-level vdevs is in the degraded state because one or more
+.Pp
+The health of the top-level
+.No vdev ,
+such as mirror or
+.No raidz
+device, is
+potentially impacted by the state of its associated
+.No vdev Ns s,
+or component devices. A top-level
+.No vdev
+or component device is in one of the following states:
+.Bl -tag -width "DEGRADED"
+.It Sy DEGRADED
+One or more top-level
+.No vdev Ns s
+is in the degraded state because one or more
 component devices are offline. Sufficient replicas exist to continue
 functioning.
-.sp
+.Pp
 One or more component devices is in the degraded or faulted state, but
 sufficient replicas exist to continue functioning. The underlying conditions
 are as follows:
-.RS +4
-.TP
-.ie t \(bu
-.el o
+.Bl -bullet -offset 2n
+.It
 The number of checksum errors exceeds acceptable levels and the device is
-degraded as an indication that something may be wrong. \fBZFS\fR continues to
-use the device as necessary.
-.RE
-.RS +4
-.TP
-.ie t \(bu
-.el o
-The number of I/O errors exceeds acceptable levels. The device could not be
+degraded as an indication that something may be wrong.
+.Tn ZFS
+continues to use the device as necessary.
+.It
+The number of
+.Tn I/O
+errors exceeds acceptable levels. The device could not be
 marked as faulted because there are insufficient replicas to continue
 functioning.
-.RE
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBFAULTED\fR\fR
-.ad
-.RS 12n
-One or more top-level vdevs is in the faulted state because one or more
+.El
+.It Sy FAULTED
+One or more top-level
+.No vdev Ns s
+is in the faulted state because one or more
 component devices are offline. Insufficient replicas exist to continue
 functioning.
-.sp
+.Pp
 One or more component devices is in the faulted state, and insufficient
 replicas exist to continue functioning. The underlying conditions are as
 follows:
-.RS +4
-.TP
-.ie t \(bu
-.el o
+.Bl -bullet -offset 2n
+.It
 The device could be opened, but the contents did not match expected values.
-.RE
-.RS +4
-.TP
-.ie t \(bu
-.el o
-The number of I/O errors exceeds acceptable levels and the device is faulted to
+.It
+The number of
+.Tn I/O
+errors exceeds acceptable levels and the device is faulted to
 prevent further use of the device.
-.RE
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBOFFLINE\fR\fR
-.ad
-.RS 12n
-The device was explicitly taken offline by the "\fBzpool offline\fR" command.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBONLINE\fR\fR
-.ad
-.RS 12n
+.El
+.It Sy OFFLINE
+The device was explicitly taken offline by the
+.Qq Nm Cm offline
+command.
+.It Sy ONLINE
 The device is online and functioning.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBREMOVED\fR\fR
-.ad
-.RS 12n
+.It Sy REMOVED
 The device was physically removed while the system was running. Device removal
 detection is hardware-dependent and may not be supported on all platforms.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBUNAVAIL\fR\fR
-.ad
-.RS 12n
+.It Sy UNAVAIL
 The device could not be opened. If a pool is imported when a device was
 unavailable, then the device will be identified by a unique identifier instead
 of its path since the path was never correct in the first place.
-.RE
-
-.sp
-.LP
-If a device is removed and later re-attached to the system, \fBZFS\fR attempts
-to put the device online automatically. Device attach detection is
+.El
+.Pp
+If a device is removed and later reattached to the system,
+.Tn ZFS
+attempts to put the device online automatically. Device attach detection is
 hardware-dependent and might not be supported on all platforms.
-.SS "Hot Spares"
-.sp
-.LP
-\fBZFS\fR allows devices to be associated with pools as "hot spares". These
-devices are not actively used in the pool, but when an active device fails, it
-is automatically replaced by a hot spare. To create a pool with hot spares,
-specify a "spare" \fBvdev\fR with any number of devices. For example,
-.sp
-.in +2
-.nf
-# zpool create pool mirror da0 da1 spare da2 da3
-.fi
-.in -2
-.sp
-
-.sp
-.LP
-Spares can be shared across multiple pools, and can be added with the "\fBzpool
-add\fR" command and removed with the "\fBzpool remove\fR" command. Once a spare
-replacement is initiated, a new "spare" \fBvdev\fR is created within the
-configuration that will remain there until the original device is replaced. At
-this point, the hot spare becomes available again if another device fails.
-.sp
-.LP
+.Ss Hot Spares
+.Tn ZFS
+allows devices to be associated with pools as
+.Qq hot spares .
+These devices are not actively used in the pool, but when an active device
+fails, it is automatically replaced by a hot spare. To create a pool with hot
+spares, specify a 
+.Qq spare
+.No vdev
+with any number of devices. For example,
+.Bd -literal -offset 2n
+.Li # Ic zpool create pool mirror da0 da1 spare da2 da3
+.Ed
+.Pp
+Spares can be shared across multiple pools, and can be added with the
+.Qq Nm Cm add
+command and removed with the
+.Qq Nm Cm remove
+command. Once a spare replacement is initiated, a new "spare"
+.No vdev
+is created
+within the configuration that will remain there until the original device is
+replaced. At this point, the hot spare becomes available again if another
+device fails.
+.Pp
 If a pool has a shared spare that is currently being used, the pool can not be
 exported since other pools may use this shared spare, which may lead to
 potential data corruption.
-.sp
-.LP
+.Pp
 An in-progress spare replacement can be cancelled by detaching the hot spare.
 If the original faulted device is detached, then the hot spare assumes its
 place in the configuration, and is removed from the spare list of all active
 pools.
-.sp
-.LP
+.Pp
 Spares cannot replace log devices.
-.SS "Intent Log"
-.sp
-.LP
-The \fBZFS\fR Intent Log (\fBZIL\fR) satisfies \fBPOSIX\fR requirements for
-synchronous transactions. For instance, databases often require their
-transactions to be on stable storage devices when returning from a system call.
-\fBNFS\fR and other applications can also use \fBfsync\fR() to ensure data
-stability. By default, the intent log is allocated from blocks within the main
-pool. However, it might be possible to get better performance using separate
-intent log devices such as \fBNVRAM\fR or a dedicated disk. For example:
-.sp
-.in +2
-.nf
-\fB# zpool create pool da0 da1 log da3\fR
-.fi
-.in -2
-.sp
-
-.sp
-.LP
+.Ss Intent Log
+The 
+.Tn ZFS
+Intent Log
+.Pq Tn ZIL
+satisfies
+.Tn POSIX
+requirements for synchronous transactions. For instance, databases often
+require their transactions to be on stable storage devices when returning from
+a system call.
+.Tn NFS
+and other applications can also use
+.Xr fsync 2
+to ensure data stability. By default, the intent log is allocated from blocks
+within the main pool. However, it might be possible to get better performance
+using separate intent log devices such as
+.Tn NVRAM
+or a dedicated disk. For example:
+.Bd -literal -offset 2n
+.Li # Ic zpool create pool da0 da1 log da2
+.Ed
+.Pp
 Multiple log devices can also be specified, and they can be mirrored. See the
-EXAMPLES section for an example of mirroring multiple log devices.
-.sp
-.LP
-Log devices can be added, replaced, attached, detached, and imported and
-exported as part of the larger pool. Mirrored log devices can be removed by
-specifying the top-level mirror for the log.
-.SS "Cache Devices"
-.sp
-.LP
+.Sx EXAMPLES
+section for an example of mirroring multiple log devices.
+.Pp
+Log devices can be added, replaced, attached, detached, imported and exported
+as part of the larger pool. Mirrored log devices can be removed by specifying
+the top-level mirror for the log.
+.Ss Cache devices
 Devices can be added to a storage pool as "cache devices." These devices
 provide an additional layer of caching between main memory and disk. For
 read-heavy workloads, where the working set size is much larger than what can
@@ -494,172 +494,150 @@
 set to be served from low latency media. Using cache devices provides the
 greatest performance improvement for random read-workloads of mostly static
 content.
-.sp
-.LP
-To create a pool with cache devices, specify a "cache" \fBvdev\fR with any
-number of devices. For example:
-.sp
-.in +2
-.nf
-\fB# zpool create pool da0 da1 cache da2 da3\fR
-.fi
-.in -2
-.sp
-
-.sp
-.LP
-Cache devices cannot be mirrored or part of a \fBraidz\fR configuration. If a
-read error is encountered on a cache device, that read \fBI/O\fR is reissued to
-the original storage pool device, which might be part of a mirrored or
-\fBraidz\fR configuration.
-.sp
-.LP
+.Pp
+To create a pool with cache devices, specify a "cache"
+.No vdev
+with any number of devices. For example:
+.Bd -literal -offset 2n
+.Li # Ic zpool create pool da0 da1 cache da2 da3
+.Ed
+.Pp
+Cache devices cannot be mirrored or part of a
+.No raidz
+configuration. If a read
+error is encountered on a cache device, that read
+.Tn I/O
+is reissued to the original storage pool device, which might be part of a
+mirrored or
+.No raidz
+configuration.
+.Pp
 The content of the cache devices is considered volatile, as is the case with
 other system caches.
-.SS "Properties"
-.sp
-.LP
+.Ss Properties
 Each pool has several properties associated with it. Some properties are
 read-only statistics while others are configurable and change the behavior of
 the pool. The following are read-only properties:
-.sp
-.ne 2
-.na
-\fB\fBavailable\fR\fR
-.ad
-.RS 20n
-Amount of storage available within the pool. This property can also be referred
-to by its shortened column name, "avail".
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBcapacity\fR\fR
-.ad
-.RS 20n
+.Bl -tag -width "dedupratio"
+.It Sy alloc
+Amount of storage space within the pool that has been physically allocated.
+.It Sy capacity
 Percentage of pool space used. This property can also be referred to by its
 shortened column name, "cap".
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBhealth\fR\fR
-.ad
-.RS 20n
-The current health of the pool. Health can be "\fBONLINE\fR", "\fBDEGRADED\fR",
-"\fBFAULTED\fR", " \fBOFFLINE\fR", "\fBREMOVED\fR", or "\fBUNAVAIL\fR".
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBguid\fR\fR
-.ad
-.RS 20n
+.It Sy comment
+A text string consisting of printable ASCII characters that will be stored
+such that it is available even if the pool becomes faulted.  An administrator
+can provide additional information about a pool using this property.
+.It Sy dedupratio
+The deduplication ratio specified for a pool, expressed as a multiplier.
+For example, a
+.S dedupratio
+value of 1.76 indicates that 1.76 units of data were stored but only 1 unit of disk space was actually consumed. See
+.Xr zfs 8
+for a description of the deduplication feature.
+.It Sy free
+Number of blocks within the pool that are not allocated.
+.It Sy guid
 A unique identifier for the pool.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBsize\fR\fR
-.ad
-.RS 20n
+.It Sy health
+The current health of the pool. Health can be
+.Qq Sy ONLINE ,
+.Qq Sy DEGRADED ,
+.Qq Sy FAULTED ,
+.Qq Sy OFFLINE ,
+.Qq Sy REMOVED ,
+or
+.Qq Sy UNAVAIL .
+.It Sy size
 Total size of the storage pool.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBused\fR\fR
-.ad
-.RS 20n
+.It Sy used
 Amount of storage space used within the pool.
-.RE
-
-.sp
-.LP
+.El
+.Pp
 These space usage properties report actual physical space available to the
 storage pool. The physical space can be different from the total amount of
 space that any contained datasets can actually use. The amount of space used in
-a \fBraidz\fR configuration depends on the characteristics of the data being
-written. In addition, \fBZFS\fR reserves some space for internal accounting
-that the \fBzfs\fR(8) command takes into account, but the \fBzpool\fR command
-does not. For non-full pools of a reasonable size, these effects should be
-invisible. For small pools, or pools that are close to being completely full,
-these discrepancies may become more noticeable.
-.sp
-.LP
+a
+.No raidz
+configuration depends on the characteristics of the data being written.
+In addition,
+.Tn ZFS
+reserves some space for internal accounting that the
+.Xr zfs 8
+command takes into account, but the
+.Xr zpool 8
+command does not. For non-full pools of a reasonable size, these effects should
+be invisible. For small pools, or pools that are close to being completely
+full, these discrepancies may become more noticeable.
+.Pp
 The following property can be set at creation time and import time:
-.sp
-.ne 2
-.na
-\fB\fBaltroot\fR\fR
-.ad
-.sp .6
-.RS 4n
+.Bl -tag -width 2n
+.It Sy altroot
 Alternate root directory. If set, this directory is prepended to any mount
 points within the pool. This can be used when examining an unknown pool where
 the mount points cannot be trusted, or in an alternate boot environment, where
-the typical paths are not valid. \fBaltroot\fR is not a persistent property. It
-is valid only while the system is up. Setting \fBaltroot\fR defaults to using
-\fBcachefile\fR=none, though this may be overridden using an explicit setting.
-.RE
-
-.sp
-.LP
+the typical paths are not valid.
+.Sy altroot
+is not a persistent property. It is valid only while the system is up.
+Setting
+.Sy altroot 
+defaults to using
+.Cm cachefile=none ,
+though this may be overridden using an explicit setting.
+.El
+.Pp
+The following property can only be set at import time:
+.Bl -tag -width 2n
+.It Sy readonly Ns = Ns Cm on No | Cm off
+If set to
+.Cm on ,
+pool will be imported in read-only mode with the following restrictions:
+.Bl -bullet -offset 2n
+.It
+Synchronous data in the intent log will not be accessible
+.It
+Properties of the pool can not be changed
+.It
+Datasets of this pool can only be mounted read-only
+.It
+To write to a read-only pool, a export and import of the pool is required.
+.El
+.El
+.Pp
 The following properties can be set at creation time and import time, and later
-changed with the \fBzpool set\fR command:
-.sp
-.ne 2
-.na
-\fB\fBautoexpand\fR=\fBon\fR | \fBoff\fR\fR
-.ad
-.sp .6
-.RS 4n
+changed with the
+.Ic zpool set
+command:
+.Bl -tag -width 2n
+.It Sy autoexpand Ns = Ns Cm on No | Cm off
 Controls automatic pool expansion when the underlying LUN is grown. If set to
-\fBon\fR, the pool will be resized according to the size of the expanded
-device. If the device is part of a mirror or \fBraidz\fR then all devices
-within that mirror/\fBraidz\fR group must be expanded before the new space is
-made available to the pool. The default behavior is \fBoff\fR. This property
-can also be referred to by its shortened column name, \fBexpand\fR.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBautoreplace\fR=\fBon\fR | \fBoff\fR\fR
-.ad
-.sp .6
-.RS 4n
-Controls automatic device replacement. If set to "\fBoff\fR", device
-replacement must be initiated by the administrator by using the "\fBzpool
-replace\fR" command. If set to "\fBon\fR", any new device, found in the same
+.Qq Cm on ,
+the pool will be resized according to the size of the expanded
+device. If the device is part of a mirror or
+.No raidz
+then all devices within that
+.No mirror/ Ns No raidz
+group must be expanded before the new space is made available to
+the pool. The default behavior is
+.Qq off .
+This property can also be referred to by its shortened column name,
+.Sy expand .
+.It Sy autoreplace Ns = Ns Cm on No | Cm off
+Controls automatic device replacement. If set to
+.Qq Cm off ,
+device replacement must be initiated by the administrator by using the 
+.Qq Nm Cm replace
+command. If set to 
+.Qq Cm on ,
+any new device, found in the same
 physical location as a device that previously belonged to the pool, is
-automatically formatted and replaced. The default behavior is "\fBoff\fR". This
-property can also be referred to by its shortened column name, "replace".
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBbootfs\fR=\fIpool\fR/\fIdataset\fR\fR
-.ad
-.sp .6
-.RS 4n
+automatically formatted and replaced. The default behavior is
+.Qq Cm off .
+This property can also be referred to by its shortened column name, "replace".
+.It Sy bootfs Ns = Ns Ar pool Ns / Ns Ar dataset
 Identifies the default bootable dataset for the root pool. This property is
 expected to be set mainly by the installation and upgrade programs.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBcachefile\fR=\fIpath\fR | \fBnone\fR\fR
-.ad
-.sp .6
-.RS 4n
+.It Sy cachefile Ns = Ns Ar path No | Cm none
 Controls the location of where the pool configuration is cached. Discovering
 all pools on system startup requires a cached copy of the configuration data
 that is stored on the root file system. All pools in this cache are
@@ -667,1137 +645,1083 @@
 install and clustering, need to cache this information in a different location
 so that pools are not automatically imported. Setting this property caches the
 pool configuration in a different location that can later be imported with
-"\fBzpool import -c\fR". Setting it to the special value "\fBnone\fR" creates a
-temporary pool that is never cached, and the special value \fB\&''\fR (empty
-string) uses the default location.
-.sp
-Multiple pools can share the same cache file. Because the kernel destroys and
-recreates this file when pools are added and removed, care should be taken when
-attempting to access this file. When the last pool using a \fBcachefile\fR is
-exported or destroyed, the file is removed.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBdelegation\fR=\fBon\fR | \fBoff\fR\fR
-.ad
-.sp .6
-.RS 4n
+.Qq Nm Cm import Fl c .
+Setting it to the special value
+.Qq Cm none
+creates a temporary pool that is never cached, and the special value 
+.Cm ''
+(empty string) uses the default location.
+.It Sy dedupditto Ns = Ns Ar number
+Threshold for the number of block ditto copies. If the reference count for a
+deduplicated block increases above this number, a new ditto copy of this block
+is automatically stored. Deafult setting is
+.Cm 0 .
+.It Sy delegation Ns = Ns Cm on No | Cm off
 Controls whether a non-privileged user is granted access based on the dataset
-permissions defined on the dataset. See \fBzfs\fR(8) for more information on
-\fBZFS\fR delegated administration.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBfailmode\fR=\fBwait\fR | \fBcontinue\fR | \fBpanic\fR\fR
-.ad
-.sp .6
-.RS 4n
+permissions defined on the dataset. See
+.Xr zfs 8
+for more information on
+.Tn ZFS
+delegated administration.
+.It Sy failmode Ns = Ns Cm wait No | Cm continue No | Cm panic
 Controls the system behavior in the event of catastrophic pool failure. This
 condition is typically a result of a loss of connectivity to the underlying
 storage device(s) or a failure of all devices within the pool. The behavior of
 such an event is determined as follows:
-.sp
-.ne 2
-.na
-\fB\fBwait\fR\fR
-.ad
-.RS 12n
-Blocks all \fBI/O\fR access until the device connectivity is recovered and the
-errors are cleared. This is the default behavior.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBcontinue\fR\fR
-.ad
-.RS 12n
-Returns \fBEIO\fR to any new write \fBI/O\fR requests but allows reads to any
-of the remaining healthy devices. Any write requests that have yet to be
-committed to disk would be blocked.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBpanic\fR\fR
-.ad
-.RS 12n
+.Bl -tag -width indent
+.It Sy wait
+Blocks all
+.Tn I/O
+access until the device connectivity is recovered and the errors are cleared.
+This is the default behavior.
+.It Sy continue
+Returns
+.Em EIO
+to any new write
+.Tn I/O
+requests but allows reads to any of the remaining healthy devices. Any write
+requests that have yet to be committed to disk would be blocked.
+.It Sy panic
 Prints out a message to the console and generates a system crash dump.
-.RE
-
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBlistsnaps\fR=on | off\fR
-.ad
-.sp .6
-.RS 4n
+.El
+.It Sy listsnaps Ns = Ns Cm on No | Cm off
 Controls whether information about snapshots associated with this pool is
-output when "\fBzfs list\fR" is run without the \fB-t\fR option. The default
-value is "off".
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBversion\fR=\fIversion\fR\fR
-.ad
-.sp .6
-.RS 4n
+output when
+.Qq Nm zfs Cm list
+is run without the
+.Fl t
+option. The default value is
+.Cm off .
+.It Sy version Ns = Ns Ar version
 The current on-disk version of the pool. This can be increased, but never
-decreased. The preferred method of updating pools is with the "\fBzpool
-upgrade\fR" command, though this property can be used when a specific version
-is needed for backwards compatibility. This property can be any number between
-1 and the current version reported by "\fBzpool upgrade -v\fR".
-.RE
-
-.SS "Subcommands"
-.sp
-.LP
+decreased. The preferred method of updating pools is with the
+.Qq Nm Cm upgrade
+command, though this property can be used when a specific version is needed
+for backwards compatibility. This property can be any number between 1 and the
+current version reported by
+.Qo Ic zpool upgrade -v Qc .
+.El
+.Sh SUBCOMMANDS
 All subcommands that modify state are logged persistently to the pool in their
 original form.
-.sp
-.LP
-The \fBzpool\fR command provides subcommands to create and destroy storage
-pools, add capacity to storage pools, and provide information about the storage
-pools. The following subcommands are supported:
-.sp
-.ne 2
-.na
-\fB\fBzpool\fR \fB-?\fR\fR
-.ad
-.sp .6
-.RS 4n
+.Pp
+The
+.Nm
+command provides subcommands to create and destroy storage pools, add capacity
+to storage pools, and provide information about the storage pools. The following
+subcommands are supported:
+.Bl -tag -width 2n
+.It Xo
+.Nm
+.Op Fl \&?
+.Xc
+.Pp
 Displays a help message.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzpool add\fR [\fB-fn\fR] \fIpool\fR \fIvdev\fR ...\fR
-.ad
-.sp .6
-.RS 4n
-Adds the specified virtual devices to the given pool. The \fIvdev\fR
-specification is described in the "Virtual Devices" section. The behavior of
-the \fB-f\fR option, and the device checks performed are described in the
-"zpool create" subcommand.
-.sp
-.ne 2
-.na
-\fB\fB-f\fR\fR
-.ad
-.RS 6n
-Forces use of \fBvdev\fRs, even if they appear in use or specify a conflicting
-replication level. Not all devices can be overridden in this manner.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-n\fR\fR
-.ad
-.RS 6n
+.It Xo
+.Nm
+.Cm add
+.Op Fl fn
+.Ar pool vdev ...
+.Xc
+.Pp
+Adds the specified virtual devices to the given pool. The
+.No vdev
+specification is described in the
+.Qq Sx Virtual Devices
+section. The behavior of the
+.Fl f
+option, and the device checks performed are described in the
+.Qq Nm Cm create
+subcommand.
+.Bl -tag -width indent
+.It Fl f
+Forces use of
+.Ar vdev ,
+even if they appear in use or specify a conflicting replication level.
+Not all devices can be overridden in this manner.
+.It Fl n
 Displays the configuration that would be used without actually adding the
-\fBvdev\fRs. The actual pool creation can still fail due to insufficient
-privileges or device sharing.
-.RE
-
+.Ar vdev Ns s.
+The actual pool creation can still fail due to insufficient privileges or device
+sharing.
+.Pp
 Do not add a disk that is currently configured as a quorum device to a zpool.
 After a disk is in the pool, that disk can then be configured as a quorum
 device.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzpool attach\fR [\fB-f\fR] \fIpool\fR \fIdevice\fR \fInew_device\fR\fR
-.ad
-.sp .6
-.RS 4n
-Attaches \fInew_device\fR to an existing \fBzpool\fR device. The existing
-device cannot be part of a \fBraidz\fR configuration. If \fIdevice\fR is not
-currently part of a mirrored configuration, \fIdevice\fR automatically
-transforms into a two-way mirror of \fIdevice\fR and \fInew_device\fR. If
-\fIdevice\fR is part of a two-way mirror, attaching \fInew_device\fR creates a
-three-way mirror, and so on. In either case, \fInew_device\fR begins to
-resilver immediately.
-.sp
-.ne 2
-.na
-\fB\fB-f\fR\fR
-.ad
-.RS 6n
-Forces use of \fInew_device\fR, even if its appears to be in use. Not all
-devices can be overridden in this manner.
-.RE
-
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzpool clear\fR \fIpool\fR [\fIdevice\fR] ...\fR
-.ad
-.sp .6
-.RS 4n
+.El
+.It Xo
+.Nm
+.Cm attach
+.Op Fl f
+.Ar pool device new_device
+.Xc
+.Pp
+Attaches
+.Ar new_device
+to an existing
+.Sy zpool
+device. The existing device cannot be part of a
+.No raidz
+configuration. If
+.Ar device
+is not currently part of a mirrored configuration,
+.Ar device
+automatically transforms into a two-way mirror of
+.Ar device No and Ar new_device .
+If
+.Ar device
+is part of a two-way mirror, attaching
+.Ar new_device
+creates a three-way mirror, and so on. In either case,
+.Ar new_device
+begins to resilver immediately.
+.Bl -tag -width indent
+.It Fl f
+Forces use of
+.Ar new_device ,
+even if its appears to be in use. Not all devices can be overridden in this
+manner.
+.El
+.It Xo
+.Nm
+.Cm clear
+.Op Fl F Op Fl n
+.Ar pool
+.Op Ar device
+.Xc
+.Pp
 Clears device errors in a pool. If no arguments are specified, all device
 errors within the pool are cleared. If one or more devices is specified, only
 those errors associated with the specified device or devices are cleared.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzpool create\fR [\fB-fn\fR] [\fB-o\fR \fIproperty=value\fR] ... [\fB-O\fR
-\fIfile-system-property=value\fR] ... [\fB-m\fR \fImountpoint\fR] [\fB-R\fR
-\fIroot\fR] \fIpool\fR \fIvdev\fR ...\fR
-.ad
-.sp .6
-.RS 4n
+.Bl -tag -width indent
+.It Fl F
+Initiates recovery mode for an unopenable pool. Attempts to discard the last
+few transactions in the pool to return it to an openable state. Not all damaged
+pools can be recovered by using this option. If successful, the data from the
+discarded transactions is irretrievably lost.
+.It Fl n
+Used in combination with the
+.Fl F
+flag. Check whether discarding transactions would make the pool openable, but
+do not actually discard any transactions.
+.El
+.It Xo
+.Nm
+.Cm create
+.Op Fl fn
+.Op Fl o Ar property Ns = Ns Ar value
+.Ar ...
+.Op Fl O Ar file-system-property Ns = Ns Ar value
+.Ar ...
+.Op Fl m Ar mountpoint
+.Op Fl R Ar root
+.Ar pool vdev ...
+.Xc
+.Pp
 Creates a new storage pool containing the virtual devices specified on the
 command line. The pool name must begin with a letter, and can only contain
 alphanumeric characters as well as underscore ("_"), dash ("-"), and period
 ("."). The pool names "mirror", "raidz", "spare" and "log" are reserved, as are
-names beginning with the pattern "c[0-9]". The \fBvdev\fR specification is
-described in the "Virtual Devices" section.
-.sp
+names beginning with the pattern "c[0-9]". The
+.No vdev
+specification is described in the
+.Qq Sx Virtual Devices
+section.
+.Pp
 The command verifies that each device specified is accessible and not currently
 in use by another subsystem. There are some uses, such as being currently
 mounted, or specified as the dedicated dump device, that prevents a device from
-ever being used by \fBZFS\fR. Other uses, such as having a preexisting
-\fBUFS\fR file system, can be overridden with the \fB-f\fR option.
-.sp
+ever being used by
+.Tn ZFS
+Other uses, such as having a preexisting
+.Sy UFS
+file system, can be overridden with the
+.Fl f
+option.
+.Pp
 The command also checks that the replication strategy for the pool is
 consistent. An attempt to combine redundant and non-redundant storage in a
-single pool, or to mix disks and files, results in an error unless \fB-f\fR is
-specified. The use of differently sized devices within a single \fBraidz\fR or
-mirror group is also flagged as an error unless \fB-f\fR is specified.
-.sp
-Unless the \fB-R\fR option is specified, the default mount point is
-"/\fIpool\fR". The mount point must not exist or must be empty, or else the
-root dataset cannot be mounted. This can be overridden with the \fB-m\fR
+single pool, or to mix disks and files, results in an error unless
+.Fl f
+is specified. The use of differently sized devices within a single
+.No raidz
+or mirror group is also flagged as an error unless
+.Fl f
+is specified.
+.Pp
+Unless the
+.Fl R
+option is specified, the default mount point is
+.Qq Pa /pool .
+The mount point must not exist or must be empty, or else the
+root dataset cannot be mounted. This can be overridden with the
+.Fl m
 option.
-.sp
-.ne 2
-.na
-\fB\fB-f\fR\fR
-.ad
-.sp .6
-.RS 4n
-Forces use of \fBvdev\fRs, even if they appear in use or specify a conflicting
-replication level. Not all devices can be overridden in this manner.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-n\fR\fR
-.ad
-.sp .6
-.RS 4n
+.Bl -tag -width indent
+.It Fl f
+Forces use of 
+.Ar vdev Ns s,
+even if they appear in use or specify a conflicting replication level.
+Not all devices can be overridden in this manner.
+.It Fl n
 Displays the configuration that would be used without actually creating the
 pool. The actual pool creation can still fail due to insufficient privileges or
 device sharing.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-o\fR \fIproperty=value\fR [\fB-o\fR \fIproperty=value\fR] ...\fR
-.ad
-.sp .6
-.RS 4n
-Sets the given pool properties. See the "Properties" section for a list of
-valid properties that can be set.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-O\fR \fIfile-system-property=value\fR\fR
-.ad
-.br
-.na
-\fB[\fB-O\fR \fIfile-system-property=value\fR] ...\fR
-.ad
-.sp .6
-.RS 4n
+.It Xo
+.Fl o Ar property Ns = Ns Ar value
+.Op Fl o Ar property Ns = Ns Ar value
+.Ar ...
+.Xc
+Sets the given pool properties. See the
+.Qq Sx Properties
+section for a list of valid properties that can be set.
+.It Xo
+.Fl O
+.Ar file-system-property Ns = Ns Ar value
+.Op Fl O Ar file-system-property Ns = Ns Ar value
+.Ar ...
+.Xc
 Sets the given file system properties in the root file system of the pool. See
-the "Properties" section of \fBzfs\fR(8) for a list of valid properties that
+.Xr zfs 8 Properties
+for a list of valid properties that
 can be set.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-R\fR \fIroot\fR\fR
-.ad
-.sp .6
-.RS 4n
-Equivalent to "-o cachefile=none,altroot=\fIroot\fR"
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-m\fR \fImountpoint\fR\fR
-.ad
-.sp .6
-.RS 4n
+.It Fl R Ar root
+Equivalent to
+.Qq Fl o Cm cachefile=none,altroot= Ns Pa root
+.It Fl m Ar mountpoint
 Sets the mount point for the root dataset. The default mount point is
-"/\fIpool\fR" or "\fBaltroot\fR/\fIpool\fR" if \fBaltroot\fR is specified. The
-mount point must be an absolute path, "\fBlegacy\fR", or "\fBnone\fR". For more
-information on dataset mount points, see \fBzfs\fR(8).
-.RE
-
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzpool destroy\fR [\fB-f\fR] \fIpool\fR\fR
-.ad
-.sp .6
-.RS 4n
+.Qq Pa /pool
+or
+.Qq Cm altroot Ns Pa /pool
+if
+.Sy altroot
+is specified. The mount point must be an absolute path, 
+.Qq Cm legacy ,
+or
+.Qq Cm none .
+For more information on dataset mount points, see
+.Xr zfs 8 .
+.El
+.It Xo
+.Nm
+.Cm destroy
+.Op Fl f
+.Ar pool
+.Xc
+.Pp
 Destroys the given pool, freeing up any devices for other use. This command
 tries to unmount any active datasets before destroying the pool.
-.sp
-.ne 2
-.na
-\fB\fB-f\fR\fR
-.ad
-.RS 6n
+.Bl -tag -width indent
+.It Fl f
 Forces any active datasets contained within the pool to be unmounted.
-.RE
-
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzpool detach\fR \fIpool\fR \fIdevice\fR\fR
-.ad
-.sp .6
-.RS 4n
-Detaches \fIdevice\fR from a mirror. The operation is refused if there are no
-other valid replicas of the data.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzpool export\fR [\fB-f\fR] \fIpool\fR ...\fR
-.ad
-.sp .6
-.RS 4n
+.El
+.It Xo
+.Nm
+.Cm detach
+.Ar pool device
+.Xc
+.Pp
+Detaches
+.Ar device
+from a mirror. The operation is refused if there are no other valid replicas
+of the data.
+.It Xo
+.Nm
+.Cm export
+.Op Fl f
+.Ar pool ...
+.Xc
+.Pp
 Exports the given pools from the system. All devices are marked as exported,
 but are still considered in use by other subsystems. The devices can be moved
 between systems (even those of different endianness) and imported as long as a
 sufficient number of devices are present.
-.sp
+.Pp
 Before exporting the pool, all datasets within the pool are unmounted. A pool
 can not be exported if it has a shared spare that is currently being used.
-.sp
-For pools to be portable, you must give the \fBzpool\fR command whole disks,
-not just slices, so that \fBZFS\fR can label the disks with portable \fBEFI\fR
+.Pp
+For pools to be portable, you must give the
+.Nm
+command whole disks, not just slices, so that
+.Tn ZFS
+can label the disks with portable
+.Sy EFI
 labels. Otherwise, disk drivers on platforms of different endianness will not
 recognize the disks.
-.sp
-.ne 2
-.na
-\fB\fB-f\fR\fR
-.ad
-.RS 6n
-Forcefully unmount all datasets, using the "\fBunmount -f\fR" command.
-.sp
+.Bl -tag -width indent
+.It Fl f
+Forcefully unmount all datasets, using the
+.Qq Nm unmount Fl f
+command.
+.Pp
 This command will forcefully export the pool even if it has a shared spare that
 is currently being used. This may lead to potential data corruption.
-.RE
-
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzpool get\fR "\fIall\fR" | \fIproperty\fR[,...] \fIpool\fR ...\fR
-.ad
-.sp .6
-.RS 4n
-Retrieves the given list of properties (or all properties if "\fBall\fR" is
-used) for the specified storage pool(s). These properties are displayed with
+.El
+.It Xo
+.Nm
+.Cm get
+.Ar all | property Ns Op , Ns Ar ...
+.Ar pool ...
+.Xc
+.Pp
+Retrieves the given list of properties (or all properties if
+.Qq Cm all
+is used) for the specified storage pool(s). These properties are displayed with
 the following fields:
-.sp
-.in +2
-.nf
-       name          Name of storage pool
-        property      Property name
-        value         Property value
-        source        Property source, either 'default' or 'local'.
-.fi
-.in -2
-.sp
-
-See the "Properties" section for more information on the available pool
-properties.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzpool history\fR [\fB-il\fR] [\fIpool\fR] ...\fR
-.ad
-.sp .6
-.RS 4n
+.Bl -column -offset indent "property"
+.It name Ta Name of storage pool
+.It property Ta Property name
+.It value Ta Property value
+.It source Ta Property source, either 'default' or 'local'.
+.El
+.Pp
+See the
+.Qq Sx Properties
+section for more information on the available pool properties.
+.It Xo
+.Nm
+.Cm history
+.Op Fl il
+.Op Ar pool
+.Ar ...
+.Xc
+.Pp
 Displays the command history of the specified pools or all pools if no pool is
 specified.
-.sp
-.ne 2
-.na
-\fB\fB-i\fR\fR
-.ad
-.RS 6n
-Displays internally logged \fBZFS\fR events in addition to user initiated
-events.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-l\fR\fR
-.ad
-.RS 6n
+.Bl -tag -width indent
+.It Fl i
+Displays internally logged
+.Tn ZFS
+events in addition to user initiated events.
+.It Fl l
 Displays log records in long format, which in addition to standard format
-includes, the user name, the hostname, and the jail in which the operation was
+includes, the user name, the hostname, and the zone in which the operation was
 performed.
-.RE
-
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzpool import\fR [\fB-d\fR \fIdir\fR | \fB-c\fR \fIcachefile\fR]
-[\fB-D\fR]\fR
-.ad
-.sp .6
-.RS 4n
-Lists pools available to import. If the \fB-d\fR option is not specified, this
-command searches for devices in "/dev/dsk". The \fB-d\fR option can be
-specified multiple times, and all directories are searched. If the device
-appears to be part of an exported pool, this command displays a summary of the
-pool with the name of the pool, a numeric identifier, as well as the \fIvdev\fR
-layout and current health of the device for each device or file. Destroyed
-pools, pools that were previously destroyed with the "\fBzpool destroy\fR"
-command, are not listed unless the \fB-D\fR option is specified.
-.sp
+.El
+.It Xo
+.Nm
+.Cm import
+.Op Fl d Ar dir | Fl c Ar cachefile
+.Op Fl D
+.Xc
+.Pp
+Lists pools available to import. If the
+.Fl d
+option is not specified, this command searches for devices in
+.Qq Pa /dev .
+The
+.Fl d
+option can be specified multiple times, and all directories are searched. If
+the device appears to be part of an exported pool, this command displays a
+summary of the pool with the name of the pool, a numeric identifier, as well as
+the
+.No vdev
+layout and current health of the device for each device or file.
+Destroyed pools, pools that were previously destroyed with the
+.Qq Nm Cm destroy
+command, are not listed unless the
+.Fl D
+option is specified.
+.Pp
 The numeric identifier is unique, and can be used instead of the pool name when
 multiple exported pools of the same name are available.
-.sp
-.ne 2
-.na
-\fB\fB-c\fR \fIcachefile\fR\fR
-.ad
-.RS 16n
-Reads configuration from the given \fBcachefile\fR that was created with the
-"\fBcachefile\fR" pool property. This \fBcachefile\fR is used instead of
-searching for devices.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-d\fR \fIdir\fR\fR
-.ad
-.RS 16n
-Searches for devices or files in \fIdir\fR. The \fB-d\fR option can be
-specified multiple times.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-D\fR\fR
-.ad
-.RS 16n
+.Bl -tag -width indent
+.It Fl c Ar cachefile
+Reads configuration from the given
+.Ar cachefile
+that was created with the
+.Qq Sy cachefile
+pool property. This
+.Ar cachefile
+is used instead of searching for devices.
+.It Fl d Ar dir
+Searches for devices or files in
+.Ar dir .
+The
+.Fl d
+option can be specified multiple times.
+.It Fl D
 Lists destroyed pools only.
-.RE
-
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzpool import\fR [\fB-o\fR \fImntopts\fR] [ \fB-o\fR
-\fIproperty\fR=\fIvalue\fR] ... [\fB-d\fR \fIdir\fR | \fB-c\fR \fIcachefile\fR]
-[\fB-D\fR] [\fB-f\fR] [\fB-R\fR \fIroot\fR] \fB-a\fR\fR
-.ad
-.sp .6
-.RS 4n
+.El
+.It Xo
+.Nm
+.Cm import
+.Op Fl o Ar mntopts
+.Op Fl o Ar property Ns = Ns Ar value
+.Ar ...
+.Op Fl d Ar dir | Fl c Ar cachefile
+.Op Fl D
+.Op Fl f
+.Op Fl m
+.Op Fl N
+.Op Fl R Ar root
+.Op Fl F Op Fl n
+.Fl a
+.Xc
+.Pp
 Imports all pools found in the search directories. Identical to the previous
 command, except that all pools with a sufficient number of devices available
 are imported. Destroyed pools, pools that were previously destroyed with the
-"\fBzpool destroy\fR" command, will not be imported unless the \fB-D\fR option
-is specified.
-.sp
-.ne 2
-.na
-\fB\fB-o\fR \fImntopts\fR\fR
-.ad
-.RS 21n
+.Qq Nm Cm destroy
+command, will not be imported unless the
+.Fl D
+option is specified.
+.Bl -tag -width indent
+.It Fl o Ar mntopts
 Comma-separated list of mount options to use when mounting datasets within the
-pool. See \fBzfs\fR(8) for a description of dataset properties and mount
-options.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-o\fR \fIproperty=value\fR\fR
-.ad
-.RS 21n
-Sets the specified property on the imported pool. See the "Properties" section
-for more information on the available pool properties.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-c\fR \fIcachefile\fR\fR
-.ad
-.RS 21n
-Reads configuration from the given \fBcachefile\fR that was created with the
-"\fBcachefile\fR" pool property. This \fBcachefile\fR is used instead of
-searching for devices.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-d\fR \fIdir\fR\fR
-.ad
-.RS 21n
-Searches for devices or files in \fIdir\fR. The \fB-d\fR option can be
-specified multiple times. This option is incompatible with the \fB-c\fR option.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-D\fR\fR
-.ad
-.RS 21n
-Imports destroyed pools only. The \fB-f\fR option is also required.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-f\fR\fR
-.ad
-.RS 21n
+pool. See
+.Xr zfs 8
+for a description of dataset properties and mount options.
+.It Fl o Ar property Ns = Ns Ar value
+Sets the specified property on the imported pool. See the
+.Qq Sx Properties
+section for more information on the available pool properties.
+.It Fl c Ar cachefile
+Reads configuration from the given
+.Ar cachefile
+that was created with the
+.Qq Sy cachefile
+pool property. This
+.Ar cachefile
+is used instead of searching for devices.
+.It Fl d Ar dir
+Searches for devices or files in
+.Ar dir .
+The
+.Fl d
+option can be specified multiple times. This option is incompatible with the
+.Fl c
+option.
+.It Fl D
+Imports destroyed pools only. The
+.Fl f
+option is also required.
+.It Fl f
 Forces import, even if the pool appears to be potentially active.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-a\fR\fR
-.ad
-.RS 21n
+.It Fl m
+Enables import with missing log devices.
+.It Fl N
+Do not mount any filesystems from the imported pool.
+.It Fl R Ar root
+Sets the
+.Qq Sy cachefile
+property to
+.Qq Cm none
+and the
+.Qq Sy altroot
+property to
+.Qq Ar root
+.It Fl F
+Recovery mode for a non-importable pool. Attempt to return the pool to an
+importable state by discarding the last few transactions. Not all damaged pools
+can be recovered by using this option. If successful, the data from the
+discarded transactions is irretrievably lost. This option is ignored if the
+pool is importable or already imported.
+.It Fl n
+Used with the
+.Fl F
+recovery option. Determines whether a non-importable pool can be made
+importable again, but does not actually perform the pool recovery. For more
+details about pool recovery mode, see the
+.Fl F
+option, above.
+.It Fl a
 Searches for and imports all pools found.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-R\fR \fIroot\fR\fR
-.ad
-.RS 21n
-Sets the "\fBcachefile\fR" property to "\fBnone\fR" and the "\fIaltroot\fR"
-property to "\fIroot\fR".
-.RE
-
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzpool import\fR [\fB-o\fR \fImntopts\fR] [ \fB-o\fR
-\fIproperty\fR=\fIvalue\fR] ... [\fB-d\fR \fIdir\fR | \fB-c\fR \fIcachefile\fR]
-[\fB-D\fR] [\fB-f\fR] [\fB-R\fR \fIroot\fR] \fIpool\fR | \fIid\fR
-[\fInewpool\fR]\fR
-.ad
-.sp .6
-.RS 4n
+.El
+.It Xo
+.Nm
+.Cm import
+.Op Fl o Ar mntopts
+.Op Fl o Ar property Ns = Ns Ar value
+.Ar ...
+.Op Fl d Ar dir | Fl c Ar cachefile
+.Op Fl D
+.Op Fl f
+.Op Fl m
+.Op Fl N
+.Op Fl R Ar root
+.Op Fl F Op Fl n
+.Ar pool | id
+.Op Ar newpool
+.Xc
+.Pp
 Imports a specific pool. A pool can be identified by its name or the numeric
-identifier. If \fInewpool\fR is specified, the pool is imported using the name
-\fInewpool\fR. Otherwise, it is imported with the same name as its exported
-name.
-.sp
-If a device is removed from a system without running "\fBzpool export\fR"
+identifier. If
+.Ar newpool
+is specified, the pool is imported using the name
+.Ar newpool .
+Otherwise, it is imported with the same name as its exported name.
+.Pp
+If a device is removed from a system without running
+.Qq Nm Cm export
 first, the device appears as potentially active. It cannot be determined if
 this was a failed export, or whether the device is really in use from another
-host. To import a pool in this state, the \fB-f\fR option is required.
-.sp
-.ne 2
-.na
-\fB\fB-o\fR \fImntopts\fR\fR
-.ad
-.sp .6
-.RS 4n
+host. To import a pool in this state, the
+.Fl f
+option is required.
+.Bl -tag -width indent
+.It Fl o Ar mntopts
 Comma-separated list of mount options to use when mounting datasets within the
-pool. See \fBzfs\fR(8) for a description of dataset properties and mount
-options.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-o\fR \fIproperty=value\fR\fR
-.ad
-.sp .6
-.RS 4n
-Sets the specified property on the imported pool. See the "Properties" section
-for more information on the available pool properties.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-c\fR \fIcachefile\fR\fR
-.ad
-.sp .6
-.RS 4n
-Reads configuration from the given \fBcachefile\fR that was created with the
-"\fBcachefile\fR" pool property. This \fBcachefile\fR is used instead of
-searching for devices.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-d\fR \fIdir\fR\fR
-.ad
-.sp .6
-.RS 4n
-Searches for devices or files in \fIdir\fR. The \fB-d\fR option can be
-specified multiple times. This option is incompatible with the \fB-c\fR option.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-D\fR\fR
-.ad
-.sp .6
-.RS 4n
-Imports destroyed pool. The \fB-f\fR option is also required.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-f\fR\fR
-.ad
-.sp .6
-.RS 4n
+pool. See
+.Xr zfs 8
+for a description of dataset properties and mount options.
+.It Fl o Ar property Ns = Ns Ar value
+Sets the specified property on the imported pool. See the
+.Qq Sx Properties
+section for more information on the available pool properties.
+.It Fl c Ar cachefile
+Reads configuration from the given
+.Ar cachefile
+that was created with the
+.Qq Sy cachefile
+pool property. This
+.Ar cachefile
+is used instead of searching for devices.
+.It Fl d Ar dir
+Searches for devices or files in
+.Ar dir .
+The
+.Fl d
+option can be specified multiple times. This option is incompatible with the
+.Fl c
+option.
+.It Fl D
+Imports destroyed pools only. The
+.Fl f
+option is also required.
+.It Fl f
 Forces import, even if the pool appears to be potentially active.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-R\fR \fIroot\fR\fR
-.ad
-.sp .6
-.RS 4n
-Sets the "\fBcachefile\fR" property to "\fBnone\fR" and the "\fIaltroot\fR"
-property to "\fIroot\fR".
-.RE
-
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzpool iostat\fR [\fB-T\fR \fBu\fR | \fBd\fR] [\fB-v\fR] [\fIpool\fR] ...
-[\fIinterval\fR[\fIcount\fR]]\fR
-.ad
-.sp .6
-.RS 4n
-Displays \fBI/O\fR statistics for the given pools. When given an interval, the
-statistics are printed every \fIinterval\fR seconds until \fBCtrl-C\fR is
-pressed. If no \fIpools\fR are specified, statistics for every pool in the
-system is shown. If \fIcount\fR is specified, the command exits after
-\fIcount\fR reports are printed.
-.sp
-.ne 2
-.na
-\fB\fB-T\fR \fBu\fR | \fBd\fR\fR
-.ad
-.RS 12n
-Display a time stamp.
-.sp
-Specify \fBu\fR for a printed representation of the internal representation of
-time. See \fBtime\fR(2). Specify \fBd\fR for standard date format. See
-\fBdate\fR(1).
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-v\fR\fR
-.ad
-.RS 12n
-Verbose statistics. Reports usage statistics for individual \fIvdevs\fR within
-the pool, in addition to the pool-wide statistics.
-.RE
-
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzpool labelclear\fR [\fB-f\fR] \fIdevice\fR
-.ad
-.sp .6
-.RS 4n
-Removes ZFS label information from the specified device. The device must not
-be part of an active pool configuration.
-.sp
-.ne 2
-.mk
-.na
-\fB\fB-f\fR\fR
-.ad
-.RS 12n
-.rt  
+.It Fl m
+Enables import with missing log devices.
+.It Fl N
+Do not mount any filesystems from the imported pool.
+.It Fl R Ar root
+Equivalent to
+.Qq Fl o Cm cachefile=none,altroot= Ns Pa root
+.It Fl F
+Recovery mode for a non-importable pool. Attempt to return the pool to an
+importable state by discarding the last few transactions. Not all damaged pools
+can be recovered by using this option. If successful, the data from the
+discarded transactions is irretrievably lost. This option is ignored if the
+pool is importable or already imported.
+.It Fl n
+Used with the
+.Fl F
+recovery option. Determines whether a non-importable pool can be made
+importable again, but does not actually perform the pool recovery. For more
+details about pool recovery mode, see the
+.Fl F
+option, above.
+.El
+.It Xo
+.Nm
+.Cm iostat
+.Op Fl T Cm d Ns | Ns Cm u
+.Op Fl v
+.Op Ar pool
+.Ar ...
+.Op Ar interval Op Ar count
+.Xc
+.Pp
+Displays
+.Tn I/O
+statistics for the given pools. When given an interval, the statistics are
+printed every
+.Ar interval
+seconds until
+.Sy Ctrl-C
+is pressed. If no
+.Ar pools
+are specified, statistics for every pool in the system is shown. If 
+.Ar count
+is specified, the command exits after
+.Ar count
+reports are printed.
+.Bl -tag -width indent
+.It Fl T Cm d Ns | Ns Cm u
+Print a timestamp.
+.Pp
+Use modifier
+.Cm d
+for standard date format. See
+.Xr date 1 .
+Use modifier
+.Cm u
+for unixtime
+.Pq equals Qq Ic date +%s .
+.It Fl v
+Verbose statistics. Reports usage statistics for individual
+.No vdev Ns s
+within the pool, in addition to the pool-wide statistics.
+.El
+.It Xo
+.Nm
+.Cm labelclear
+.Op Fl f
+.Ar device
+.Xc
+.Pp
+Removes
+.Tn ZFS
+label information from the specified
+.Ar device .
+The
+.Ar device
+must not be part of an active pool configuration.
+.Bl -tag -width indent
+.It Fl v
 Treat exported or foreign devices as inactive.
-.RE
-
-.RE
-
-.sp
-.ne 2
-.mk
-.na
-\fB\fBzpool list\fR [\fB-H\fR] [\fB-o\fR \fIprops\fR[,...]] [\fIpool\fR] ...\fR
-.ad
-.sp .6
-.RS 4n
+.El
+.It Xo
+.Nm
+.Cm list
+.Op Fl H
+.Op Fl o Ar property Ns Op , Ns Ar ...
+.Op Fl T Cm d Ns | Ns Cm u
+.Op Ar pool
+.Ar ...
+.Op Ar inverval Op Ar count
+.Xc
+.Pp
 Lists the given pools along with a health status and space usage. When given no
 arguments, all pools in the system are listed.
-.sp
-.ne 2
-.na
-\fB\fB-H\fR\fR
-.ad
-.RS 12n
+.Pp
+When given an interval, the output is printed every
+.Ar interval
+seconds until
+.Sy Ctrl-C
+is pressed. If 
+.Ar count
+is specified, the command exits after
+.Ar count
+reports are printed.
+.Bl -tag -width indent
+.It Fl H
 Scripted mode. Do not display headers, and separate fields by a single tab
 instead of arbitrary space.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-o\fR \fIprops\fR\fR
-.ad
-.RS 12n
-Comma-separated list of properties to display. See the "Properties" section for
-a list of valid properties. The default list is "name, size, used, available,
-capacity, health, altroot"
-.RE
-
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzpool offline\fR [\fB-t\fR] \fIpool\fR \fIdevice\fR ...\fR
-.ad
-.sp .6
-.RS 4n
-Takes the specified physical device offline. While the \fIdevice\fR is offline,
-no attempt is made to read or write to the device.
-.sp
-This command is not applicable to spares or cache devices.
-.sp
-.ne 2
-.na
-\fB\fB-t\fR\fR
-.ad
-.RS 6n
+.It Fl o Ar property Ns Op , Ns Ar ...
+Comma-separated list of properties to display. See the
+.Qq Sx Properties
+section for a list of valid properties. The default list is
+.Sy name ,
+.Sy size ,
+.Sy used ,
+.Sy available ,
+.Sy capacity  ,
+.Sy health ,
+.Sy altroot .
+.It Fl T Cm d Ns | Ns Cm u
+Print a timestamp.
+.Pp
+Use modifier
+.Cm d
+for standard date format. See
+.Xr date 1 .
+Use modifier
+.Cm u
+for unixtime
+.Pq equals Qq Ic date +%s .
+.El
+.It Xo
+.Nm
+.Cm offline
+.Op Fl t
+.Ar pool device ...
+.Xc
+.Pp
+Takes the specified physical device offline. While the
+.Ar device
+is offline, no attempt is made to read or write to the device.
+.Bl -tag -width indent
+.It Fl t
 Temporary. Upon reboot, the specified physical device reverts to its previous
 state.
-.RE
-
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzpool online\fR [\fB-e\fR] \fIpool\fR \fIdevice\fR...\fR
-.ad
-.sp .6
-.RS 4n
+.El
+.It Xo
+.Nm
+.Cm online
+.Op Fl e
+.Ar pool device ...
+.Xc
+.Pp
 Brings the specified physical device online.
-.sp
+.Pp
 This command is not applicable to spares or cache devices.
-.sp
-.ne 2
-.na
-\fB\fB-e\fR\fR
-.ad
-.RS 6n
+.Bl -tag -width indent
+.It Fl e
 Expand the device to use all available space. If the device is part of a mirror
-or \fBraidz\fR then all devices must be expanded before the new space will
-become available to the pool.
-.RE
-
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzpool remove\fR \fIpool\fR \fIdevice\fR ...\fR
-.ad
-.sp .6
-.RS 4n
+or
+.No raidz
+then all devices must be expanded before the new space will become
+available to the pool.
+.El
+.It Xo
+.Nm
+.Cm reguid
+.Ar pool
+.Xc
+.Pp
+Generates a new unique identifier for the pool.  You must ensure that all
+devices in this pool are online and healthy before performing this action.
+.It Xo
+.Nm
+.Cm remove
+.Ar pool device ...
+.Xc
+.Pp
 Removes the specified device from the pool. This command currently only
 supports removing hot spares, cache, and log devices. A mirrored log device can
 be removed by specifying the top-level mirror for the log. Non-log devices that
-are part of a mirrored configuration can be removed using the \fBzpool
-detach\fR command. Non-redundant and \fBraidz\fR devices cannot be removed from
-a pool.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzpool replace\fR [\fB-f\fR] \fIpool\fR \fIold_device\fR
-[\fInew_device\fR]\fR
-.ad
-.sp .6
-.RS 4n
-Replaces \fIold_device\fR with \fInew_device\fR. This is equivalent to
-attaching \fInew_device\fR, waiting for it to resilver, and then detaching
-\fIold_device\fR.
-.sp
-The size of \fInew_device\fR must be greater than or equal to the minimum size
-of all the devices in a mirror or \fBraidz\fR configuration.
-.sp
-\fInew_device\fR is required if the pool is not redundant. If \fInew_device\fR
-is not specified, it defaults to \fIold_device\fR. This form of replacement is
-useful after an existing disk has failed and has been physically replaced. In
-this case, the new disk may have the same \fB/dev/dsk\fR path as the old
-device, even though it is actually a different disk. \fBZFS\fR recognizes this.
-.sp
-.ne 2
-.na
-\fB\fB-f\fR\fR
-.ad
-.RS 6n
-Forces use of \fInew_device\fR, even if its appears to be in use. Not all
-devices can be overridden in this manner.
-.RE
-
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzpool scrub\fR [\fB-s\fR] \fIpool\fR ...\fR
-.ad
-.sp .6
-.RS 4n
+are part of a mirrored configuration can be removed using the
+.Qq Nm Cm detach
+command. Non-redundant and
+.No raidz
+devices cannot be removed from a pool.
+.It Xo
+.Nm
+.Cm replace
+.Op Fl f
+.Ar pool device
+.Op Ar new_device
+.Xc
+.Pp
+Replaces
+.Ar old_device
+with
+.Ar new_device .
+This is equivalent to attaching
+.Ar new_device ,
+waiting for it to resilver, and then detaching
+.Ar old_device .
+.Pp
+The size of 
+.Ar new_device
+must be greater than or equal to the minimum size
+of all the devices in a mirror or
+.No raidz
+configuration.
+.Pp
+.Ar new_device
+is required if the pool is not redundant. If
+.Ar new_device
+is not specified, it defaults to
+.Ar old_device . 
+This form of replacement is useful after an existing disk has failed and has
+been physically replaced. In this case, the new disk may have the same
+.Pa /dev
+path as the old device, even though it is actually a different disk.
+.Tn ZFS
+recognizes this.
+.Bl -tag -width indent
+.It Fl f
+Forces use of
+.Ar new_device ,
+even if its appears to be in use. Not all devices can be overridden in this
+manner.
+.El
+.It Xo
+.Nm
+.Cm scrub
+.Op Fl s
+.Ar pool ...
+.Xc
+.Pp
 Begins a scrub. The scrub examines all data in the specified pools to verify
-that it checksums correctly. For replicated (mirror or \fBraidz\fR) devices,
-\fBZFS\fR automatically repairs any damage discovered during the scrub. The
-"\fBzpool status\fR" command reports the progress of the scrub and summarizes
-the results of the scrub upon completion.
-.sp
+that it checksums correctly. For replicated (mirror or
+.No raidz )
+devices,
+.Tn ZFS
+automatically repairs any damage discovered during the scrub. The
+.Qq Nm Cm status
+command reports the progress of the scrub and summarizes the results of the
+scrub upon completion.
+.Pp
 Scrubbing and resilvering are very similar operations. The difference is that
-resilvering only examines data that \fBZFS\fR knows to be out of date (for
-example, when attaching a new device to a mirror or replacing an existing
-device), whereas scrubbing examines all data to discover silent errors due to
-hardware faults or disk failure.
-.sp
-Because scrubbing and resilvering are \fBI/O\fR-intensive operations, \fBZFS\fR
-only allows one at a time. If a scrub is already in progress, the "\fBzpool
-scrub\fR" command terminates it and starts a new scrub. If a resilver is in
-progress, \fBZFS\fR does not allow a scrub to be started until the resilver
-completes.
-.sp
-.ne 2
-.na
-\fB\fB-s\fR\fR
-.ad
-.RS 6n
+resilvering only examines data that
+.Tn ZFS
+knows to be out of date (for example, when attaching a new device to a mirror
+or replacing an existing device), whereas scrubbing examines all data to
+discover silent errors due to hardware faults or disk failure.
+.Pp
+Because scrubbing and resilvering are
+.Tn I/O Ns -intensive
+operations,
+.Tn ZFS
+only allows one at a time. If a scrub is already in progress, the
+.Qq Nm Cm scrub
+command returns an error. To start a new scrub, you have to stop the old scrub
+with the
+.Qq Nm Cm scrub Fl s
+command first. If a resilver is in progress,
+.Tn ZFS
+does not allow a scrub to be started until the resilver completes.
+.Bl -tag -width indent
+.It Fl s
 Stop scrubbing.
-.RE
-
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzpool set\fR \fIproperty\fR=\fIvalue\fR \fIpool\fR\fR
-.ad
-.sp .6
-.RS 4n
-Sets the given property on the specified pool. See the "Properties" section for
-more information on what properties can be set and acceptable values.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzpool status\fR [\fB-xv\fR] [\fIpool\fR] ...\fR
-.ad
-.sp .6
-.RS 4n
-Displays the detailed health status for the given pools. If no \fIpool\fR is
-specified, then the status of each pool in the system is displayed. For more
-information on pool and device health, see the "Device Failure and Recovery"
+.El
+.It Xo
+.Nm
+.Cm set
+.Ar property Ns = Ns Ar value pool
+.Xc
+.Pp
+Sets the given property on the specified pool. See the
+.Qq Sx Properties
+section for more information on what properties can be set and acceptable
+values.
+.It Xo
+.Nm
+.Cm split
+.Op Fl n
+.Op Fl R Ar altroot
+.Op Fl o Ar mntopts
+.Op Fl o Ar property Ns = Ns Ar value
+.Ar pool newpool
+.Op Ar device ...
+.Xc
+.Pp
+Splits off one disk from each mirrored top-level
+.No vdev
+in a pool and creates a new pool from the split-off disks. The original pool
+must be made up of one or more mirrors and must not be in the process of
+resilvering. The
+.Cm split
+subcommand chooses the last device in each mirror
+.No vdev
+unless overridden by a device specification on the command line.
+.Pp
+When using a
+.Ar device
+argument, 
+.Cm split
+includes the specified device(s) in a new pool and, should any devices remain 
+unspecified, assigns the last device in each mirror
+.No vdev
+to that pool, as it does normally. If you are uncertain about the outcome of a 
+.Cm split
+command, use the
+.Fl n
+("dry-run") option to ensure your command will have the effect you intend.
+.Bl -tag -width indent
+.It Fl R Ar altroot
+Automatically import the newly created pool after splitting, using the
+specified
+.Ar altroot
+parameter for the new pool's alternate root. See the
+.Sy altroot
+description in the
+.Qq Sx Properties
+section, above.
+.It Fl n
+Displays the configuration that would be created without actually splitting the
+pool. The actual pool split could still fail due to insufficient privileges or
+device status.
+.It Fl o Ar mntopts
+Comma-separated list of mount options to use when mounting datasets within the
+pool. See
+.Xr zfs 8
+for a description of dataset properties and mount options. Valid only in
+conjunction with the
+.Fl R
+option.
+.It Fl o Ar property Ns = Ns Ar value
+Sets the specified property on the new pool. See the
+.Qq Sx Properties
+section, above, for more information on the available pool properties.
+.El
+.It Xo
+.Nm
+.Cm status
+.Op Fl vx
+.Op Fl T Cm d Ns | Ns Cm u
+.Op Ar pool
+.Ar ...
+.Op Ar interval Op Ar count
+.Xc
+.Pp
+Displays the detailed health status for the given pools. If no
+.Ar pool
+is specified, then the status of each pool in the system is displayed. For more
+information on pool and device health, see the
+.Qq Sx Device Failure and Recovery
 section.
-.sp
+.Pp
+When given an interval, the output is printed every
+.Ar interval
+seconds until
+.Sy Ctrl-C
+is pressed. If 
+.Ar count
+is specified, the command exits after
+.Ar count
+reports are printed.
+.Pp
 If a scrub or resilver is in progress, this command reports the percentage done
 and the estimated time to completion. Both of these are only approximate,
 because the amount of data in the pool and the other workloads on the system
 can change.
-.sp
-.ne 2
-.na
-\fB\fB-x\fR\fR
-.ad
-.RS 6n
+.Bl -tag -width indent
+.It Fl x
 Only display status for pools that are exhibiting errors or are otherwise
 unavailable.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-v\fR\fR
-.ad
-.RS 6n
+.It Fl v
 Displays verbose data error information, printing out a complete list of all
 data errors since the last complete pool scrub.
-.RE
-
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzpool upgrade\fR\fR
-.ad
-.sp .6
-.RS 4n
-Displays all pools formatted using a different \fBZFS\fR on-disk version. Older
-versions can continue to be used, but some features may not be available. These
-pools can be upgraded using "\fBzpool upgrade -a\fR". Pools that are formatted
-with a more recent version are also displayed, although these pools will be
-inaccessible on the system.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzpool upgrade\fR \fB-v\fR\fR
-.ad
-.sp .6
-.RS 4n
-Displays \fBZFS\fR versions supported by the current software. The current
-\fBZFS\fR versions and all previous supported versions are displayed, along
+.It Fl T Cm d Ns | Ns Cm u
+Print a timestamp.
+.Pp
+Use modifier
+.Cm d
+for standard date format. See
+.Xr date 1 .
+Use modifier
+.Cm u
+for unixtime
+.Pq equals Qq Ic date +%s .
+.El
+.It Xo
+.Nm
+.Cm upgrade
+.Op Fl v
+.Xc
+.Pp
+Displays all pools formatted using a different
+.Tn ZFS
+pool on-disk version. Older versions can continue to be used, but some
+features may not be available. These pools can be upgraded using
+.Qq Nm Cm upgrade Fl a .
+Pools that are formatted with a more recent version are also displayed,
+although these pools will be inaccessible on the system.
+.Bl -tag -width indent
+.It Fl v
+Displays
+.Tn ZFS
+pool versions supported by the current software. The current
+.Tn ZFS
+pool version and all previous supported versions are displayed, along
 with an explanation of the features provided with each version.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fBzpool upgrade\fR [\fB-V\fR \fIversion\fR] \fB-a\fR | \fIpool\fR ...\fR
-.ad
-.sp .6
-.RS 4n
-Upgrades the given pool to the latest on-disk version. Once this is done, the
-pool will no longer be accessible on systems running older versions of the
+.El
+.It Xo
+.Nm
+.Cm upgrade
+.Op Fl V Ar version
+.Fl a | Ar pool ...
+.Xc
+.Pp
+Upgrades the given pool to the latest on-disk pool version. Once this is done,
+the pool will no longer be accessible on systems running older versions of the
 software.
-.sp
-.ne 2
-.na
-\fB\fB-a\fR\fR
-.ad
-.RS 14n
+.Bl -tag -width indent
+.It Fl a
 Upgrades all pools.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-V\fR \fIversion\fR\fR
-.ad
-.RS 14n
-Upgrade to the specified version. If the \fB-V\fR flag is not specified, the
-pool is upgraded to the most recent version. This option can only be used to
-increase the version number, and only up to the most recent version supported
-by this software.
-.RE
-
-.RE
-
-.SH EXAMPLES
-.LP
-\fBExample 1 \fRCreating a RAID-Z Storage Pool
-.sp
-.LP
-The following command creates a pool with a single \fBraidz\fR root \fIvdev\fR
+.It Fl V Ar version
+Upgrade to the specified version. If the
+.Fl V
+flag is not specified, the pool is upgraded to the most recent version. This
+option can only be used to increase the version number, and only up to the most
+recent version supported by this software.
+.El
+.El
+.Sh EXAMPLES
+.Bl -tag -width 0n
+.It Sy Example 1 No Creating a RAID-Z Storage Pool
+.Pp
+The following command creates a pool with a single
+.No raidz
+root
+.No vdev
 that consists of six disks.
-
-.sp
-.in +2
-.nf
-# \fBzpool create tank raidz da0 da1 da2 da3 da4 da5\fR
-.fi
-.in -2
-.sp
-
-.LP
-\fBExample 2 \fRCreating a Mirrored Storage Pool
-.sp
-.LP
+.Bd -literal -offset 2n
+.Li # Ic zpool create tank raidz da0 da1 da2 da3 da4 da5
+.Ed
+.It Sy Example 2 No Creating a Mirrored Storage Pool
+.Pp
 The following command creates a pool with two mirrors, where each mirror
 contains two disks.
-
-.sp
-.in +2
-.nf
-# \fBzpool create tank mirror da0 da1 mirror da2 da3\fR
-.fi
-.in -2
-.sp
-
-.LP
-\fBExample 3 \fRCreating a ZFS Storage Pool by Using Slices
-.sp
-.LP
-The following command creates an unmirrored pool using two disk slices.
-
-.sp
-.in +2
-.nf
-# \fBzpool create tank /dev/da0s1 da1s4\fR
-.fi
-.in -2
-.sp
-
-.LP
-\fBExample 4 \fRCreating a ZFS Storage Pool by Using Files
-.sp
-.LP
+.Bd -literal -offset 2n
+.Li # Ic zpool create tank mirror da0 da1 mirror da2 da3
+.Ed
+.It Sy Example 3 No Creating a Tn ZFS No Storage Pool by Using Partitions
+.Pp
+The following command creates an unmirrored pool using two GPT partitions.
+.Bd -literal -offset 2n
+.Li # Ic zpool create tank da0p3 da1p3
+.Ed
+.It Sy Example 4 No Creating a Tn ZFS No Storage Pool by Using Files
+.Pp
 The following command creates an unmirrored pool using files. While not
 recommended, a pool based on files can be useful for experimental purposes.
-
-.sp
-.in +2
-.nf
-# \fBzpool create tank /path/to/file/a /path/to/file/b\fR
-.fi
-.in -2
-.sp
-
-.LP
-\fBExample 5 \fRAdding a Mirror to a ZFS Storage Pool
-.sp
-.LP
-The following command adds two mirrored disks to the pool "\fItank\fR",
+.Bd -literal -offset 2n
+.Li # Ic zpool create tank /path/to/file/a /path/to/file/b
+.Ed
+.It Sy Example 5 No Adding a Mirror to a Tn ZFS No Storage Pool
+.Pp
+The following command adds two mirrored disks to the pool
+.Em tank ,
 assuming the pool is already made up of two-way mirrors. The additional space
 is immediately available to any datasets within the pool.
+.Bd -literal -offset 2n
+.Li # Ic zpool add tank mirror da2 da3
+.Ed
+.It Sy Example 6 No Listing Available Tn ZFS No Storage Pools
+.Pp
+The following command lists all available pools on the system.
+.Bd -literal -offset 2n
+.Li # Ic zpool list
+NAME   SIZE  ALLOC   FREE    CAP  DEDUP  HEALTH  ALTROOT
+pool  2.70T   473G  2.24T    17%  1.00x  ONLINE  -
+test  1.98G  89.5K  1.98G     0%  1.00x  ONLINE  -
+.Ed
+.It Sy Example 7 No Listing All Properties for a Pool
+.Pp
+The following command lists all the properties for a pool.
+.Bd -literal -offset 2n
+.Li # Ic zpool get all pool
+pool  size           2.70T       -
+pool  capacity       17%         -
+pool  altroot        -           default
+pool  health         ONLINE      -
+pool  guid           2501120270416322443  default
+pool  version        28          default
+pool  bootfs         pool/root   local
+pool  delegation     on          default
+pool  autoreplace    off         default
+pool  cachefile      -           default
+pool  failmode       wait        default
+pool  listsnapshots  off         default
+pool  autoexpand     off         default
+pool  dedupditto     0           default
+pool  dedupratio     1.00x       -
+pool  free           2.24T       -
+pool  allocated      473G        -
+pool  readonly       off         -
+.Ed
+.It Sy Example 8 No Destroying a Tn ZFS No Storage Pool
+.Pp
+The following command destroys the pool
+.Qq Em tank
+and any datasets contained within.
+.Bd -literal -offset 2n
+.Li # Ic zpool destroy -f tank
+.Ed
+.It Sy Example 9 No Exporting a Tn ZFS No Storage Pool
+.Pp
+The following command exports the devices in pool
+.Em tank
+so that they can be relocated or later imported.
+.Bd -literal -offset 2n
+.Li # Ic zpool export tank
+.Ed
+.It Sy Example 10 No Importing a Tn ZFS No Storage Pool
+.Pp
+The following command displays available pools, and then imports the pool
+.Qq Em tank
+for use on the system.
+.Pp
+The results from this command are similar to the following:
+.Bd -literal -offset 2n
+.Li # Ic zpool import
 
-.sp
-.in +2
-.nf
-# \fBzpool add tank mirror da0 da1\fR
-.fi
-.in -2
-.sp
-
-.LP
-\fBExample 6 \fRListing Available ZFS Storage Pools
-.sp
-.LP
-The following command lists all available pools on the system. In this case,
-the pool \fIzion\fR is faulted due to a missing device.
-
-.sp
-.LP
-The results from this command are similar to the following:
-
-.sp
-.in +2
-.nf
-# \fBzpool list\fR
-     NAME              SIZE    USED   AVAIL    CAP  HEALTH     ALTROOT
-     pool             67.5G   2.92M   67.5G     0%  ONLINE     -
-     tank             67.5G   2.92M   67.5G     0%  ONLINE     -
-     zion                 -       -       -     0%  FAULTED    -
-.fi
-.in -2
-.sp
-
-.LP
-\fBExample 7 \fRDestroying a ZFS Storage Pool
-.sp
-.LP
-The following command destroys the pool "\fItank\fR" and any datasets contained
-within.
-
-.sp
-.in +2
-.nf
-# \fBzpool destroy -f tank\fR
-.fi
-.in -2
-.sp
-
-.LP
-\fBExample 8 \fRExporting a ZFS Storage Pool
-.sp
-.LP
-The following command exports the devices in pool \fItank\fR so that they can
-be relocated or later imported.
-
-.sp
-.in +2
-.nf
-# \fBzpool export tank\fR
-.fi
-.in -2
-.sp
-
-.LP
-\fBExample 9 \fRImporting a ZFS Storage Pool
-.sp
-.LP
-The following command displays available pools, and then imports the pool
-"tank" for use on the system.
-
-.sp
-.LP
-The results from this command are similar to the following:
-
-.sp
-.in +2
-.nf
-# \fBzpool import\fR
   pool: tank
     id: 15451357997522795478
  state: ONLINE
@@ -1808,132 +1732,83 @@
           mirror    ONLINE
                da0  ONLINE
                da1  ONLINE
-
-# \fBzpool import tank\fR
-.fi
-.in -2
-.sp
-
-.LP
-\fBExample 10 \fRUpgrading All ZFS Storage Pools to the Current Version
-.sp
-.LP
-The following command upgrades all ZFS Storage pools to the current version of
+.Ed
+.It Xo
+.Sy Example 11
+Upgrading All
+.Tn ZFS
+Storage Pools to the Current Version
+.Xc
+.Pp
+The following command upgrades all
+.Tn ZFS
+Storage pools to the current version of
 the software.
-
-.sp
-.in +2
-.nf
-# \fBzpool upgrade -a\fR
-This system is currently running ZFS version 2.
-.fi
-.in -2
-.sp
-
-.LP
-\fBExample 11 \fRManaging Hot Spares
-.sp
-.LP
+.Bd -literal -offset 2n
+.Li # Ic zpool upgrade -a
+This system is currently running ZFS pool version 28.
+.Ed
+.It Sy Example 12 No Managing Hot Spares
+.Pp
 The following command creates a new pool with an available hot spare:
-
-.sp
-.in +2
-.nf
-# \fBzpool create tank mirror da0 da1 spare da2\fR
-.fi
-.in -2
-.sp
-
-.sp
-.LP
+.Bd -literal -offset 2n
+.Li # Ic zpool create tank mirror da0 da1 spare da2
+.Ed
+.Pp
 If one of the disks were to fail, the pool would be reduced to the degraded
 state. The failed device can be replaced using the following command:
-
-.sp
-.in +2
-.nf
-# \fBzpool replace tank da0 da2\fR
-.fi
-.in -2
-.sp
-
-.sp
-.LP
+.Bd -literal -offset 2n
+.Li # Ic zpool replace tank da0 da2
+.Ed
+.Pp
 Once the data has been resilvered, the spare is automatically removed and is
 made available should another device fails. The hot spare can be permanently
 removed from the pool using the following command:
-
-.sp
-.in +2
-.nf
-# \fBzpool remove tank da3\fR
-.fi
-.in -2
-.sp
-
-.LP
-\fBExample 12 \fRCreating a ZFS Pool with Mirrored Separate Intent Logs
-.sp
-.LP
-The following command creates a ZFS storage pool consisting of two, two-way
+.Bd -literal -offset 2n
+.Li # Ic zpool remove tank da2
+.Ed
+.It Xo
+.Sy Example 13
+Creating a
+.Tn ZFS
+Pool with Mirrored Separate Intent Logs
+.Xc
+.Pp
+The following command creates a
+.Tn ZFS
+storage pool consisting of two, two-way
 mirrors and mirrored log devices:
-
-.sp
-.in +2
-.nf
-# \fBzpool create pool mirror da0 da1 mirror da2 da3 log mirror \e
-   da4 da5\fR
-.fi
-.in -2
-.sp
-
-.LP
-\fBExample 13 \fRAdding Cache Devices to a ZFS Pool
-.sp
-.LP
-The following command adds two disks for use as cache devices to a ZFS storage
-pool:
-
-.sp
-.in +2
-.nf
-# \fBzpool add pool cache c2d0 c3d0\fR
-.fi
-.in -2
-.sp
-
-.sp
-.LP
+.Bd -literal -offset 2n
+.Li # Ic zpool create pool mirror da0 da1 mirror da2 da3 log miror da4 da5
+.Ed
+.It Sy Example 14 No Adding Cache Devices to a Tn ZFS No Pool
+.Pp
+The following command adds two disks for use as cache devices to a
+.Tn ZFS
+storage pool:
+.Bd -literal -offset 2n
+.Li # Ic zpool add pool cache da2 da3
+.Ed
+.Pp
 Once added, the cache devices gradually fill with content from main memory.
 Depending on the size of your cache devices, it could take over an hour for
-them to fill. Capacity and reads can be monitored using the \fBiostat\fR option
-as follows:
-
-.sp
-.in +2
-.nf
-# \fBzpool iostat -v pool 5\fR
-.fi
-.in -2
-.sp
-
-.LP
-\fBExample 14 \fRRemoving a Mirrored Log Device
-.sp
-.LP
-The following command removes the mirrored log device \fBmirror-2\fR.
-
-.sp
-.LP
+them to fill. Capacity and reads can be monitored using the
+.Cm iostat
+subcommand as follows:
+.Bd -literal -offset 2n
+.Li # Ic zpool iostat -v pool 5
+.Ed
+.It Sy Example 15 No Removing a Mirrored Log Device
+.Pp
+The following command removes the mirrored log device
+.Em mirror-2 .
+.Pp
 Given this configuration:
-
-.sp
-.in +2
-.nf
+.Bd -literal -offset 2n
    pool: tank
   state: ONLINE
   scrub: none requested
-config:
+ config:
 
          NAME        STATE     READ WRITE CKSUM
          tank        ONLINE       0     0     0
@@ -1947,54 +1822,68 @@
            mirror-2  ONLINE       0     0     0
                 da4  ONLINE       0     0     0
                 da5  ONLINE       0     0     0
-.fi
-.in -2
-.sp
-
-.sp
-.LP
-The command to remove the mirrored log \fBmirror-2\fR is:
-
-.sp
-.in +2
-.nf
-# \fBzpool remove tank mirror-2\fR
-.fi
-.in -2
-.sp
-
-.SH EXIT STATUS
-.sp
-.LP
+.Ed
+.Pp
+The command to remove the mirrored log
+.Em mirror-2
+is:
+.Bd -literal -offset 2n
+.Li # Ic zpool remove tank mirror-2
+.Ed
+.It Sy Example 16 No Recovering a Faulted Tn ZFS No Pool
+.Pp
+If a pool is faulted but recoverable, a message indicating this state is
+provided by
+.Qq Nm Cm status
+if the pool was cached (see the
+.Fl c Ar cachefile
+argument above), or as part of the error output from a failed
+.Qq Nm Cm import
+of the pool.
+.Pp
+Recover a cached pool with the
+.Qq Nm Cm clear
+command:
+.Bd -literal -offset 2n
+.Li # Ic zpool clear -F data
+Pool data returned to its state as of Tue Sep 08 13:23:35 2009.
+Discarded approximately 29 seconds of transactions.
+.Ed
+.Pp
+If the pool configuration was not cached, use
+.Qq Nm Cm import
+with the recovery mode flag:
+.Bd -literal -offset 2n
+.Li # Ic zpool import -F data
+Pool data returned to its state as of Tue Sep 08 13:23:35 2009.
+Discarded approximately 29 seconds of transactions.
+.Ed
+.El
+.Sh EXIT STATUS
 The following exit values are returned:
-.sp
-.ne 2
-.na
-\fB\fB0\fR\fR
-.ad
-.RS 5n
+.Bl -tag -offset 2n -width 2n
+.It 0
 Successful completion.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB1\fR\fR
-.ad
-.RS 5n
+.It 1
 An error occurred.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB2\fR\fR
-.ad
-.RS 5n
+.It 2
 Invalid command line options were specified.
-.RE
-
-.SH SEE ALSO
-.sp
-.LP
-zfs(8)
+.El
+.Sh SEE ALSO
+.Xr zfs 8
+.Sh AUTHORS
+This manual page is a
+.Xr mdoc 7
+reimplementation of the
+.Tn OpenSolaris
+manual page
+.Em zpool(1M) ,
+modified and customized for
+.Fx
+and licensed under the Common Development and Distribution License
+.Pq Tn CDDL .
+.Pp
+The
+.Xr mdoc 7
+implementation of this manual page was initially written by
+.An Martin Matuska Aq mm at FreeBSD.org .
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/cddl/contrib/opensolaris/cmd/zpool/zpool_main.c
--- a/head/cddl/contrib/opensolaris/cmd/zpool/zpool_main.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/cddl/contrib/opensolaris/cmd/zpool/zpool_main.c	Tue Dec 06 20:26:16 2011 +0200
@@ -22,6 +22,8 @@
 /*
  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
  * Copyright 2011 Nexenta Systems, Inc. All rights reserved.
+ * Copyright (c) 2011 by Delphix. All rights reserved.
+ * Copyright (c) 2011 Martin Matuska <mm at FreeBSD.org>. All rights reserved.
  */
 
 #include <solaris.h>
@@ -68,6 +70,8 @@
 static int zpool_do_offline(int, char **);
 static int zpool_do_clear(int, char **);
 
+static int zpool_do_reguid(int, char **);
+
 static int zpool_do_attach(int, char **);
 static int zpool_do_detach(int, char **);
 static int zpool_do_replace(int, char **);
@@ -126,7 +130,8 @@
 	HELP_UPGRADE,
 	HELP_GET,
 	HELP_SET,
-	HELP_SPLIT
+	HELP_SPLIT,
+	HELP_REGUID
 } zpool_help_t;
 
 
@@ -172,6 +177,7 @@
 	{ "import",	zpool_do_import,	HELP_IMPORT		},
 	{ "export",	zpool_do_export,	HELP_EXPORT		},
 	{ "upgrade",	zpool_do_upgrade,	HELP_UPGRADE		},
+	{ "reguid",	zpool_do_reguid,	HELP_REGUID		},
 	{ NULL },
 	{ "history",	zpool_do_history,	HELP_HISTORY		},
 	{ "get",	zpool_do_get,		HELP_GET		},
@@ -228,7 +234,7 @@
 	case HELP_OFFLINE:
 		return (gettext("\toffline [-t] <pool> <device> ...\n"));
 	case HELP_ONLINE:
-		return (gettext("\tonline <pool> <device> ...\n"));
+		return (gettext("\tonline [-e] <pool> <device> ...\n"));
 	case HELP_REPLACE:
 		return (gettext("\treplace [-f] <pool> <device> "
 		    "[new-device]\n"));
@@ -240,8 +246,7 @@
 		return (gettext("\tstatus [-vx] [-T d|u] [pool] ... [interval "
 		    "[count]]\n"));
 	case HELP_UPGRADE:
-		return (gettext("\tupgrade\n"
-		    "\tupgrade -v\n"
+		return (gettext("\tupgrade [-v]\n"
 		    "\tupgrade [-V version] <-a | pool ...>\n"));
 	case HELP_GET:
 		return (gettext("\tget <\"all\" | property[,...]> "
@@ -252,6 +257,8 @@
 		return (gettext("\tsplit [-n] [-R altroot] [-o mntopts]\n"
 		    "\t    [-o property=value] <pool> <newpool> "
 		    "[<device> ...]\n"));
+	case HELP_REGUID:
+		return (gettext("\treguid <pool>\n"));
 	}
 
 	abort();
@@ -1455,6 +1462,7 @@
 	const char *health;
 	uint_t vsc;
 	int namewidth;
+	char *comment;
 
 	verify(nvlist_lookup_string(config, ZPOOL_CONFIG_POOL_NAME,
 	    &name) == 0);
@@ -1471,9 +1479,9 @@
 
 	reason = zpool_import_status(config, &msgid);
 
-	(void) printf(gettext("  pool: %s\n"), name);
-	(void) printf(gettext("    id: %llu\n"), (u_longlong_t)guid);
-	(void) printf(gettext(" state: %s"), health);
+	(void) printf(gettext("   pool: %s\n"), name);
+	(void) printf(gettext("     id: %llu\n"), (u_longlong_t)guid);
+	(void) printf(gettext("  state: %s"), health);
 	if (pool_state == POOL_STATE_DESTROYED)
 		(void) printf(gettext(" (DESTROYED)"));
 	(void) printf("\n");
@@ -1482,58 +1490,59 @@
 	case ZPOOL_STATUS_MISSING_DEV_R:
 	case ZPOOL_STATUS_MISSING_DEV_NR:
 	case ZPOOL_STATUS_BAD_GUID_SUM:
-		(void) printf(gettext("status: One or more devices are missing "
-		    "from the system.\n"));
+		(void) printf(gettext(" status: One or more devices are "
+		    "missing from the system.\n"));
 		break;
 
 	case ZPOOL_STATUS_CORRUPT_LABEL_R:
 	case ZPOOL_STATUS_CORRUPT_LABEL_NR:
-		(void) printf(gettext("status: One or more devices contains "
+		(void) printf(gettext(" status: One or more devices contains "
 		    "corrupted data.\n"));
 		break;
 
 	case ZPOOL_STATUS_CORRUPT_DATA:
-		(void) printf(gettext("status: The pool data is corrupted.\n"));
+		(void) printf(
+		    gettext(" status: The pool data is corrupted.\n"));
 		break;
 
 	case ZPOOL_STATUS_OFFLINE_DEV:
-		(void) printf(gettext("status: One or more devices "
+		(void) printf(gettext(" status: One or more devices "
 		    "are offlined.\n"));
 		break;
 
 	case ZPOOL_STATUS_CORRUPT_POOL:
-		(void) printf(gettext("status: The pool metadata is "
+		(void) printf(gettext(" status: The pool metadata is "
 		    "corrupted.\n"));
 		break;
 
 	case ZPOOL_STATUS_VERSION_OLDER:
-		(void) printf(gettext("status: The pool is formatted using an "
+		(void) printf(gettext(" status: The pool is formatted using an "
 		    "older on-disk version.\n"));
 		break;
 
 	case ZPOOL_STATUS_VERSION_NEWER:
-		(void) printf(gettext("status: The pool is formatted using an "
+		(void) printf(gettext(" status: The pool is formatted using an "
 		    "incompatible version.\n"));
 		break;
 
 	case ZPOOL_STATUS_HOSTID_MISMATCH:
-		(void) printf(gettext("status: The pool was last accessed by "
+		(void) printf(gettext(" status: The pool was last accessed by "
 		    "another system.\n"));
 		break;
 
 	case ZPOOL_STATUS_FAULTED_DEV_R:
 	case ZPOOL_STATUS_FAULTED_DEV_NR:
-		(void) printf(gettext("status: One or more devices are "
+		(void) printf(gettext(" status: One or more devices are "
 		    "faulted.\n"));
 		break;
 
 	case ZPOOL_STATUS_BAD_LOG:
-		(void) printf(gettext("status: An intent log record cannot be "
+		(void) printf(gettext(" status: An intent log record cannot be "
 		    "read.\n"));
 		break;
 
 	case ZPOOL_STATUS_RESILVERING:
-		(void) printf(gettext("status: One or more devices were being "
+		(void) printf(gettext(" status: One or more devices were being "
 		    "resilvered.\n"));
 		break;
 
@@ -1549,26 +1558,26 @@
 	 */
 	if (vs->vs_state == VDEV_STATE_HEALTHY) {
 		if (reason == ZPOOL_STATUS_VERSION_OLDER)
-			(void) printf(gettext("action: The pool can be "
+			(void) printf(gettext(" action: The pool can be "
 			    "imported using its name or numeric identifier, "
 			    "though\n\tsome features will not be available "
 			    "without an explicit 'zpool upgrade'.\n"));
 		else if (reason == ZPOOL_STATUS_HOSTID_MISMATCH)
-			(void) printf(gettext("action: The pool can be "
+			(void) printf(gettext(" action: The pool can be "
 			    "imported using its name or numeric "
 			    "identifier and\n\tthe '-f' flag.\n"));
 		else
-			(void) printf(gettext("action: The pool can be "
+			(void) printf(gettext(" action: The pool can be "
 			    "imported using its name or numeric "
 			    "identifier.\n"));
 	} else if (vs->vs_state == VDEV_STATE_DEGRADED) {
-		(void) printf(gettext("action: The pool can be imported "
+		(void) printf(gettext(" action: The pool can be imported "
 		    "despite missing or damaged devices.  The\n\tfault "
 		    "tolerance of the pool may be compromised if imported.\n"));
 	} else {
 		switch (reason) {
 		case ZPOOL_STATUS_VERSION_NEWER:
-			(void) printf(gettext("action: The pool cannot be "
+			(void) printf(gettext(" action: The pool cannot be "
 			    "imported.  Access the pool on a system running "
 			    "newer\n\tsoftware, or recreate the pool from "
 			    "backup.\n"));
@@ -1576,16 +1585,20 @@
 		case ZPOOL_STATUS_MISSING_DEV_R:
 		case ZPOOL_STATUS_MISSING_DEV_NR:
 		case ZPOOL_STATUS_BAD_GUID_SUM:
-			(void) printf(gettext("action: The pool cannot be "
+			(void) printf(gettext(" action: The pool cannot be "
 			    "imported. Attach the missing\n\tdevices and try "
 			    "again.\n"));
 			break;
 		default:
-			(void) printf(gettext("action: The pool cannot be "
+			(void) printf(gettext(" action: The pool cannot be "
 			    "imported due to damaged devices or data.\n"));
 		}
 	}
 
+	/* Print the comment attached to the pool. */
+	if (nvlist_lookup_string(config, ZPOOL_CONFIG_COMMENT, &comment) == 0)
+		(void) printf(gettext("comment: %s\n"), comment);
+
 	/*
 	 * If the state is "closed" or "can't open", and the aux state
 	 * is "corrupt data":
@@ -1606,7 +1619,7 @@
 		(void) printf(gettext("   see: http://www.sun.com/msg/%s\n"),
 		    msgid);
 
-	(void) printf(gettext("config:\n\n"));
+	(void) printf(gettext(" config:\n\n"));
 
 	namewidth = max_width(NULL, nvroot, 0, 0);
 	if (namewidth < 10)
@@ -3321,6 +3334,52 @@
 	return (ret);
 }
 
+/*
+ * zpool reguid <pool>
+ */
+int
+zpool_do_reguid(int argc, char **argv)
+{
+	int c;
+	char *poolname;
+	zpool_handle_t *zhp;
+	int ret = 0;
+
+	/* check options */
+	while ((c = getopt(argc, argv, "")) != -1) {
+		switch (c) {
+		case '?':
+			(void) fprintf(stderr, gettext("invalid option '%c'\n"),
+			    optopt);
+			usage(B_FALSE);
+		}
+	}
+
+	argc -= optind;
+	argv += optind;
+
+	/* get pool name and check number of arguments */
+	if (argc < 1) {
+		(void) fprintf(stderr, gettext("missing pool name\n"));
+		usage(B_FALSE);
+	}
+
+	if (argc > 1) {
+		(void) fprintf(stderr, gettext("too many arguments\n"));
+		usage(B_FALSE);
+	}
+
+	poolname = argv[0];
+	if ((zhp = zpool_open(g_zfs, poolname)) == NULL)
+		return (1);
+
+	ret = zpool_reguid(zhp);
+
+	zpool_close(zhp);
+	return (ret);
+}
+
+
 typedef struct scrub_cbdata {
 	int	cb_type;
 	int	cb_argc;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/cddl/contrib/opensolaris/cmd/zstreamdump/zstreamdump.1
--- a/head/cddl/contrib/opensolaris/cmd/zstreamdump/zstreamdump.1	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/cddl/contrib/opensolaris/cmd/zstreamdump/zstreamdump.1	Tue Dec 06 20:26:16 2011 +0200
@@ -1,49 +1,67 @@
 '\" te
-.\" Copyright (c) 2009, Sun Microsystems, Inc. All Rights Reserved
-.\" The contents of this file are subject to the terms of the Common Development and Distribution License (the "License").  You may not use this file except in compliance with the License. You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE or http://www.opensolaris.org/os/licensing.
-.\"  See the License for the specific language governing permissions and limitations under the License. When distributing Covered Code, include this CDDL HEADER in each file and include the License file at usr/src/OPENSOLARIS.LICENSE.  If applicable, add the following below this CDDL HEADER, with
-.\" the fields enclosed by brackets "[]" replaced with your own identifying information: Portions Copyright [yyyy] [name of copyright owner]
-.\" Portions Copyright 2011 Martin Matuska <mm at FreeBSD.org>
-.TH ZSTREAMDUMP 1 "Sep 21, 2009"
-.SH NAME
-zstreamdump \- filter data in zfs send stream
-.SH SYNOPSIS
-.LP
-.nf
-\fBzstreamdump\fR [\fB-C\fR] [\fB-v\fR]
-.fi
-
-.SH DESCRIPTION
-.sp
-.LP
-The \fBzstreamdump\fR utility reads from the output of the \fBzfs send\fR
-command, then displays headers and some statistics from that output.  See
-\fBzfs\fR(1M).
-.SH OPTIONS
-.sp
-.LP
+.\" Copyright (c) 2011, Martin Matuska <mm at FreeBSD.org>.
+.\" All Rights Reserved.
+.\"
+.\" The contents of this file are subject to the terms of the
+.\" Common Development and Distribution License (the "License").
+.\" You may not use this file except in compliance with the License.
+.\"
+.\" You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
+.\" or http://www.opensolaris.org/os/licensing.
+.\" See the License for the specific language governing permissions
+.\" and limitations under the License.
+.\"
+.\" When distributing Covered Code, include this CDDL HEADER in each
+.\" file and include the License file at usr/src/OPENSOLARIS.LICENSE.
+.\" If applicable, add the following below this CDDL HEADER, with the
+.\" fields enclosed by brackets "[]" replaced with your own identifying
+.\" information: Portions Copyright [yyyy] [name of copyright owner]
+.\"
+.\" Copyright (c) 2009, Sun Microsystems, Inc. All Rights Reserved.
+.\"
+.\" $FreeBSD$
+.\"
+.Dd November 26, 2011
+.Dt ZSTREAMDUMP 8
+.Os
+.Sh NAME
+.Nm zdb
+.Nd filter data in zfs send stream
+.Sh SYNOPSIS
+.Nm
+.Op Fl C
+.Op Fl v
+.Sh DESCRIPTION
+The
+.Nm
+utility reads from the output of the
+.Qq Nm zfs Cm send
+command, then displays headers and some statistics from that output. See
+.Xr zfs 8 .
+.Pp
 The following options are supported:
-.sp
-.ne 2
-.na
-\fB\fB-C\fR\fR
-.ad
-.sp .6
-.RS 4n
+.Bl -tag -width indent
+.It Fl C
 Suppress the validation of checksums.
-.RE
-
-.sp
-.ne 2
-.na
-\fB\fB-v\fR\fR
-.ad
-.sp .6
-.RS 4n
+.It Fl v
 Verbose. Dump all headers, not only begin and end headers.
-.RE
-
-.SH SEE ALSO
-.sp
-.LP
-zfs(8)
+.El
+.Sh SEE ALSO
+.Xr zfs 8
+.Sh AUTHORS
+This manual page is a
+.Xr mdoc 7
+reimplementation of the
+.Tn OpenSolaris
+manual page
+.Em zstreamdump(1M) ,
+modified and customized for
+.Fx
+and licensed under the
+.Tn Common Development and Distribution License
+.Pq Tn CDDL .
+.Pp
+The
+.Xr mdoc 7
+implementation of this manual page was initially written by
+.An Martin Matuska Aq mm at FreeBSD.org .
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/cddl/contrib/opensolaris/cmd/ztest/ztest.c
--- a/head/cddl/contrib/opensolaris/cmd/ztest/ztest.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/cddl/contrib/opensolaris/cmd/ztest/ztest.c	Tue Dec 06 20:26:16 2011 +0200
@@ -21,6 +21,7 @@
 /*
  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
  * Copyright (c) 2011 by Delphix. All rights reserved.
+ * Copyright 2011 Nexenta Systems, Inc.  All rights reserved.
  */
 
 /*
@@ -259,6 +260,7 @@
 ztest_func_t ztest_vdev_add_remove;
 ztest_func_t ztest_vdev_aux_add_remove;
 ztest_func_t ztest_split_pool;
+ztest_func_t ztest_reguid;
 
 uint64_t zopt_always = 0ULL * NANOSEC;		/* all the time */
 uint64_t zopt_incessant = 1ULL * NANOSEC / 10;	/* every 1/10 second */
@@ -289,6 +291,7 @@
 	{ ztest_fault_inject,			1,	&zopt_sometimes	},
 	{ ztest_ddt_repair,			1,	&zopt_sometimes	},
 	{ ztest_dmu_snapshot_hold,		1,	&zopt_sometimes	},
+	{ ztest_reguid,				1,	&zopt_sometimes },
 	{ ztest_spa_rename,			1,	&zopt_rarely	},
 	{ ztest_scrub,				1,	&zopt_rarely	},
 	{ ztest_dsl_dataset_promote_busy,	1,	&zopt_rarely	},
@@ -325,6 +328,7 @@
 	uint64_t	zs_vdev_aux;
 	uint64_t	zs_alloc;
 	uint64_t	zs_space;
+	uint64_t	zs_guid;
 	mutex_t		zs_vdev_lock;
 	rwlock_t	zs_name_lock;
 	ztest_info_t	zs_info[ZTEST_FUNCS];
@@ -4646,7 +4650,7 @@
 
 	object = od[0].od_object;
 	blocksize = od[0].od_blocksize;
-	pattern = spa_guid(spa) ^ dmu_objset_fsid_guid(os);
+	pattern = zs->zs_guid ^ dmu_objset_fsid_guid(os);
 
 	ASSERT(object != 0);
 
@@ -4717,6 +4721,31 @@
 }
 
 /*
+ * Change the guid for the pool.
+ */
+/* ARGSUSED */
+void
+ztest_reguid(ztest_ds_t *zd, uint64_t id)
+{
+	ztest_shared_t *zs = ztest_shared;
+	spa_t *spa = zs->zs_spa;
+	uint64_t orig, load;
+
+	orig = spa_guid(spa);
+	load = spa_load_guid(spa);
+	if (spa_change_guid(spa) != 0)
+		return;
+
+	if (zopt_verbose >= 3) {
+		(void) printf("Changed guid old %llu -> %llu\n",
+		    (u_longlong_t)orig, (u_longlong_t)spa_guid(spa));
+	}
+
+	VERIFY3U(orig, !=, spa_guid(spa));
+	VERIFY3U(load, ==, spa_load_guid(spa));
+}
+
+/*
  * Rename the pool to a different name and then rename it back.
  */
 /* ARGSUSED */
@@ -5145,6 +5174,7 @@
 {
 	thread_t *tid;
 	spa_t *spa;
+	objset_t *os;
 	thread_t resume_tid;
 	int error;
 
@@ -5176,6 +5206,10 @@
 	spa->spa_debug = B_TRUE;
 	zs->zs_spa = spa;
 
+	VERIFY3U(0, ==, dmu_objset_hold(zs->zs_pool, FTAG, &os));
+	zs->zs_guid = dmu_objset_fsid_guid(os);
+	dmu_objset_rele(os, FTAG);
+
 	spa->spa_dedup_ditto = 2 * ZIO_DEDUPDITTO_MIN;
 
 	/*
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/cddl/contrib/opensolaris/lib/libzfs/common/libzfs.h
--- a/head/cddl/contrib/opensolaris/lib/libzfs/common/libzfs.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/cddl/contrib/opensolaris/lib/libzfs/common/libzfs.h	Tue Dec 06 20:26:16 2011 +0200
@@ -21,8 +21,8 @@
 
 /*
  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
- * Copyright 2010 Nexenta Systems, Inc. All rights reserved.
- * Copyright (c) 2011 Pawel Jakub Dawidek <pawel at dawidek.net>.
+ * Copyright 2011 Nexenta Systems, Inc. All rights reserved.
+ * Copyright (c) 2011 by Delphix. All rights reserved.
  * All rights reserved.
  */
 
@@ -233,6 +233,7 @@
  */
 extern int zpool_scan(zpool_handle_t *, pool_scan_func_t);
 extern int zpool_clear(zpool_handle_t *, const char *, nvlist_t *);
+extern int zpool_reguid(zpool_handle_t *);
 
 extern int zpool_vdev_online(zpool_handle_t *, const char *, int,
     vdev_state_t *);
@@ -384,6 +385,7 @@
  * underlying datasets, only the references to them.
  */
 extern zfs_handle_t *zfs_open(libzfs_handle_t *, const char *, int);
+extern zfs_handle_t *zfs_handle_dup(zfs_handle_t *);
 extern void zfs_close(zfs_handle_t *);
 extern zfs_type_t zfs_get_type(const zfs_handle_t *);
 extern const char *zfs_get_name(const zfs_handle_t *);
@@ -417,12 +419,20 @@
     uint64_t *propvalue);
 extern int zfs_prop_get_userquota(zfs_handle_t *zhp, const char *propname,
     char *propbuf, int proplen, boolean_t literal);
+extern int zfs_prop_get_written_int(zfs_handle_t *zhp, const char *propname,
+    uint64_t *propvalue);
+extern int zfs_prop_get_written(zfs_handle_t *zhp, const char *propname,
+    char *propbuf, int proplen, boolean_t literal);
+extern int zfs_get_snapused_int(zfs_handle_t *firstsnap, zfs_handle_t *lastsnap,
+    uint64_t *usedp);
 extern uint64_t zfs_prop_get_int(zfs_handle_t *, zfs_prop_t);
 extern int zfs_prop_inherit(zfs_handle_t *, const char *, boolean_t);
 extern const char *zfs_prop_values(zfs_prop_t);
 extern int zfs_prop_is_string(zfs_prop_t prop);
 extern nvlist_t *zfs_get_user_props(zfs_handle_t *);
 extern nvlist_t *zfs_get_recvd_props(zfs_handle_t *);
+extern nvlist_t *zfs_get_clones_nvl(zfs_handle_t *);
+
 
 typedef struct zprop_list {
 	int		pl_prop;
@@ -497,6 +507,7 @@
 extern int zfs_iter_filesystems(zfs_handle_t *, zfs_iter_f, void *);
 extern int zfs_iter_snapshots(zfs_handle_t *, zfs_iter_f, void *);
 extern int zfs_iter_snapshots_sorted(zfs_handle_t *, zfs_iter_f, void *);
+extern int zfs_iter_snapspec(zfs_handle_t *, const char *, zfs_iter_f, void *);
 
 typedef struct get_all_cb {
 	zfs_handle_t	**cb_handles;
@@ -517,6 +528,7 @@
 extern int zfs_create_ancestors(libzfs_handle_t *, const char *);
 extern int zfs_destroy(zfs_handle_t *, boolean_t);
 extern int zfs_destroy_snaps(zfs_handle_t *, char *, boolean_t);
+extern int zfs_destroy_snaps_nvl(zfs_handle_t *, nvlist_t *, boolean_t);
 extern int zfs_clone(zfs_handle_t *, const char *, nvlist_t *);
 extern int zfs_snapshot(libzfs_handle_t *, const char *, boolean_t, nvlist_t *);
 extern int zfs_rollback(zfs_handle_t *, zfs_handle_t *, boolean_t);
@@ -533,29 +545,34 @@
 
 typedef struct sendflags {
 	/* print informational messages (ie, -v was specified) */
-	int verbose : 1;
+	boolean_t verbose;
 
 	/* recursive send  (ie, -R) */
-	int replicate : 1;
+	boolean_t replicate;
 
 	/* for incrementals, do all intermediate snapshots */
-	int doall : 1; /* (ie, -I) */
+	boolean_t doall;
 
 	/* if dataset is a clone, do incremental from its origin */
-	int fromorigin : 1;
+	boolean_t fromorigin;
 
 	/* do deduplication */
-	int dedup : 1;
+	boolean_t dedup;
 
 	/* send properties (ie, -p) */
-	int props : 1;
+	boolean_t props;
+
+	/* do not send (no-op, ie. -n) */
+	boolean_t dryrun;
+
+	/* parsable verbose output (ie. -P) */
+	boolean_t parsable;
 } sendflags_t;
 
 typedef boolean_t (snapfilter_cb_t)(zfs_handle_t *, void *);
 
-extern int zfs_send(zfs_handle_t *zhp, const char *fromsnap, const char *tosnap,
-    sendflags_t flags, int outfd, snapfilter_cb_t filter_func,
-    void *cb_arg, nvlist_t **debugnvp);
+extern int zfs_send(zfs_handle_t *, const char *, const char *,
+    sendflags_t *, int, snapfilter_cb_t, void *, nvlist_t **);
 
 extern int zfs_promote(zfs_handle_t *);
 extern int zfs_hold(zfs_handle_t *, const char *, const char *, boolean_t,
@@ -575,34 +592,34 @@
 
 typedef struct recvflags {
 	/* print informational messages (ie, -v was specified) */
-	int verbose : 1;
+	boolean_t verbose;
 
 	/* the destination is a prefix, not the exact fs (ie, -d) */
-	int isprefix : 1;
+	boolean_t isprefix;
 
 	/*
 	 * Only the tail of the sent snapshot path is appended to the
 	 * destination to determine the received snapshot name (ie, -e).
 	 */
-	int istail : 1;
+	boolean_t istail;
 
 	/* do not actually do the recv, just check if it would work (ie, -n) */
-	int dryrun : 1;
+	boolean_t dryrun;
 
 	/* rollback/destroy filesystems as necessary (eg, -F) */
-	int force : 1;
+	boolean_t force;
 
 	/* set "canmount=off" on all modified filesystems */
-	int canmountoff : 1;
+	boolean_t canmountoff;
 
 	/* byteswap flag is used internally; callers need not specify */
-	int byteswap : 1;
+	boolean_t byteswap;
 
 	/* do not mount file systems as they are extracted (private) */
-	int nomount : 1;
+	boolean_t nomount;
 } recvflags_t;
 
-extern int zfs_receive(libzfs_handle_t *, const char *, recvflags_t,
+extern int zfs_receive(libzfs_handle_t *, const char *, recvflags_t *,
     int, avl_tree_t *);
 
 typedef enum diff_flags {
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/cddl/contrib/opensolaris/lib/libzfs/common/libzfs_dataset.c
--- a/head/cddl/contrib/opensolaris/lib/libzfs/common/libzfs_dataset.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/cddl/contrib/opensolaris/lib/libzfs/common/libzfs_dataset.c	Tue Dec 06 20:26:16 2011 +0200
@@ -496,7 +496,7 @@
 	return (zhp);
 }
 
-static zfs_handle_t *
+zfs_handle_t *
 make_dataset_handle_zc(libzfs_handle_t *hdl, zfs_cmd_t *zc)
 {
 	zfs_handle_t *zhp = calloc(sizeof (zfs_handle_t), 1);
@@ -513,6 +513,53 @@
 	return (zhp);
 }
 
+zfs_handle_t *
+zfs_handle_dup(zfs_handle_t *zhp_orig)
+{
+	zfs_handle_t *zhp = calloc(sizeof (zfs_handle_t), 1);
+
+	if (zhp == NULL)
+		return (NULL);
+
+	zhp->zfs_hdl = zhp_orig->zfs_hdl;
+	zhp->zpool_hdl = zhp_orig->zpool_hdl;
+	(void) strlcpy(zhp->zfs_name, zhp_orig->zfs_name,
+	    sizeof (zhp->zfs_name));
+	zhp->zfs_type = zhp_orig->zfs_type;
+	zhp->zfs_head_type = zhp_orig->zfs_head_type;
+	zhp->zfs_dmustats = zhp_orig->zfs_dmustats;
+	if (zhp_orig->zfs_props != NULL) {
+		if (nvlist_dup(zhp_orig->zfs_props, &zhp->zfs_props, 0) != 0) {
+			(void) no_memory(zhp->zfs_hdl);
+			zfs_close(zhp);
+			return (NULL);
+		}
+	}
+	if (zhp_orig->zfs_user_props != NULL) {
+		if (nvlist_dup(zhp_orig->zfs_user_props,
+		    &zhp->zfs_user_props, 0) != 0) {
+			(void) no_memory(zhp->zfs_hdl);
+			zfs_close(zhp);
+			return (NULL);
+		}
+	}
+	if (zhp_orig->zfs_recvd_props != NULL) {
+		if (nvlist_dup(zhp_orig->zfs_recvd_props,
+		    &zhp->zfs_recvd_props, 0)) {
+			(void) no_memory(zhp->zfs_hdl);
+			zfs_close(zhp);
+			return (NULL);
+		}
+	}
+	zhp->zfs_mntcheck = zhp_orig->zfs_mntcheck;
+	if (zhp_orig->zfs_mntopts != NULL) {
+		zhp->zfs_mntopts = zfs_strdup(zhp_orig->zfs_hdl,
+		    zhp_orig->zfs_mntopts);
+	}
+	zhp->zfs_props_table = zhp_orig->zfs_props_table;
+	return (zhp);
+}
+
 /*
  * Opens the given snapshot, filesystem, or volume.   The 'types'
  * argument is a mask of acceptable types.  The function will print an
@@ -876,6 +923,12 @@
 				goto error;
 			}
 			continue;
+		} else if (prop == ZPROP_INVAL && zfs_prop_written(propname)) {
+			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
+			    "'%s' is readonly"),
+			    propname);
+			(void) zfs_error(hdl, EZFS_PROPREADONLY, errbuf);
+			goto error;
 		}
 
 		if (prop == ZPROP_INVAL) {
@@ -1869,8 +1922,6 @@
 		err = zfs_prop_get(zhp, prop, propbuf, proplen,
 		    NULL, NULL, 0, literal);
 		zfs_unset_recvd_props_mode(zhp, &cookie);
-	} else if (zfs_prop_userquota(propname)) {
-		return (-1);
 	} else {
 		nvlist_t *propval;
 		char *recvdval;
@@ -1885,6 +1936,120 @@
 	return (err == 0 ? 0 : -1);
 }
 
+static int
+get_clones_string(zfs_handle_t *zhp, char *propbuf, size_t proplen)
+{
+	nvlist_t *value;
+	nvpair_t *pair;
+
+	value = zfs_get_clones_nvl(zhp);
+	if (value == NULL)
+		return (-1);
+
+	propbuf[0] = '\0';
+	for (pair = nvlist_next_nvpair(value, NULL); pair != NULL;
+	    pair = nvlist_next_nvpair(value, pair)) {
+		if (propbuf[0] != '\0')
+			(void) strlcat(propbuf, ",", proplen);
+		(void) strlcat(propbuf, nvpair_name(pair), proplen);
+	}
+
+	return (0);
+}
+
+struct get_clones_arg {
+	uint64_t numclones;
+	nvlist_t *value;
+	const char *origin;
+	char buf[ZFS_MAXNAMELEN];
+};
+
+int
+get_clones_cb(zfs_handle_t *zhp, void *arg)
+{
+	struct get_clones_arg *gca = arg;
+
+	if (gca->numclones == 0) {
+		zfs_close(zhp);
+		return (0);
+	}
+
+	if (zfs_prop_get(zhp, ZFS_PROP_ORIGIN, gca->buf, sizeof (gca->buf),
+	    NULL, NULL, 0, B_TRUE) != 0)
+		goto out;
+	if (strcmp(gca->buf, gca->origin) == 0) {
+		if (nvlist_add_boolean(gca->value, zfs_get_name(zhp)) != 0) {
+			zfs_close(zhp);
+			return (no_memory(zhp->zfs_hdl));
+		}
+		gca->numclones--;
+	}
+
+out:
+	(void) zfs_iter_children(zhp, get_clones_cb, gca);
+	zfs_close(zhp);
+	return (0);
+}
+
+nvlist_t *
+zfs_get_clones_nvl(zfs_handle_t *zhp)
+{
+	nvlist_t *nv, *value;
+
+	if (nvlist_lookup_nvlist(zhp->zfs_props,
+	    zfs_prop_to_name(ZFS_PROP_CLONES), &nv) != 0) {
+		struct get_clones_arg gca;
+
+		/*
+		 * if this is a snapshot, then the kernel wasn't able
+		 * to get the clones.  Do it by slowly iterating.
+		 */
+		if (zhp->zfs_type != ZFS_TYPE_SNAPSHOT)
+			return (NULL);
+		if (nvlist_alloc(&nv, NV_UNIQUE_NAME, 0) != 0)
+			return (NULL);
+		if (nvlist_alloc(&value, NV_UNIQUE_NAME, 0) != 0) {
+			nvlist_free(nv);
+			return (NULL);
+		}
+
+		gca.numclones = zfs_prop_get_int(zhp, ZFS_PROP_NUMCLONES);
+		gca.value = value;
+		gca.origin = zhp->zfs_name;
+
+		if (gca.numclones != 0) {
+			zfs_handle_t *root;
+			char pool[ZFS_MAXNAMELEN];
+			char *cp = pool;
+
+			/* get the pool name */
+			(void) strlcpy(pool, zhp->zfs_name, sizeof (pool));
+			(void) strsep(&cp, "/@");
+			root = zfs_open(zhp->zfs_hdl, pool,
+			    ZFS_TYPE_FILESYSTEM);
+
+			(void) get_clones_cb(root, &gca);
+		}
+
+		if (gca.numclones != 0 ||
+		    nvlist_add_nvlist(nv, ZPROP_VALUE, value) != 0 ||
+		    nvlist_add_nvlist(zhp->zfs_props,
+		    zfs_prop_to_name(ZFS_PROP_CLONES), nv) != 0) {
+			nvlist_free(nv);
+			nvlist_free(value);
+			return (NULL);
+		}
+		nvlist_free(nv);
+		nvlist_free(value);
+		verify(0 == nvlist_lookup_nvlist(zhp->zfs_props,
+		    zfs_prop_to_name(ZFS_PROP_CLONES), &nv));
+	}
+
+	verify(nvlist_lookup_nvlist(nv, ZPROP_VALUE, &value) == 0);
+
+	return (value);
+}
+
 /*
  * Retrieve a property from the given object.  If 'literal' is specified, then
  * numbers are left as exact values.  Otherwise, numbers are converted to a
@@ -2013,6 +2178,11 @@
 			return (-1);
 		break;
 
+	case ZFS_PROP_CLONES:
+		if (get_clones_string(zhp, propbuf, proplen) != 0)
+			return (-1);
+		break;
+
 	case ZFS_PROP_QUOTA:
 	case ZFS_PROP_REFQUOTA:
 	case ZFS_PROP_RESERVATION:
@@ -2385,7 +2555,7 @@
 	int err;
 	zfs_cmd_t zc = { 0 };
 
-	(void) strncpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
+	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
 
 	err = userquota_propname_decode(propname,
 	    zfs_prop_get_int(zhp, ZFS_PROP_ZONED),
@@ -2437,6 +2607,79 @@
 	return (0);
 }
 
+int
+zfs_prop_get_written_int(zfs_handle_t *zhp, const char *propname,
+    uint64_t *propvalue)
+{
+	int err;
+	zfs_cmd_t zc = { 0 };
+	const char *snapname;
+
+	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
+
+	snapname = strchr(propname, '@') + 1;
+	if (strchr(snapname, '@')) {
+		(void) strlcpy(zc.zc_value, snapname, sizeof (zc.zc_value));
+	} else {
+		/* snapname is the short name, append it to zhp's fsname */
+		char *cp;
+
+		(void) strlcpy(zc.zc_value, zhp->zfs_name,
+		    sizeof (zc.zc_value));
+		cp = strchr(zc.zc_value, '@');
+		if (cp != NULL)
+			*cp = '\0';
+		(void) strlcat(zc.zc_value, "@", sizeof (zc.zc_value));
+		(void) strlcat(zc.zc_value, snapname, sizeof (zc.zc_value));
+	}
+
+	err = ioctl(zhp->zfs_hdl->libzfs_fd, ZFS_IOC_SPACE_WRITTEN, &zc);
+	if (err)
+		return (err);
+
+	*propvalue = zc.zc_cookie;
+	return (0);
+}
+
+int
+zfs_prop_get_written(zfs_handle_t *zhp, const char *propname,
+    char *propbuf, int proplen, boolean_t literal)
+{
+	int err;
+	uint64_t propvalue;
+
+	err = zfs_prop_get_written_int(zhp, propname, &propvalue);
+
+	if (err)
+		return (err);
+
+	if (literal) {
+		(void) snprintf(propbuf, proplen, "%llu", propvalue);
+	} else {
+		zfs_nicenum(propvalue, propbuf, proplen);
+	}
+	return (0);
+}
+
+int
+zfs_get_snapused_int(zfs_handle_t *firstsnap, zfs_handle_t *lastsnap,
+    uint64_t *usedp)
+{
+	int err;
+	zfs_cmd_t zc = { 0 };
+
+	(void) strlcpy(zc.zc_name, lastsnap->zfs_name, sizeof (zc.zc_name));
+	(void) strlcpy(zc.zc_value, firstsnap->zfs_name, sizeof (zc.zc_value));
+
+	err = ioctl(lastsnap->zfs_hdl->libzfs_fd, ZFS_IOC_SPACE_SNAPS, &zc);
+	if (err)
+		return (err);
+
+	*usedp = zc.zc_cookie;
+
+	return (0);
+}
+
 /*
  * Returns the name of the given zfs handle.
  */
@@ -2455,128 +2698,6 @@
 	return (zhp->zfs_type);
 }
 
-static int
-zfs_do_list_ioctl(zfs_handle_t *zhp, unsigned long arg, zfs_cmd_t *zc)
-{
-	int rc;
-	uint64_t	orig_cookie;
-
-	orig_cookie = zc->zc_cookie;
-top:
-	(void) strlcpy(zc->zc_name, zhp->zfs_name, sizeof (zc->zc_name));
-	rc = ioctl(zhp->zfs_hdl->libzfs_fd, arg, zc);
-
-	if (rc == -1) {
-		switch (errno) {
-		case ENOMEM:
-			/* expand nvlist memory and try again */
-			if (zcmd_expand_dst_nvlist(zhp->zfs_hdl, zc) != 0) {
-				zcmd_free_nvlists(zc);
-				return (-1);
-			}
-			zc->zc_cookie = orig_cookie;
-			goto top;
-		/*
-		 * An errno value of ESRCH indicates normal completion.
-		 * If ENOENT is returned, then the underlying dataset
-		 * has been removed since we obtained the handle.
-		 */
-		case ESRCH:
-		case ENOENT:
-			rc = 1;
-			break;
-		default:
-			rc = zfs_standard_error(zhp->zfs_hdl, errno,
-			    dgettext(TEXT_DOMAIN,
-			    "cannot iterate filesystems"));
-			break;
-		}
-	}
-	return (rc);
-}
-
-/*
- * Iterate over all child filesystems
- */
-int
-zfs_iter_filesystems(zfs_handle_t *zhp, zfs_iter_f func, void *data)
-{
-	zfs_cmd_t zc = { 0 };
-	zfs_handle_t *nzhp;
-	int ret;
-
-	if (zhp->zfs_type != ZFS_TYPE_FILESYSTEM)
-		return (0);
-
-	if (zcmd_alloc_dst_nvlist(zhp->zfs_hdl, &zc, 0) != 0)
-		return (-1);
-
-	while ((ret = zfs_do_list_ioctl(zhp, ZFS_IOC_DATASET_LIST_NEXT,
-	    &zc)) == 0) {
-		/*
-		 * Silently ignore errors, as the only plausible explanation is
-		 * that the pool has since been removed.
-		 */
-		if ((nzhp = make_dataset_handle_zc(zhp->zfs_hdl,
-		    &zc)) == NULL) {
-			continue;
-		}
-
-		if ((ret = func(nzhp, data)) != 0) {
-			zcmd_free_nvlists(&zc);
-			return (ret);
-		}
-	}
-	zcmd_free_nvlists(&zc);
-	return ((ret < 0) ? ret : 0);
-}
-
-/*
- * Iterate over all snapshots
- */
-int
-zfs_iter_snapshots(zfs_handle_t *zhp, zfs_iter_f func, void *data)
-{
-	zfs_cmd_t zc = { 0 };
-	zfs_handle_t *nzhp;
-	int ret;
-
-	if (zhp->zfs_type == ZFS_TYPE_SNAPSHOT)
-		return (0);
-
-	if (zcmd_alloc_dst_nvlist(zhp->zfs_hdl, &zc, 0) != 0)
-		return (-1);
-	while ((ret = zfs_do_list_ioctl(zhp, ZFS_IOC_SNAPSHOT_LIST_NEXT,
-	    &zc)) == 0) {
-
-		if ((nzhp = make_dataset_handle_zc(zhp->zfs_hdl,
-		    &zc)) == NULL) {
-			continue;
-		}
-
-		if ((ret = func(nzhp, data)) != 0) {
-			zcmd_free_nvlists(&zc);
-			return (ret);
-		}
-	}
-	zcmd_free_nvlists(&zc);
-	return ((ret < 0) ? ret : 0);
-}
-
-/*
- * Iterate over all children, snapshots and filesystems
- */
-int
-zfs_iter_children(zfs_handle_t *zhp, zfs_iter_f func, void *data)
-{
-	int ret;
-
-	if ((ret = zfs_iter_filesystems(zhp, func, data)) != 0)
-		return (ret);
-
-	return (zfs_iter_snapshots(zhp, func, data));
-}
-
 /*
  * Is one dataset name a child dataset of another?
  *
@@ -2600,18 +2721,19 @@
 
 /*
  * Given a complete name, return just the portion that refers to the parent.
- * Can return NULL if this is a pool.
+ * Will return -1 if there is no parent (path is just the name of the
+ * pool).
  */
 static int
 parent_name(const char *path, char *buf, size_t buflen)
 {
-	char *loc;
-
-	if ((loc = strrchr(path, '/')) == NULL)
+	char *slashp;
+
+	(void) strlcpy(buf, path, buflen);
+
+	if ((slashp = strrchr(buf, '/')) == NULL)
 		return (-1);
-
-	(void) strncpy(buf, path, MIN(buflen, loc - path));
-	buf[loc - path] = '\0';
+	*slashp = '\0';
 
 	return (0);
 }
@@ -3010,9 +3132,8 @@
 }
 
 struct destroydata {
-	char *snapname;
-	boolean_t gotone;
-	boolean_t closezhp;
+	nvlist_t *nvl;
+	const char *snapname;
 };
 
 static int
@@ -3021,24 +3142,19 @@
 	struct destroydata *dd = arg;
 	zfs_handle_t *szhp;
 	char name[ZFS_MAXNAMELEN];
-	boolean_t closezhp = dd->closezhp;
 	int rv = 0;
 
-	(void) strlcpy(name, zhp->zfs_name, sizeof (name));
-	(void) strlcat(name, "@", sizeof (name));
-	(void) strlcat(name, dd->snapname, sizeof (name));
+	(void) snprintf(name, sizeof (name),
+	    "%s@%s", zhp->zfs_name, dd->snapname);
 
 	szhp = make_dataset_handle(zhp->zfs_hdl, name);
 	if (szhp) {
-		dd->gotone = B_TRUE;
+		verify(nvlist_add_boolean(dd->nvl, name) == 0);
 		zfs_close(szhp);
 	}
 
-	dd->closezhp = B_TRUE;
-	if (!dd->gotone)
-		rv = zfs_iter_filesystems(zhp, zfs_check_snap_cb, arg);
-	if (closezhp)
-		zfs_close(zhp);
+	rv = zfs_iter_filesystems(zhp, zfs_check_snap_cb, dd);
+	zfs_close(zhp);
 	return (rv);
 }
 
@@ -3048,29 +3164,45 @@
 int
 zfs_destroy_snaps(zfs_handle_t *zhp, char *snapname, boolean_t defer)
 {
-	zfs_cmd_t zc = { 0 };
 	int ret;
 	struct destroydata dd = { 0 };
 
 	dd.snapname = snapname;
-	(void) zfs_check_snap_cb(zhp, &dd);
-
-	if (!dd.gotone) {
-		return (zfs_standard_error_fmt(zhp->zfs_hdl, ENOENT,
+	verify(nvlist_alloc(&dd.nvl, NV_UNIQUE_NAME, 0) == 0);
+	(void) zfs_check_snap_cb(zfs_handle_dup(zhp), &dd);
+
+	if (nvlist_next_nvpair(dd.nvl, NULL) == NULL) {
+		ret = zfs_standard_error_fmt(zhp->zfs_hdl, ENOENT,
 		    dgettext(TEXT_DOMAIN, "cannot destroy '%s@%s'"),
-		    zhp->zfs_name, snapname));
+		    zhp->zfs_name, snapname);
+	} else {
+		ret = zfs_destroy_snaps_nvl(zhp, dd.nvl, defer);
 	}
+	nvlist_free(dd.nvl);
+	return (ret);
+}
+
+/*
+ * Destroys all the snapshots named in the nvlist.  They must be underneath
+ * the zhp (either snapshots of it, or snapshots of its descendants).
+ */
+int
+zfs_destroy_snaps_nvl(zfs_handle_t *zhp, nvlist_t *snaps, boolean_t defer)
+{
+	int ret;
+	zfs_cmd_t zc = { 0 };
 
 	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
-	(void) strlcpy(zc.zc_value, snapname, sizeof (zc.zc_value));
+	if (zcmd_write_src_nvlist(zhp->zfs_hdl, &zc, snaps) != 0)
+		return (-1);
 	zc.zc_defer_destroy = defer;
 
-	ret = zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_DESTROY_SNAPS, &zc);
+	ret = zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_DESTROY_SNAPS_NVL, &zc);
 	if (ret != 0) {
 		char errbuf[1024];
 
 		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
-		    "cannot destroy '%s@%s'"), zc.zc_name, snapname);
+		    "cannot destroy snapshots in %s"), zc.zc_name);
 
 		switch (errno) {
 		case EEXIST:
@@ -3106,7 +3238,7 @@
 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
 	    "cannot create '%s'"), target);
 
-	/* validate the target name */
+	/* validate the target/clone name */
 	if (!zfs_validate_name(hdl, target, ZFS_TYPE_FILESYSTEM, B_TRUE))
 		return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
 
@@ -3443,42 +3575,6 @@
 }
 
 /*
- * Iterate over all dependents for a given dataset.  This includes both
- * hierarchical dependents (children) and data dependents (snapshots and
- * clones).  The bulk of the processing occurs in get_dependents() in
- * libzfs_graph.c.
- */
-int
-zfs_iter_dependents(zfs_handle_t *zhp, boolean_t allowrecursion,
-    zfs_iter_f func, void *data)
-{
-	char **dependents;
-	size_t count;
-	int i;
-	zfs_handle_t *child;
-	int ret = 0;
-
-	if (get_dependents(zhp->zfs_hdl, allowrecursion, zhp->zfs_name,
-	    &dependents, &count) != 0)
-		return (-1);
-
-	for (i = 0; i < count; i++) {
-		if ((child = make_dataset_handle(zhp->zfs_hdl,
-		    dependents[i])) == NULL)
-			continue;
-
-		if ((ret = func(child, data)) != 0)
-			break;
-	}
-
-	for (i = 0; i < count; i++)
-		free(dependents[i]);
-	free(dependents);
-
-	return (ret);
-}
-
-/*
  * Renames the given dataset.
  */
 int
@@ -3947,7 +4043,7 @@
 	int error;
 	zfs_useracct_t buf[100];
 
-	(void) strncpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
+	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
 
 	zc.zc_objset_type = type;
 	zc.zc_nvlist_dst = (uintptr_t)buf;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/cddl/contrib/opensolaris/lib/libzfs/common/libzfs_graph.c
--- a/head/cddl/contrib/opensolaris/lib/libzfs/common/libzfs_graph.c	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,653 +0,0 @@
-/*
- * CDDL HEADER START
- *
- * The contents of this file are subject to the terms of the
- * Common Development and Distribution License (the "License").
- * You may not use this file except in compliance with the License.
- *
- * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
- * or http://www.opensolaris.org/os/licensing.
- * See the License for the specific language governing permissions
- * and limitations under the License.
- *
- * When distributing Covered Code, include this CDDL HEADER in each
- * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
- * If applicable, add the following below this CDDL HEADER, with the
- * fields enclosed by brackets "[]" replaced with your own identifying
- * information: Portions Copyright [yyyy] [name of copyright owner]
- *
- * CDDL HEADER END
- */
-/*
- * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
- * Use is subject to license terms.
- */
-
-/*
- * Iterate over all children of the current object.  This includes the normal
- * dataset hierarchy, but also arbitrary hierarchies due to clones.  We want to
- * walk all datasets in the pool, and construct a directed graph of the form:
- *
- * 			home
- *                        |
- *                   +----+----+
- *                   |         |
- *                   v         v             ws
- *                  bar       baz             |
- *                             |              |
- *                             v              v
- *                          @yesterday ----> foo
- *
- * In order to construct this graph, we have to walk every dataset in the pool,
- * because the clone parent is stored as a property of the child, not the
- * parent.  The parent only keeps track of the number of clones.
- *
- * In the normal case (without clones) this would be rather expensive.  To avoid
- * unnecessary computation, we first try a walk of the subtree hierarchy
- * starting from the initial node.  At each dataset, we construct a node in the
- * graph and an edge leading from its parent.  If we don't see any snapshots
- * with a non-zero clone count, then we are finished.
- *
- * If we do find a cloned snapshot, then we finish the walk of the current
- * subtree, but indicate that we need to do a complete walk.  We then perform a
- * global walk of all datasets, avoiding the subtree we already processed.
- *
- * At the end of this, we'll end up with a directed graph of all relevant (and
- * possible some irrelevant) datasets in the system.  We need to both find our
- * limiting subgraph and determine a safe ordering in which to destroy the
- * datasets.  We do a topological ordering of our graph starting at our target
- * dataset, and then walk the results in reverse.
- *
- * It's possible for the graph to have cycles if, for example, the user renames
- * a clone to be the parent of its origin snapshot.  The user can request to
- * generate an error in this case, or ignore the cycle and continue.
- *
- * When removing datasets, we want to destroy the snapshots in chronological
- * order (because this is the most efficient method).  In order to accomplish
- * this, we store the creation transaction group with each vertex and keep each
- * vertex's edges sorted according to this value.  The topological sort will
- * automatically walk the snapshots in the correct order.
- */
-
-#include <assert.h>
-#include <libintl.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <strings.h>
-#include <unistd.h>
-
-#include <libzfs.h>
-
-#include "libzfs_impl.h"
-#include "zfs_namecheck.h"
-
-#define	MIN_EDGECOUNT	4
-
-/*
- * Vertex structure.  Indexed by dataset name, this structure maintains a list
- * of edges to other vertices.
- */
-struct zfs_edge;
-typedef struct zfs_vertex {
-	char			zv_dataset[ZFS_MAXNAMELEN];
-	struct zfs_vertex	*zv_next;
-	int			zv_visited;
-	uint64_t		zv_txg;
-	struct zfs_edge		**zv_edges;
-	int			zv_edgecount;
-	int			zv_edgealloc;
-} zfs_vertex_t;
-
-enum {
-	VISIT_SEEN = 1,
-	VISIT_SORT_PRE,
-	VISIT_SORT_POST
-};
-
-/*
- * Edge structure.  Simply maintains a pointer to the destination vertex.  There
- * is no need to store the source vertex, since we only use edges in the context
- * of the source vertex.
- */
-typedef struct zfs_edge {
-	zfs_vertex_t		*ze_dest;
-	struct zfs_edge		*ze_next;
-} zfs_edge_t;
-
-#define	ZFS_GRAPH_SIZE		1027	/* this could be dynamic some day */
-
-/*
- * Graph structure.  Vertices are maintained in a hash indexed by dataset name.
- */
-typedef struct zfs_graph {
-	zfs_vertex_t		**zg_hash;
-	size_t			zg_size;
-	size_t			zg_nvertex;
-	const char		*zg_root;
-	int			zg_clone_count;
-} zfs_graph_t;
-
-/*
- * Allocate a new edge pointing to the target vertex.
- */
-static zfs_edge_t *
-zfs_edge_create(libzfs_handle_t *hdl, zfs_vertex_t *dest)
-{
-	zfs_edge_t *zep = zfs_alloc(hdl, sizeof (zfs_edge_t));
-
-	if (zep == NULL)
-		return (NULL);
-
-	zep->ze_dest = dest;
-
-	return (zep);
-}
-
-/*
- * Destroy an edge.
- */
-static void
-zfs_edge_destroy(zfs_edge_t *zep)
-{
-	free(zep);
-}
-
-/*
- * Allocate a new vertex with the given name.
- */
-static zfs_vertex_t *
-zfs_vertex_create(libzfs_handle_t *hdl, const char *dataset)
-{
-	zfs_vertex_t *zvp = zfs_alloc(hdl, sizeof (zfs_vertex_t));
-
-	if (zvp == NULL)
-		return (NULL);
-
-	assert(strlen(dataset) < ZFS_MAXNAMELEN);
-
-	(void) strlcpy(zvp->zv_dataset, dataset, sizeof (zvp->zv_dataset));
-
-	if ((zvp->zv_edges = zfs_alloc(hdl,
-	    MIN_EDGECOUNT * sizeof (void *))) == NULL) {
-		free(zvp);
-		return (NULL);
-	}
-
-	zvp->zv_edgealloc = MIN_EDGECOUNT;
-
-	return (zvp);
-}
-
-/*
- * Destroy a vertex.  Frees up any associated edges.
- */
-static void
-zfs_vertex_destroy(zfs_vertex_t *zvp)
-{
-	int i;
-
-	for (i = 0; i < zvp->zv_edgecount; i++)
-		zfs_edge_destroy(zvp->zv_edges[i]);
-
-	free(zvp->zv_edges);
-	free(zvp);
-}
-
-/*
- * Given a vertex, add an edge to the destination vertex.
- */
-static int
-zfs_vertex_add_edge(libzfs_handle_t *hdl, zfs_vertex_t *zvp,
-    zfs_vertex_t *dest)
-{
-	zfs_edge_t *zep = zfs_edge_create(hdl, dest);
-
-	if (zep == NULL)
-		return (-1);
-
-	if (zvp->zv_edgecount == zvp->zv_edgealloc) {
-		void *ptr;
-
-		if ((ptr = zfs_realloc(hdl, zvp->zv_edges,
-		    zvp->zv_edgealloc * sizeof (void *),
-		    zvp->zv_edgealloc * 2 * sizeof (void *))) == NULL)
-			return (-1);
-
-		zvp->zv_edges = ptr;
-		zvp->zv_edgealloc *= 2;
-	}
-
-	zvp->zv_edges[zvp->zv_edgecount++] = zep;
-
-	return (0);
-}
-
-static int
-zfs_edge_compare(const void *a, const void *b)
-{
-	const zfs_edge_t *ea = *((zfs_edge_t **)a);
-	const zfs_edge_t *eb = *((zfs_edge_t **)b);
-
-	if (ea->ze_dest->zv_txg < eb->ze_dest->zv_txg)
-		return (-1);
-	if (ea->ze_dest->zv_txg > eb->ze_dest->zv_txg)
-		return (1);
-	return (0);
-}
-
-/*
- * Sort the given vertex edges according to the creation txg of each vertex.
- */
-static void
-zfs_vertex_sort_edges(zfs_vertex_t *zvp)
-{
-	if (zvp->zv_edgecount == 0)
-		return;
-
-	qsort(zvp->zv_edges, zvp->zv_edgecount, sizeof (void *),
-	    zfs_edge_compare);
-}
-
-/*
- * Construct a new graph object.  We allow the size to be specified as a
- * parameter so in the future we can size the hash according to the number of
- * datasets in the pool.
- */
-static zfs_graph_t *
-zfs_graph_create(libzfs_handle_t *hdl, const char *dataset, size_t size)
-{
-	zfs_graph_t *zgp = zfs_alloc(hdl, sizeof (zfs_graph_t));
-
-	if (zgp == NULL)
-		return (NULL);
-
-	zgp->zg_size = size;
-	if ((zgp->zg_hash = zfs_alloc(hdl,
-	    size * sizeof (zfs_vertex_t *))) == NULL) {
-		free(zgp);
-		return (NULL);
-	}
-
-	zgp->zg_root = dataset;
-	zgp->zg_clone_count = 0;
-
-	return (zgp);
-}
-
-/*
- * Destroy a graph object.  We have to iterate over all the hash chains,
- * destroying each vertex in the process.
- */
-static void
-zfs_graph_destroy(zfs_graph_t *zgp)
-{
-	int i;
-	zfs_vertex_t *current, *next;
-
-	for (i = 0; i < zgp->zg_size; i++) {
-		current = zgp->zg_hash[i];
-		while (current != NULL) {
-			next = current->zv_next;
-			zfs_vertex_destroy(current);
-			current = next;
-		}
-	}
-
-	free(zgp->zg_hash);
-	free(zgp);
-}
-
-/*
- * Graph hash function.  Classic bernstein k=33 hash function, taken from
- * usr/src/cmd/sgs/tools/common/strhash.c
- */
-static size_t
-zfs_graph_hash(zfs_graph_t *zgp, const char *str)
-{
-	size_t hash = 5381;
-	int c;
-
-	while ((c = *str++) != 0)
-		hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
-
-	return (hash % zgp->zg_size);
-}
-
-/*
- * Given a dataset name, finds the associated vertex, creating it if necessary.
- */
-static zfs_vertex_t *
-zfs_graph_lookup(libzfs_handle_t *hdl, zfs_graph_t *zgp, const char *dataset,
-    uint64_t txg)
-{
-	size_t idx = zfs_graph_hash(zgp, dataset);
-	zfs_vertex_t *zvp;
-
-	for (zvp = zgp->zg_hash[idx]; zvp != NULL; zvp = zvp->zv_next) {
-		if (strcmp(zvp->zv_dataset, dataset) == 0) {
-			if (zvp->zv_txg == 0)
-				zvp->zv_txg = txg;
-			return (zvp);
-		}
-	}
-
-	if ((zvp = zfs_vertex_create(hdl, dataset)) == NULL)
-		return (NULL);
-
-	zvp->zv_next = zgp->zg_hash[idx];
-	zvp->zv_txg = txg;
-	zgp->zg_hash[idx] = zvp;
-	zgp->zg_nvertex++;
-
-	return (zvp);
-}
-
-/*
- * Given two dataset names, create an edge between them.  For the source vertex,
- * mark 'zv_visited' to indicate that we have seen this vertex, and not simply
- * created it as a destination of another edge.  If 'dest' is NULL, then this
- * is an individual vertex (i.e. the starting vertex), so don't add an edge.
- */
-static int
-zfs_graph_add(libzfs_handle_t *hdl, zfs_graph_t *zgp, const char *source,
-    const char *dest, uint64_t txg)
-{
-	zfs_vertex_t *svp, *dvp;
-
-	if ((svp = zfs_graph_lookup(hdl, zgp, source, 0)) == NULL)
-		return (-1);
-	svp->zv_visited = VISIT_SEEN;
-	if (dest != NULL) {
-		dvp = zfs_graph_lookup(hdl, zgp, dest, txg);
-		if (dvp == NULL)
-			return (-1);
-		if (zfs_vertex_add_edge(hdl, svp, dvp) != 0)
-			return (-1);
-	}
-
-	return (0);
-}
-
-/*
- * Iterate over all children of the given dataset, adding any vertices
- * as necessary.  Returns -1 if there was an error, or 0 otherwise.
- * This is a simple recursive algorithm - the ZFS namespace typically
- * is very flat.  We manually invoke the necessary ioctl() calls to
- * avoid the overhead and additional semantics of zfs_open().
- */
-static int
-iterate_children(libzfs_handle_t *hdl, zfs_graph_t *zgp, const char *dataset)
-{
-	zfs_cmd_t zc = { 0 };
-	zfs_vertex_t *zvp;
-
-	/*
-	 * Look up the source vertex, and avoid it if we've seen it before.
-	 */
-	zvp = zfs_graph_lookup(hdl, zgp, dataset, 0);
-	if (zvp == NULL)
-		return (-1);
-	if (zvp->zv_visited == VISIT_SEEN)
-		return (0);
-
-	/*
-	 * Iterate over all children
-	 */
-	for ((void) strlcpy(zc.zc_name, dataset, sizeof (zc.zc_name));
-	    ioctl(hdl->libzfs_fd, ZFS_IOC_DATASET_LIST_NEXT, &zc) == 0;
-	    (void) strlcpy(zc.zc_name, dataset, sizeof (zc.zc_name))) {
-		/*
-		 * Get statistics for this dataset, to determine the type of the
-		 * dataset and clone statistics.  If this fails, the dataset has
-		 * since been removed, and we're pretty much screwed anyway.
-		 */
-		zc.zc_objset_stats.dds_origin[0] = '\0';
-		if (ioctl(hdl->libzfs_fd, ZFS_IOC_OBJSET_STATS, &zc) != 0)
-			continue;
-
-		if (zc.zc_objset_stats.dds_origin[0] != '\0') {
-			if (zfs_graph_add(hdl, zgp,
-			    zc.zc_objset_stats.dds_origin, zc.zc_name,
-			    zc.zc_objset_stats.dds_creation_txg) != 0)
-				return (-1);
-			/*
-			 * Count origins only if they are contained in the graph
-			 */
-			if (isa_child_of(zc.zc_objset_stats.dds_origin,
-			    zgp->zg_root))
-				zgp->zg_clone_count--;
-		}
-
-		/*
-		 * Add an edge between the parent and the child.
-		 */
-		if (zfs_graph_add(hdl, zgp, dataset, zc.zc_name,
-		    zc.zc_objset_stats.dds_creation_txg) != 0)
-			return (-1);
-
-		/*
-		 * Recursively visit child
-		 */
-		if (iterate_children(hdl, zgp, zc.zc_name))
-			return (-1);
-	}
-
-	/*
-	 * Now iterate over all snapshots.
-	 */
-	bzero(&zc, sizeof (zc));
-
-	for ((void) strlcpy(zc.zc_name, dataset, sizeof (zc.zc_name));
-	    ioctl(hdl->libzfs_fd, ZFS_IOC_SNAPSHOT_LIST_NEXT, &zc) == 0;
-	    (void) strlcpy(zc.zc_name, dataset, sizeof (zc.zc_name))) {
-
-		/*
-		 * Get statistics for this dataset, to determine the type of the
-		 * dataset and clone statistics.  If this fails, the dataset has
-		 * since been removed, and we're pretty much screwed anyway.
-		 */
-		if (ioctl(hdl->libzfs_fd, ZFS_IOC_OBJSET_STATS, &zc) != 0)
-			continue;
-
-		/*
-		 * Add an edge between the parent and the child.
-		 */
-		if (zfs_graph_add(hdl, zgp, dataset, zc.zc_name,
-		    zc.zc_objset_stats.dds_creation_txg) != 0)
-			return (-1);
-
-		zgp->zg_clone_count += zc.zc_objset_stats.dds_num_clones;
-	}
-
-	zvp->zv_visited = VISIT_SEEN;
-
-	return (0);
-}
-
-/*
- * Returns false if there are no snapshots with dependent clones in this
- * subtree or if all of those clones are also in this subtree.  Returns
- * true if there is an error or there are external dependents.
- */
-static boolean_t
-external_dependents(libzfs_handle_t *hdl, zfs_graph_t *zgp, const char *dataset)
-{
-	zfs_cmd_t zc = { 0 };
-
-	/*
-	 * Check whether this dataset is a clone or has clones since
-	 * iterate_children() only checks the children.
-	 */
-	(void) strlcpy(zc.zc_name, dataset, sizeof (zc.zc_name));
-	if (ioctl(hdl->libzfs_fd, ZFS_IOC_OBJSET_STATS, &zc) != 0)
-		return (B_TRUE);
-
-	if (zc.zc_objset_stats.dds_origin[0] != '\0') {
-		if (zfs_graph_add(hdl, zgp,
-		    zc.zc_objset_stats.dds_origin, zc.zc_name,
-		    zc.zc_objset_stats.dds_creation_txg) != 0)
-			return (B_TRUE);
-		if (isa_child_of(zc.zc_objset_stats.dds_origin, dataset))
-			zgp->zg_clone_count--;
-	}
-
-	if ((zc.zc_objset_stats.dds_num_clones) ||
-	    iterate_children(hdl, zgp, dataset))
-		return (B_TRUE);
-
-	return (zgp->zg_clone_count != 0);
-}
-
-/*
- * Construct a complete graph of all necessary vertices.  First, iterate over
- * only our object's children.  If no cloned snapshots are found, or all of
- * the cloned snapshots are in this subtree then return a graph of the subtree.
- * Otherwise, start at the root of the pool and iterate over all datasets.
- */
-static zfs_graph_t *
-construct_graph(libzfs_handle_t *hdl, const char *dataset)
-{
-	zfs_graph_t *zgp = zfs_graph_create(hdl, dataset, ZFS_GRAPH_SIZE);
-	int ret = 0;
-
-	if (zgp == NULL)
-		return (zgp);
-
-	if ((strchr(dataset, '/') == NULL) ||
-	    (external_dependents(hdl, zgp, dataset))) {
-		/*
-		 * Determine pool name and try again.
-		 */
-		int len = strcspn(dataset, "/@") + 1;
-		char *pool = zfs_alloc(hdl, len);
-
-		if (pool == NULL) {
-			zfs_graph_destroy(zgp);
-			return (NULL);
-		}
-		(void) strlcpy(pool, dataset, len);
-
-		if (iterate_children(hdl, zgp, pool) == -1 ||
-		    zfs_graph_add(hdl, zgp, pool, NULL, 0) != 0) {
-			free(pool);
-			zfs_graph_destroy(zgp);
-			return (NULL);
-		}
-		free(pool);
-	}
-
-	if (ret == -1 || zfs_graph_add(hdl, zgp, dataset, NULL, 0) != 0) {
-		zfs_graph_destroy(zgp);
-		return (NULL);
-	}
-
-	return (zgp);
-}
-
-/*
- * Given a graph, do a recursive topological sort into the given array.  This is
- * really just a depth first search, so that the deepest nodes appear first.
- * hijack the 'zv_visited' marker to avoid visiting the same vertex twice.
- */
-static int
-topo_sort(libzfs_handle_t *hdl, boolean_t allowrecursion, char **result,
-    size_t *idx, zfs_vertex_t *zgv)
-{
-	int i;
-
-	if (zgv->zv_visited == VISIT_SORT_PRE && !allowrecursion) {
-		/*
-		 * If we've already seen this vertex as part of our depth-first
-		 * search, then we have a cyclic dependency, and we must return
-		 * an error.
-		 */
-		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
-		    "recursive dependency at '%s'"),
-		    zgv->zv_dataset);
-		return (zfs_error(hdl, EZFS_RECURSIVE,
-		    dgettext(TEXT_DOMAIN,
-		    "cannot determine dependent datasets")));
-	} else if (zgv->zv_visited >= VISIT_SORT_PRE) {
-		/*
-		 * If we've already processed this as part of the topological
-		 * sort, then don't bother doing so again.
-		 */
-		return (0);
-	}
-
-	zgv->zv_visited = VISIT_SORT_PRE;
-
-	/* avoid doing a search if we don't have to */
-	zfs_vertex_sort_edges(zgv);
-	for (i = 0; i < zgv->zv_edgecount; i++) {
-		if (topo_sort(hdl, allowrecursion, result, idx,
-		    zgv->zv_edges[i]->ze_dest) != 0)
-			return (-1);
-	}
-
-	/* we may have visited this in the course of the above */
-	if (zgv->zv_visited == VISIT_SORT_POST)
-		return (0);
-
-	if ((result[*idx] = zfs_alloc(hdl,
-	    strlen(zgv->zv_dataset) + 1)) == NULL)
-		return (-1);
-
-	(void) strcpy(result[*idx], zgv->zv_dataset);
-	*idx += 1;
-	zgv->zv_visited = VISIT_SORT_POST;
-	return (0);
-}
-
-/*
- * The only public interface for this file.  Do the dirty work of constructing a
- * child list for the given object.  Construct the graph, do the toplogical
- * sort, and then return the array of strings to the caller.
- *
- * The 'allowrecursion' parameter controls behavior when cycles are found.  If
- * it is set, the the cycle is ignored and the results returned as if the cycle
- * did not exist.  If it is not set, then the routine will generate an error if
- * a cycle is found.
- */
-int
-get_dependents(libzfs_handle_t *hdl, boolean_t allowrecursion,
-    const char *dataset, char ***result, size_t *count)
-{
-	zfs_graph_t *zgp;
-	zfs_vertex_t *zvp;
-
-	if ((zgp = construct_graph(hdl, dataset)) == NULL)
-		return (-1);
-
-	if ((*result = zfs_alloc(hdl,
-	    zgp->zg_nvertex * sizeof (char *))) == NULL) {
-		zfs_graph_destroy(zgp);
-		return (-1);
-	}
-
-	if ((zvp = zfs_graph_lookup(hdl, zgp, dataset, 0)) == NULL) {
-		free(*result);
-		zfs_graph_destroy(zgp);
-		return (-1);
-	}
-
-	*count = 0;
-	if (topo_sort(hdl, allowrecursion, *result, count, zvp) != 0) {
-		free(*result);
-		zfs_graph_destroy(zgp);
-		return (-1);
-	}
-
-	/*
-	 * Get rid of the last entry, which is our starting vertex and not
-	 * strictly a dependent.
-	 */
-	assert(*count > 0);
-	free((*result)[*count - 1]);
-	(*count)--;
-
-	zfs_graph_destroy(zgp);
-
-	return (0);
-}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/cddl/contrib/opensolaris/lib/libzfs/common/libzfs_impl.h
--- a/head/cddl/contrib/opensolaris/lib/libzfs/common/libzfs_impl.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/cddl/contrib/opensolaris/lib/libzfs/common/libzfs_impl.h	Tue Dec 06 20:26:16 2011 +0200
@@ -23,6 +23,7 @@
  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
  * Copyright (c) 2011 Pawel Jakub Dawidek <pawel at dawidek.net>.
  * All rights reserved.
+ * Copyright (c) 2011 by Delphix. All rights reserved.
  */
 
 #ifndef	_LIBFS_IMPL_H
@@ -116,7 +117,7 @@
 	diskaddr_t zpool_start_block;
 };
 
-typedef  enum {
+typedef enum {
 	PROTO_NFS = 0,
 	PROTO_SMB = 1,
 	PROTO_END = 2
@@ -148,6 +149,7 @@
 
 int get_dependents(libzfs_handle_t *, boolean_t, const char *, char ***,
     size_t *);
+zfs_handle_t *make_dataset_handle_zc(libzfs_handle_t *, zfs_cmd_t *);
 
 
 int zprop_parse_value(libzfs_handle_t *, nvpair_t *, int, zfs_type_t,
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/cddl/contrib/opensolaris/lib/libzfs/common/libzfs_import.c
--- a/head/cddl/contrib/opensolaris/lib/libzfs/common/libzfs_import.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/cddl/contrib/opensolaris/lib/libzfs/common/libzfs_import.c	Tue Dec 06 20:26:16 2011 +0200
@@ -20,6 +20,8 @@
  */
 /*
  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright 2011 Nexenta Systems, Inc. All rights reserved.
+ * Copyright (c) 2011 by Delphix. All rights reserved.
  */
 
 /*
@@ -435,7 +437,7 @@
 	uint_t i, nspares, nl2cache;
 	boolean_t config_seen;
 	uint64_t best_txg;
-	char *name, *hostname;
+	char *name, *hostname, *comment;
 	uint64_t version, guid;
 	uint_t children = 0;
 	nvlist_t **child = NULL;
@@ -524,6 +526,7 @@
 				 *	version
 				 * 	pool guid
 				 * 	name
+				 *	comment (if available)
 				 * 	pool state
 				 *	hostid (if available)
 				 *	hostname (if available)
@@ -545,11 +548,24 @@
 				if (nvlist_add_string(config,
 				    ZPOOL_CONFIG_POOL_NAME, name) != 0)
 					goto nomem;
+
+				/*
+				 * COMMENT is optional, don't bail if it's not
+				 * there, instead, set it to NULL.
+				 */
+				if (nvlist_lookup_string(tmp,
+				    ZPOOL_CONFIG_COMMENT, &comment) != 0)
+					comment = NULL;
+				else if (nvlist_add_string(config,
+				    ZPOOL_CONFIG_COMMENT, comment) != 0)
+					goto nomem;
+
 				verify(nvlist_lookup_uint64(tmp,
 				    ZPOOL_CONFIG_POOL_STATE, &state) == 0);
 				if (nvlist_add_uint64(config,
 				    ZPOOL_CONFIG_POOL_STATE, state) != 0)
 					goto nomem;
+
 				hostid = 0;
 				if (nvlist_lookup_uint64(tmp,
 				    ZPOOL_CONFIG_HOSTID, &hostid) == 0) {
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/cddl/contrib/opensolaris/lib/libzfs/common/libzfs_iter.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/cddl/contrib/opensolaris/lib/libzfs/common/libzfs_iter.c	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,462 @@
+/*
+ * CDDL HEADER START
+ *
+ * The contents of this file are subject to the terms of the
+ * Common Development and Distribution License (the "License").
+ * You may not use this file except in compliance with the License.
+ *
+ * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
+ * or http://www.opensolaris.org/os/licensing.
+ * See the License for the specific language governing permissions
+ * and limitations under the License.
+ *
+ * When distributing Covered Code, include this CDDL HEADER in each
+ * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
+ * If applicable, add the following below this CDDL HEADER, with the
+ * fields enclosed by brackets "[]" replaced with your own identifying
+ * information: Portions Copyright [yyyy] [name of copyright owner]
+ *
+ * CDDL HEADER END
+ */
+
+/*
+ * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright 2010 Nexenta Systems, Inc. All rights reserved.
+ * Copyright (c) 2011 by Delphix. All rights reserved.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <strings.h>
+#include <unistd.h>
+#include <stddef.h>
+#include <libintl.h>
+#include <libzfs.h>
+
+#include "libzfs_impl.h"
+
+int
+zfs_iter_clones(zfs_handle_t *zhp, zfs_iter_f func, void *data)
+{
+	nvlist_t *nvl = zfs_get_clones_nvl(zhp);
+	nvpair_t *pair;
+
+	if (nvl == NULL)
+		return (0);
+
+	for (pair = nvlist_next_nvpair(nvl, NULL); pair != NULL;
+	    pair = nvlist_next_nvpair(nvl, pair)) {
+		zfs_handle_t *clone = zfs_open(zhp->zfs_hdl, nvpair_name(pair),
+		    ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
+		if (clone != NULL) {
+			int err = func(clone, data);
+			if (err != 0)
+				return (err);
+		}
+	}
+	return (0);
+}
+
+static int
+zfs_do_list_ioctl(zfs_handle_t *zhp, unsigned long arg, zfs_cmd_t *zc)
+{
+	int rc;
+	uint64_t	orig_cookie;
+
+	orig_cookie = zc->zc_cookie;
+top:
+	(void) strlcpy(zc->zc_name, zhp->zfs_name, sizeof (zc->zc_name));
+	rc = ioctl(zhp->zfs_hdl->libzfs_fd, arg, zc);
+
+	if (rc == -1) {
+		switch (errno) {
+		case ENOMEM:
+			/* expand nvlist memory and try again */
+			if (zcmd_expand_dst_nvlist(zhp->zfs_hdl, zc) != 0) {
+				zcmd_free_nvlists(zc);
+				return (-1);
+			}
+			zc->zc_cookie = orig_cookie;
+			goto top;
+		/*
+		 * An errno value of ESRCH indicates normal completion.
+		 * If ENOENT is returned, then the underlying dataset
+		 * has been removed since we obtained the handle.
+		 */
+		case ESRCH:
+		case ENOENT:
+			rc = 1;
+			break;
+		default:
+			rc = zfs_standard_error(zhp->zfs_hdl, errno,
+			    dgettext(TEXT_DOMAIN,
+			    "cannot iterate filesystems"));
+			break;
+		}
+	}
+	return (rc);
+}
+
+/*
+ * Iterate over all child filesystems
+ */
+int
+zfs_iter_filesystems(zfs_handle_t *zhp, zfs_iter_f func, void *data)
+{
+	zfs_cmd_t zc = { 0 };
+	zfs_handle_t *nzhp;
+	int ret;
+
+	if (zhp->zfs_type != ZFS_TYPE_FILESYSTEM)
+		return (0);
+
+	if (zcmd_alloc_dst_nvlist(zhp->zfs_hdl, &zc, 0) != 0)
+		return (-1);
+
+	while ((ret = zfs_do_list_ioctl(zhp, ZFS_IOC_DATASET_LIST_NEXT,
+	    &zc)) == 0) {
+		/*
+		 * Silently ignore errors, as the only plausible explanation is
+		 * that the pool has since been removed.
+		 */
+		if ((nzhp = make_dataset_handle_zc(zhp->zfs_hdl,
+		    &zc)) == NULL) {
+			continue;
+		}
+
+		if ((ret = func(nzhp, data)) != 0) {
+			zcmd_free_nvlists(&zc);
+			return (ret);
+		}
+	}
+	zcmd_free_nvlists(&zc);
+	return ((ret < 0) ? ret : 0);
+}
+
+/*
+ * Iterate over all snapshots
+ */
+int
+zfs_iter_snapshots(zfs_handle_t *zhp, zfs_iter_f func, void *data)
+{
+	zfs_cmd_t zc = { 0 };
+	zfs_handle_t *nzhp;
+	int ret;
+
+	if (zhp->zfs_type == ZFS_TYPE_SNAPSHOT)
+		return (0);
+
+	if (zcmd_alloc_dst_nvlist(zhp->zfs_hdl, &zc, 0) != 0)
+		return (-1);
+	while ((ret = zfs_do_list_ioctl(zhp, ZFS_IOC_SNAPSHOT_LIST_NEXT,
+	    &zc)) == 0) {
+
+		if ((nzhp = make_dataset_handle_zc(zhp->zfs_hdl,
+		    &zc)) == NULL) {
+			continue;
+		}
+
+		if ((ret = func(nzhp, data)) != 0) {
+			zcmd_free_nvlists(&zc);
+			return (ret);
+		}
+	}
+	zcmd_free_nvlists(&zc);
+	return ((ret < 0) ? ret : 0);
+}
+
+/*
+ * Routines for dealing with the sorted snapshot functionality
+ */
+typedef struct zfs_node {
+	zfs_handle_t	*zn_handle;
+	avl_node_t	zn_avlnode;
+} zfs_node_t;
+
+static int
+zfs_sort_snaps(zfs_handle_t *zhp, void *data)
+{
+	avl_tree_t *avl = data;
+	zfs_node_t *node;
+	zfs_node_t search;
+
+	search.zn_handle = zhp;
+	node = avl_find(avl, &search, NULL);
+	if (node) {
+		/*
+		 * If this snapshot was renamed while we were creating the
+		 * AVL tree, it's possible that we already inserted it under
+		 * its old name. Remove the old handle before adding the new
+		 * one.
+		 */
+		zfs_close(node->zn_handle);
+		avl_remove(avl, node);
+		free(node);
+	}
+
+	node = zfs_alloc(zhp->zfs_hdl, sizeof (zfs_node_t));
+	node->zn_handle = zhp;
+	avl_add(avl, node);
+
+	return (0);
+}
+
+static int
+zfs_snapshot_compare(const void *larg, const void *rarg)
+{
+	zfs_handle_t *l = ((zfs_node_t *)larg)->zn_handle;
+	zfs_handle_t *r = ((zfs_node_t *)rarg)->zn_handle;
+	uint64_t lcreate, rcreate;
+
+	/*
+	 * Sort them according to creation time.  We use the hidden
+	 * CREATETXG property to get an absolute ordering of snapshots.
+	 */
+	lcreate = zfs_prop_get_int(l, ZFS_PROP_CREATETXG);
+	rcreate = zfs_prop_get_int(r, ZFS_PROP_CREATETXG);
+
+	if (lcreate < rcreate)
+		return (-1);
+	else if (lcreate > rcreate)
+		return (+1);
+	else
+		return (0);
+}
+
+int
+zfs_iter_snapshots_sorted(zfs_handle_t *zhp, zfs_iter_f callback, void *data)
+{
+	int ret = 0;
+	zfs_node_t *node;
+	avl_tree_t avl;
+	void *cookie = NULL;
+
+	avl_create(&avl, zfs_snapshot_compare,
+	    sizeof (zfs_node_t), offsetof(zfs_node_t, zn_avlnode));
+
+	ret = zfs_iter_snapshots(zhp, zfs_sort_snaps, &avl);
+
+	for (node = avl_first(&avl); node != NULL; node = AVL_NEXT(&avl, node))
+		ret |= callback(node->zn_handle, data);
+
+	while ((node = avl_destroy_nodes(&avl, &cookie)) != NULL)
+		free(node);
+
+	avl_destroy(&avl);
+
+	return (ret);
+}
+
+typedef struct {
+	char *ssa_first;
+	char *ssa_last;
+	boolean_t ssa_seenfirst;
+	boolean_t ssa_seenlast;
+	zfs_iter_f ssa_func;
+	void *ssa_arg;
+} snapspec_arg_t;
+
+static int
+snapspec_cb(zfs_handle_t *zhp, void *arg) {
+	snapspec_arg_t *ssa = arg;
+	char *shortsnapname;
+	int err = 0;
+
+	if (ssa->ssa_seenlast)
+		return (0);
+	shortsnapname = zfs_strdup(zhp->zfs_hdl,
+	    strchr(zfs_get_name(zhp), '@') + 1);
+
+	if (!ssa->ssa_seenfirst && strcmp(shortsnapname, ssa->ssa_first) == 0)
+		ssa->ssa_seenfirst = B_TRUE;
+
+	if (ssa->ssa_seenfirst) {
+		err = ssa->ssa_func(zhp, ssa->ssa_arg);
+	} else {
+		zfs_close(zhp);
+	}
+
+	if (strcmp(shortsnapname, ssa->ssa_last) == 0)
+		ssa->ssa_seenlast = B_TRUE;
+	free(shortsnapname);
+
+	return (err);
+}
+
+/*
+ * spec is a string like "A,B%C,D"
+ *
+ * <snaps>, where <snaps> can be:
+ *      <snap>          (single snapshot)
+ *      <snap>%<snap>   (range of snapshots, inclusive)
+ *      %<snap>         (range of snapshots, starting with earliest)
+ *      <snap>%         (range of snapshots, ending with last)
+ *      %               (all snapshots)
+ *      <snaps>[,...]   (comma separated list of the above)
+ *
+ * If a snapshot can not be opened, continue trying to open the others, but
+ * return ENOENT at the end.
+ */
+int
+zfs_iter_snapspec(zfs_handle_t *fs_zhp, const char *spec_orig,
+    zfs_iter_f func, void *arg)
+{
+	char buf[ZFS_MAXNAMELEN];
+	char *comma_separated, *cp;
+	int err = 0;
+	int ret = 0;
+
+	(void) strlcpy(buf, spec_orig, sizeof (buf));
+	cp = buf;
+
+	while ((comma_separated = strsep(&cp, ",")) != NULL) {
+		char *pct = strchr(comma_separated, '%');
+		if (pct != NULL) {
+			snapspec_arg_t ssa = { 0 };
+			ssa.ssa_func = func;
+			ssa.ssa_arg = arg;
+
+			if (pct == comma_separated)
+				ssa.ssa_seenfirst = B_TRUE;
+			else
+				ssa.ssa_first = comma_separated;
+			*pct = '\0';
+			ssa.ssa_last = pct + 1;
+
+			/*
+			 * If there is a lastname specified, make sure it
+			 * exists.
+			 */
+			if (ssa.ssa_last[0] != '\0') {
+				char snapname[ZFS_MAXNAMELEN];
+				(void) snprintf(snapname, sizeof (snapname),
+				    "%s@%s", zfs_get_name(fs_zhp),
+				    ssa.ssa_last);
+				if (!zfs_dataset_exists(fs_zhp->zfs_hdl,
+				    snapname, ZFS_TYPE_SNAPSHOT)) {
+					ret = ENOENT;
+					continue;
+				}
+			}
+
+			err = zfs_iter_snapshots_sorted(fs_zhp,
+			    snapspec_cb, &ssa);
+			if (ret == 0)
+				ret = err;
+			if (ret == 0 && (!ssa.ssa_seenfirst ||
+			    (ssa.ssa_last[0] != '\0' && !ssa.ssa_seenlast))) {
+				ret = ENOENT;
+			}
+		} else {
+			char snapname[ZFS_MAXNAMELEN];
+			zfs_handle_t *snap_zhp;
+			(void) snprintf(snapname, sizeof (snapname), "%s@%s",
+			    zfs_get_name(fs_zhp), comma_separated);
+			snap_zhp = make_dataset_handle(fs_zhp->zfs_hdl,
+			    snapname);
+			if (snap_zhp == NULL) {
+				ret = ENOENT;
+				continue;
+			}
+			err = func(snap_zhp, arg);
+			if (ret == 0)
+				ret = err;
+		}
+	}
+
+	return (ret);
+}
+
+/*
+ * Iterate over all children, snapshots and filesystems
+ */
+int
+zfs_iter_children(zfs_handle_t *zhp, zfs_iter_f func, void *data)
+{
+	int ret;
+
+	if ((ret = zfs_iter_filesystems(zhp, func, data)) != 0)
+		return (ret);
+
+	return (zfs_iter_snapshots(zhp, func, data));
+}
+
+
+typedef struct iter_stack_frame {
+	struct iter_stack_frame *next;
+	zfs_handle_t *zhp;
+} iter_stack_frame_t;
+
+typedef struct iter_dependents_arg {
+	boolean_t first;
+	boolean_t allowrecursion;
+	iter_stack_frame_t *stack;
+	zfs_iter_f func;
+	void *data;
+} iter_dependents_arg_t;
+
+static int
+iter_dependents_cb(zfs_handle_t *zhp, void *arg)
+{
+	iter_dependents_arg_t *ida = arg;
+	int err;
+	boolean_t first = ida->first;
+	ida->first = B_FALSE;
+
+	if (zhp->zfs_type == ZFS_TYPE_SNAPSHOT) {
+		err = zfs_iter_clones(zhp, iter_dependents_cb, ida);
+	} else {
+		iter_stack_frame_t isf;
+		iter_stack_frame_t *f;
+
+		/*
+		 * check if there is a cycle by seeing if this fs is already
+		 * on the stack.
+		 */
+		for (f = ida->stack; f != NULL; f = f->next) {
+			if (f->zhp->zfs_dmustats.dds_guid ==
+			    zhp->zfs_dmustats.dds_guid) {
+				if (ida->allowrecursion) {
+					zfs_close(zhp);
+					return (0);
+				} else {
+					zfs_error_aux(zhp->zfs_hdl,
+					    dgettext(TEXT_DOMAIN,
+					    "recursive dependency at '%s'"),
+					    zfs_get_name(zhp));
+					err = zfs_error(zhp->zfs_hdl,
+					    EZFS_RECURSIVE,
+					    dgettext(TEXT_DOMAIN,
+					    "cannot determine dependent "
+					    "datasets"));
+					zfs_close(zhp);
+					return (err);
+				}
+			}
+		}
+
+		isf.zhp = zhp;
+		isf.next = ida->stack;
+		ida->stack = &isf;
+		err = zfs_iter_filesystems(zhp, iter_dependents_cb, ida);
+		if (err == 0)
+			err = zfs_iter_snapshots(zhp, iter_dependents_cb, ida);
+		ida->stack = isf.next;
+	}
+	if (!first && err == 0)
+		err = ida->func(zhp, ida->data);
+	return (err);
+}
+
+int
+zfs_iter_dependents(zfs_handle_t *zhp, boolean_t allowrecursion,
+    zfs_iter_f func, void *data)
+{
+	iter_dependents_arg_t ida;
+	ida.allowrecursion = allowrecursion;
+	ida.stack = NULL;
+	ida.func = func;
+	ida.data = data;
+	ida.first = B_TRUE;
+	return (iter_dependents_cb(zfs_handle_dup(zhp), &ida));
+}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/cddl/contrib/opensolaris/lib/libzfs/common/libzfs_pool.c
--- a/head/cddl/contrib/opensolaris/lib/libzfs/common/libzfs_pool.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/cddl/contrib/opensolaris/lib/libzfs/common/libzfs_pool.c	Tue Dec 06 20:26:16 2011 +0200
@@ -21,6 +21,8 @@
 
 /*
  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright 2011 Nexenta Systems, Inc. All rights reserved.
+ * Copyright (c) 2011 by Delphix. All rights reserved.
  */
 
 #include <sys/types.h>
@@ -261,6 +263,7 @@
 
 		case ZPOOL_PROP_ALTROOT:
 		case ZPOOL_PROP_CACHEFILE:
+		case ZPOOL_PROP_COMMENT:
 			if (zhp->zpool_props != NULL ||
 			    zpool_get_all_props(zhp) == 0) {
 				(void) strlcpy(buf,
@@ -412,7 +415,7 @@
 	zpool_prop_t prop;
 	char *strval;
 	uint64_t intval;
-	char *slash;
+	char *slash, *check;
 	struct stat64 statbuf;
 	zpool_handle_t *zhp;
 	nvlist_t *nvroot;
@@ -573,6 +576,26 @@
 			*slash = '/';
 			break;
 
+		case ZPOOL_PROP_COMMENT:
+			for (check = strval; *check != '\0'; check++) {
+				if (!isprint(*check)) {
+					zfs_error_aux(hdl,
+					    dgettext(TEXT_DOMAIN,
+					    "comment may only have printable "
+					    "characters"));
+					(void) zfs_error(hdl, EZFS_BADPROP,
+					    errbuf);
+					goto error;
+				}
+			}
+			if (strlen(strval) > ZPROP_MAX_COMMENT) {
+				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
+				    "comment must not exceed %d characters"),
+				    ZPROP_MAX_COMMENT);
+				(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
+				goto error;
+			}
+			break;
 		case ZPOOL_PROP_READONLY:
 			if (!flags.import) {
 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
@@ -3011,6 +3034,26 @@
 }
 
 /*
+ * Change the GUID for a pool.
+ */
+int
+zpool_reguid(zpool_handle_t *zhp)
+{
+	char msg[1024];
+	libzfs_handle_t *hdl = zhp->zpool_hdl;
+	zfs_cmd_t zc = { 0 };
+
+	(void) snprintf(msg, sizeof (msg),
+	    dgettext(TEXT_DOMAIN, "cannot reguid '%s'"), zhp->zpool_name);
+
+	(void) strlcpy(zc.zc_name, zhp->zpool_name, sizeof (zc.zc_name));
+	if (zfs_ioctl(hdl, ZFS_IOC_POOL_REGUID, &zc) == 0)
+		return (0);
+
+	return (zpool_standard_error(hdl, errno, msg));
+}
+
+/*
  * Convert from a devid string to a path.
  */
 static char *
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/cddl/contrib/opensolaris/lib/libzfs/common/libzfs_sendrecv.c
--- a/head/cddl/contrib/opensolaris/lib/libzfs/common/libzfs_sendrecv.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/cddl/contrib/opensolaris/lib/libzfs/common/libzfs_sendrecv.c	Tue Dec 06 20:26:16 2011 +0200
@@ -21,6 +21,7 @@
 
 /*
  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011 by Delphix. All rights reserved.
  */
 
 #include <assert.h>
@@ -53,7 +54,7 @@
 /* We need to use something for ENODATA. */
 #define	ENODATA	EIDRM
 
-static int zfs_receive_impl(libzfs_handle_t *, const char *, recvflags_t,
+static int zfs_receive_impl(libzfs_handle_t *, const char *, recvflags_t *,
     int, const char *, nvlist_t *, avl_tree_t *, char **, int, uint64_t *);
 
 static const zio_cksum_t zero_cksum = { 0 };
@@ -774,88 +775,6 @@
 }
 
 /*
- * Routines for dealing with the sorted snapshot functionality
- */
-typedef struct zfs_node {
-	zfs_handle_t	*zn_handle;
-	avl_node_t	zn_avlnode;
-} zfs_node_t;
-
-static int
-zfs_sort_snaps(zfs_handle_t *zhp, void *data)
-{
-	avl_tree_t *avl = data;
-	zfs_node_t *node;
-	zfs_node_t search;
-
-	search.zn_handle = zhp;
-	node = avl_find(avl, &search, NULL);
-	if (node) {
-		/*
-		 * If this snapshot was renamed while we were creating the
-		 * AVL tree, it's possible that we already inserted it under
-		 * its old name. Remove the old handle before adding the new
-		 * one.
-		 */
-		zfs_close(node->zn_handle);
-		avl_remove(avl, node);
-		free(node);
-	}
-
-	node = zfs_alloc(zhp->zfs_hdl, sizeof (zfs_node_t));
-	node->zn_handle = zhp;
-	avl_add(avl, node);
-
-	return (0);
-}
-
-static int
-zfs_snapshot_compare(const void *larg, const void *rarg)
-{
-	zfs_handle_t *l = ((zfs_node_t *)larg)->zn_handle;
-	zfs_handle_t *r = ((zfs_node_t *)rarg)->zn_handle;
-	uint64_t lcreate, rcreate;
-
-	/*
-	 * Sort them according to creation time.  We use the hidden
-	 * CREATETXG property to get an absolute ordering of snapshots.
-	 */
-	lcreate = zfs_prop_get_int(l, ZFS_PROP_CREATETXG);
-	rcreate = zfs_prop_get_int(r, ZFS_PROP_CREATETXG);
-
-	if (lcreate < rcreate)
-		return (-1);
-	else if (lcreate > rcreate)
-		return (+1);
-	else
-		return (0);
-}
-
-int
-zfs_iter_snapshots_sorted(zfs_handle_t *zhp, zfs_iter_f callback, void *data)
-{
-	int ret = 0;
-	zfs_node_t *node;
-	avl_tree_t avl;
-	void *cookie = NULL;
-
-	avl_create(&avl, zfs_snapshot_compare,
-	    sizeof (zfs_node_t), offsetof(zfs_node_t, zn_avlnode));
-
-	ret = zfs_iter_snapshots(zhp, zfs_sort_snaps, &avl);
-
-	for (node = avl_first(&avl); node != NULL; node = AVL_NEXT(&avl, node))
-		ret |= callback(node->zn_handle, data);
-
-	while ((node = avl_destroy_nodes(&avl, &cookie)) != NULL)
-		free(node);
-
-	avl_destroy(&avl);
-
-	return (ret);
-}
-
-/*
  * Routines specific to "zfs send"
  */
 typedef struct send_dump_data {
@@ -865,7 +784,7 @@
 	char prevsnap[ZFS_MAXNAMELEN];
 	uint64_t prevsnap_obj;
 	boolean_t seenfrom, seento, replicate, doall, fromorigin;
-	boolean_t verbose;
+	boolean_t verbose, dryrun, parsable;
 	int outfd;
 	boolean_t err;
 	nvlist_t *fss;
@@ -875,49 +794,31 @@
 	nvlist_t *debugnv;
 	char holdtag[ZFS_MAXNAMELEN];
 	int cleanup_fd;
+	uint64_t size;
 } send_dump_data_t;
 
-/*
- * Dumps a backup of the given snapshot (incremental from fromsnap if it's not
- * NULL) to the file descriptor specified by outfd.
- */
 static int
-dump_ioctl(zfs_handle_t *zhp, const char *fromsnap, uint64_t fromsnap_obj,
-    boolean_t fromorigin, int outfd, nvlist_t *debugnv)
+estimate_ioctl(zfs_handle_t *zhp, uint64_t fromsnap_obj,
+    boolean_t fromorigin, uint64_t *sizep)
 {
 	zfs_cmd_t zc = { 0 };
 	libzfs_handle_t *hdl = zhp->zfs_hdl;
-	nvlist_t *thisdbg;
 
 	assert(zhp->zfs_type == ZFS_TYPE_SNAPSHOT);
 	assert(fromsnap_obj == 0 || !fromorigin);
 
 	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
-	zc.zc_cookie = outfd;
 	zc.zc_obj = fromorigin;
 	zc.zc_sendobj = zfs_prop_get_int(zhp, ZFS_PROP_OBJSETID);
 	zc.zc_fromobj = fromsnap_obj;
-
-	VERIFY(0 == nvlist_alloc(&thisdbg, NV_UNIQUE_NAME, 0));
-	if (fromsnap && fromsnap[0] != '\0') {
-		VERIFY(0 == nvlist_add_string(thisdbg,
-		    "fromsnap", fromsnap));
-	}
-
-	if (ioctl(zhp->zfs_hdl->libzfs_fd, ZFS_IOC_SEND, &zc) != 0) {
+	zc.zc_guid = 1;  /* estimate flag */
+
+	if (zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_SEND, &zc) != 0) {
 		char errbuf[1024];
 		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
-		    "warning: cannot send '%s'"), zhp->zfs_name);
-
-		VERIFY(0 == nvlist_add_uint64(thisdbg, "error", errno));
-		if (debugnv) {
-			VERIFY(0 == nvlist_add_nvlist(debugnv,
-			    zhp->zfs_name, thisdbg));
-		}
-		nvlist_free(thisdbg);
+		    "warning: cannot estimate space for '%s'"), zhp->zfs_name);
 
 		switch (errno) {
-
 		case EXDEV:
 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
 			    "not an earlier snapshot from the same fs"));
@@ -950,6 +851,86 @@
 		}
 	}
 
+	*sizep = zc.zc_objset_type;
+
+	return (0);
+}
+
+/*
+ * Dumps a backup of the given snapshot (incremental from fromsnap if it's not
+ * NULL) to the file descriptor specified by outfd.
+ */
+static int
+dump_ioctl(zfs_handle_t *zhp, const char *fromsnap, uint64_t fromsnap_obj,
+    boolean_t fromorigin, int outfd, nvlist_t *debugnv)
+{
+	zfs_cmd_t zc = { 0 };
+	libzfs_handle_t *hdl = zhp->zfs_hdl;
+	nvlist_t *thisdbg;
+
+	assert(zhp->zfs_type == ZFS_TYPE_SNAPSHOT);
+	assert(fromsnap_obj == 0 || !fromorigin);
+
+	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
+	zc.zc_cookie = outfd;
+	zc.zc_obj = fromorigin;
+	zc.zc_sendobj = zfs_prop_get_int(zhp, ZFS_PROP_OBJSETID);
+	zc.zc_fromobj = fromsnap_obj;
+
+	VERIFY(0 == nvlist_alloc(&thisdbg, NV_UNIQUE_NAME, 0));
+	if (fromsnap && fromsnap[0] != '\0') {
+		VERIFY(0 == nvlist_add_string(thisdbg,
+		    "fromsnap", fromsnap));
+	}
+
+	if (zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_SEND, &zc) != 0) {
+		char errbuf[1024];
+		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
+		    "warning: cannot send '%s'"), zhp->zfs_name);
+
+		VERIFY(0 == nvlist_add_uint64(thisdbg, "error", errno));
+		if (debugnv) {
+			VERIFY(0 == nvlist_add_nvlist(debugnv,
+			    zhp->zfs_name, thisdbg));
+		}
+		nvlist_free(thisdbg);
+
+		switch (errno) {
+		case EXDEV:
+			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
+			    "not an earlier snapshot from the same fs"));
+			return (zfs_error(hdl, EZFS_CROSSTARGET, errbuf));
+
+		case ENOENT:
+			if (zfs_dataset_exists(hdl, zc.zc_name,
+			    ZFS_TYPE_SNAPSHOT)) {
+				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
+				    "incremental source (@%s) does not exist"),
+				    zc.zc_value);
+			}
+			return (zfs_error(hdl, EZFS_NOENT, errbuf));
+
+		case EDQUOT:
+		case EFBIG:
+		case EIO:
+		case ENOLINK:
+		case ENOSPC:
+#ifdef sun
+		case ENOSTR:
+#endif
+		case ENXIO:
+		case EPIPE:
+		case ERANGE:
+		case EFAULT:
+		case EROFS:
+			zfs_error_aux(hdl, strerror(errno));
+			return (zfs_error(hdl, EZFS_BADBACKUP, errbuf));
+
+		default:
+			return (zfs_standard_error(hdl, errno, errbuf));
+		}
+	}
+
 	if (debugnv)
 		VERIFY(0 == nvlist_add_nvlist(debugnv, zhp->zfs_name, thisdbg));
 	nvlist_free(thisdbg);
@@ -966,6 +947,9 @@
 
 	assert(zhp->zfs_type == ZFS_TYPE_SNAPSHOT);
 
+	if (sdd->dryrun)
+		return (0);
+
 	/*
 	 * zfs_send() only opens a cleanup_fd for sends that need it,
 	 * e.g. replication and doall.
@@ -999,7 +983,7 @@
 	send_dump_data_t *sdd = arg;
 	char *thissnap;
 	int err;
-	boolean_t isfromsnap, istosnap;
+	boolean_t isfromsnap, istosnap, fromorigin;
 	boolean_t exclude = B_FALSE;
 
 	thissnap = strchr(zhp->zfs_name, '@') + 1;
@@ -1076,15 +1060,47 @@
 		return (err);
 	}
 
-	/* send it */
+	fromorigin = sdd->prevsnap[0] == '\0' &&
+	    (sdd->fromorigin || sdd->replicate);
+
 	if (sdd->verbose) {
-		(void) fprintf(stderr, "sending from @%s to %s\n",
-		    sdd->prevsnap, zhp->zfs_name);
+		uint64_t size;
+		err = estimate_ioctl(zhp, sdd->prevsnap_obj,
+		    fromorigin, &size);
+
+		if (sdd->parsable) {
+			if (sdd->prevsnap[0] != '\0') {
+				(void) fprintf(stderr, "incremental\t%s\t%s",
+				    sdd->prevsnap, zhp->zfs_name);
+			} else {
+				(void) fprintf(stderr, "full\t%s",
+				    zhp->zfs_name);
+			}
+		} else {
+			(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
+			    "send from @%s to %s"),
+			    sdd->prevsnap, zhp->zfs_name);
+		}
+		if (err == 0) {
+			if (sdd->parsable) {
+				(void) fprintf(stderr, "\t%llu\n",
+				    (longlong_t)size);
+			} else {
+				char buf[16];
+				zfs_nicenum(size, buf, sizeof (buf));
+				(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
+				    " estimated size is %s\n"), buf);
+			}
+			sdd->size += size;
+		} else {
+			(void) fprintf(stderr, "\n");
+		}
 	}
 
-	err = dump_ioctl(zhp, sdd->prevsnap, sdd->prevsnap_obj,
-	    sdd->prevsnap[0] == '\0' && (sdd->fromorigin || sdd->replicate),
-	    sdd->outfd, sdd->debugnv);
+	if (!sdd->dryrun) {
+		err = dump_ioctl(zhp, sdd->prevsnap, sdd->prevsnap_obj,
+		    fromorigin, sdd->outfd, sdd->debugnv);
+	}
 
 	(void) strcpy(sdd->prevsnap, thissnap);
 	sdd->prevsnap_obj = zfs_prop_get_int(zhp, ZFS_PROP_OBJSETID);
@@ -1103,8 +1119,8 @@
 	(void) snprintf(zc.zc_name, sizeof (zc.zc_name), "%s@%s",
 	    zhp->zfs_name, sdd->tosnap);
 	if (ioctl(zhp->zfs_hdl->libzfs_fd, ZFS_IOC_OBJSET_STATS, &zc) != 0) {
-		(void) fprintf(stderr, "WARNING: "
-		    "could not send %s@%s: does not exist\n",
+		(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
+		    "WARNING: could not send %s@%s: does not exist\n"),
 		    zhp->zfs_name, sdd->tosnap);
 		sdd->err = B_TRUE;
 		return (0);
@@ -1133,23 +1149,24 @@
 
 	rv = zfs_iter_snapshots_sorted(zhp, dump_snapshot, arg);
 	if (!sdd->seenfrom) {
-		(void) fprintf(stderr,
+		(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
 		    "WARNING: could not send %s@%s:\n"
-		    "incremental source (%s@%s) does not exist\n",
+		    "incremental source (%s@%s) does not exist\n"),
 		    zhp->zfs_name, sdd->tosnap,
 		    zhp->zfs_name, sdd->fromsnap);
 		sdd->err = B_TRUE;
 	} else if (!sdd->seento) {
 		if (sdd->fromsnap) {
-			(void) fprintf(stderr,
+			(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
 			    "WARNING: could not send %s@%s:\n"
 			    "incremental source (%s@%s) "
-			    "is not earlier than it\n",
+			    "is not earlier than it\n"),
 			    zhp->zfs_name, sdd->tosnap,
 			    zhp->zfs_name, sdd->fromsnap);
 		} else {
-			(void) fprintf(stderr, "WARNING: "
-			    "could not send %s@%s: does not exist\n",
+			(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
+			    "WARNING: "
+			    "could not send %s@%s: does not exist\n"),
 			    zhp->zfs_name, sdd->tosnap);
 		}
 		sdd->err = B_TRUE;
@@ -1195,11 +1212,12 @@
 	needagain = progress = B_FALSE;
 	for (fspair = nvlist_next_nvpair(sdd->fss, NULL); fspair;
 	    fspair = nvlist_next_nvpair(sdd->fss, fspair)) {
-		nvlist_t *fslist;
+		nvlist_t *fslist, *parent_nv;
 		char *fsname;
 		zfs_handle_t *zhp;
 		int err;
 		uint64_t origin_guid = 0;
+		uint64_t parent_guid = 0;
 
 		VERIFY(nvpair_value_nvlist(fspair, &fslist) == 0);
 		if (nvlist_lookup_boolean(fslist, "sent") == 0)
@@ -1207,13 +1225,23 @@
 
 		VERIFY(nvlist_lookup_string(fslist, "name", &fsname) == 0);
 		(void) nvlist_lookup_uint64(fslist, "origin", &origin_guid);
+		(void) nvlist_lookup_uint64(fslist, "parentfromsnap",
+		    &parent_guid);
+
+		if (parent_guid != 0) {
+			parent_nv = fsavl_find(sdd->fsavl, parent_guid, NULL);
+			if (!nvlist_exists(parent_nv, "sent")) {
+				/* parent has not been sent; skip this one */
+				needagain = B_TRUE;
+				continue;
+			}
+		}
 
 		if (origin_guid != 0) {
 			nvlist_t *origin_nv = fsavl_find(sdd->fsavl,
 			    origin_guid, NULL);
 			if (origin_nv != NULL &&
-			    nvlist_lookup_boolean(origin_nv,
-			    "sent") == ENOENT) {
+			    !nvlist_exists(origin_nv, "sent")) {
 				/*
 				 * origin has not been sent yet;
 				 * skip this clone.
@@ -1237,6 +1265,16 @@
 		assert(progress);
 		goto again;
 	}
+
+	/* clean out the sent flags in case we reuse this fss */
+	for (fspair = nvlist_next_nvpair(sdd->fss, NULL); fspair;
+	    fspair = nvlist_next_nvpair(sdd->fss, fspair)) {
+		nvlist_t *fslist;
+
+		VERIFY(nvpair_value_nvlist(fspair, &fslist) == 0);
+		(void) nvlist_remove_all(fslist, "sent");
+	}
+
 	return (0);
 }
 
@@ -1258,12 +1296,12 @@
  */
 int
 zfs_send(zfs_handle_t *zhp, const char *fromsnap, const char *tosnap,
-    sendflags_t flags, int outfd, snapfilter_cb_t filter_func,
+    sendflags_t *flags, int outfd, snapfilter_cb_t filter_func,
     void *cb_arg, nvlist_t **debugnvp)
 {
 	char errbuf[1024];
 	send_dump_data_t sdd = { 0 };
-	int err;
+	int err = 0;
 	nvlist_t *fss = NULL;
 	avl_tree_t *fsavl = NULL;
 	static uint64_t holdseq;
@@ -1291,12 +1329,12 @@
 		}
 	}
 
-	if (zfs_spa_version(zhp, &spa_version) == 0 &&
+	if (!flags->dryrun && zfs_spa_version(zhp, &spa_version) == 0 &&
 	    spa_version >= SPA_VERSION_USERREFS &&
-	    (flags.doall || flags.replicate))
+	    (flags->doall || flags->replicate))
 		holdsnaps = B_TRUE;
 
-	if (flags.dedup) {
+	if (flags->dedup && !flags->dryrun) {
 		featureflags |= (DMU_BACKUP_FEATURE_DEDUP |
 		    DMU_BACKUP_FEATURE_DEDUPPROPS);
 		if (err = pipe(pipefd)) {
@@ -1316,13 +1354,13 @@
 		}
 	}
 
-	if (flags.replicate || flags.doall || flags.props) {
+	if (flags->replicate || flags->doall || flags->props) {
 		dmu_replay_record_t drr = { 0 };
 		char *packbuf = NULL;
 		size_t buflen = 0;
 		zio_cksum_t zc = { 0 };
 
-		if (flags.replicate || flags.props) {
+		if (flags->replicate || flags->props) {
 			nvlist_t *hdrnv;
 
 			VERIFY(0 == nvlist_alloc(&hdrnv, NV_UNIQUE_NAME, 0));
@@ -1331,13 +1369,13 @@
 				    "fromsnap", fromsnap));
 			}
 			VERIFY(0 == nvlist_add_string(hdrnv, "tosnap", tosnap));
-			if (!flags.replicate) {
+			if (!flags->replicate) {
 				VERIFY(0 == nvlist_add_boolean(hdrnv,
 				    "not_recursive"));
 			}
 
 			err = gather_nvlist(zhp->zfs_hdl, zhp->zfs_name,
-			    fromsnap, tosnap, flags.replicate, &fss, &fsavl);
+			    fromsnap, tosnap, flags->replicate, &fss, &fsavl);
 			if (err)
 				goto err_out;
 			VERIFY(0 == nvlist_add_nvlist(hdrnv, "fss", fss));
@@ -1354,33 +1392,34 @@
 			}
 		}
 
-		/* write first begin record */
-		drr.drr_type = DRR_BEGIN;
-		drr.drr_u.drr_begin.drr_magic = DMU_BACKUP_MAGIC;
-		DMU_SET_STREAM_HDRTYPE(drr.drr_u.drr_begin.drr_versioninfo,
-		    DMU_COMPOUNDSTREAM);
-		DMU_SET_FEATUREFLAGS(drr.drr_u.drr_begin.drr_versioninfo,
-		    featureflags);
-		(void) snprintf(drr.drr_u.drr_begin.drr_toname,
-		    sizeof (drr.drr_u.drr_begin.drr_toname),
-		    "%s@%s", zhp->zfs_name, tosnap);
-		drr.drr_payloadlen = buflen;
-		err = cksum_and_write(&drr, sizeof (drr), &zc, outfd);
-
-		/* write header nvlist */
-		if (err != -1 && packbuf != NULL) {
-			err = cksum_and_write(packbuf, buflen, &zc, outfd);
-		}
-		free(packbuf);
-		if (err == -1) {
-			fsavl_destroy(fsavl);
-			nvlist_free(fss);
-			err = errno;
-			goto stderr_out;
-		}
-
-		/* write end record */
-		if (err != -1) {
+		if (!flags->dryrun) {
+			/* write first begin record */
+			drr.drr_type = DRR_BEGIN;
+			drr.drr_u.drr_begin.drr_magic = DMU_BACKUP_MAGIC;
+			DMU_SET_STREAM_HDRTYPE(drr.drr_u.drr_begin.
+			    drr_versioninfo, DMU_COMPOUNDSTREAM);
+			DMU_SET_FEATUREFLAGS(drr.drr_u.drr_begin.
+			    drr_versioninfo, featureflags);
+			(void) snprintf(drr.drr_u.drr_begin.drr_toname,
+			    sizeof (drr.drr_u.drr_begin.drr_toname),
+			    "%s@%s", zhp->zfs_name, tosnap);
+			drr.drr_payloadlen = buflen;
+			err = cksum_and_write(&drr, sizeof (drr), &zc, outfd);
+
+			/* write header nvlist */
+			if (err != -1 && packbuf != NULL) {
+				err = cksum_and_write(packbuf, buflen, &zc,
+				    outfd);
+			}
+			free(packbuf);
+			if (err == -1) {
+				fsavl_destroy(fsavl);
+				nvlist_free(fss);
+				err = errno;
+				goto stderr_out;
+			}
+
+			/* write end record */
 			bzero(&drr, sizeof (drr));
 			drr.drr_type = DRR_END;
 			drr.drr_u.drr_end.drr_checksum = zc;
@@ -1391,22 +1430,26 @@
 				err = errno;
 				goto stderr_out;
 			}
+
+			err = 0;
 		}
 	}
 
 	/* dump each stream */
 	sdd.fromsnap = fromsnap;
 	sdd.tosnap = tosnap;
-	if (flags.dedup)
+	if (flags->dedup)
 		sdd.outfd = pipefd[0];
 	else
 		sdd.outfd = outfd;
-	sdd.replicate = flags.replicate;
-	sdd.doall = flags.doall;
-	sdd.fromorigin = flags.fromorigin;
+	sdd.replicate = flags->replicate;
+	sdd.doall = flags->doall;
+	sdd.fromorigin = flags->fromorigin;
 	sdd.fss = fss;
 	sdd.fsavl = fsavl;
-	sdd.verbose = flags.verbose;
+	sdd.verbose = flags->verbose;
+	sdd.parsable = flags->parsable;
+	sdd.dryrun = flags->dryrun;
 	sdd.filter_cb = filter_func;
 	sdd.filter_cb_arg = cb_arg;
 	if (debugnvp)
@@ -1423,11 +1466,31 @@
 	} else {
 		sdd.cleanup_fd = -1;
 	}
+	if (flags->verbose) {
+		/*
+		 * Do a verbose no-op dry run to get all the verbose output
+		 * before generating any data.  Then do a non-verbose real
+		 * run to generate the streams.
+		 */
+		sdd.dryrun = B_TRUE;
+		err = dump_filesystems(zhp, &sdd);
+		sdd.dryrun = flags->dryrun;
+		sdd.verbose = B_FALSE;
+		if (flags->parsable) {
+			(void) fprintf(stderr, "size\t%llu\n",
+			    (longlong_t)sdd.size);
+		} else {
+			char buf[16];
+			zfs_nicenum(sdd.size, buf, sizeof (buf));
+			(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
+			    "total estimated size is %s\n"), buf);
+		}
+	}
 	err = dump_filesystems(zhp, &sdd);
 	fsavl_destroy(fsavl);
 	nvlist_free(fss);
 
-	if (flags.dedup) {
+	if (flags->dedup) {
 		(void) close(pipefd[0]);
 		(void) pthread_join(tid, NULL);
 	}
@@ -1437,7 +1500,8 @@
 		sdd.cleanup_fd = -1;
 	}
 
-	if (flags.replicate || flags.doall || flags.props) {
+	if (!flags->dryrun && (flags->replicate || flags->doall ||
+	    flags->props)) {
 		/*
 		 * write final end record.  NB: want to do this even if
 		 * there was some error, because it might not be totally
@@ -1458,7 +1522,7 @@
 err_out:
 	if (sdd.cleanup_fd != -1)
 		VERIFY(0 == close(sdd.cleanup_fd));
-	if (flags.dedup) {
+	if (flags->dedup) {
 		(void) pthread_cancel(tid);
 		(void) pthread_join(tid, NULL);
 		(void) close(pipefd[0]);
@@ -1529,7 +1593,7 @@
 
 static int
 recv_rename(libzfs_handle_t *hdl, const char *name, const char *tryname,
-    int baselen, char *newname, recvflags_t flags)
+    int baselen, char *newname, recvflags_t *flags)
 {
 	static int seq;
 	zfs_cmd_t zc = { 0 };
@@ -1541,7 +1605,7 @@
 	if (zhp == NULL)
 		return (-1);
 	clp = changelist_gather(zhp, ZFS_PROP_NAME, 0,
-	    flags.force ? MS_FORCE : 0);
+	    flags->force ? MS_FORCE : 0);
 	zfs_close(zhp);
 	if (clp == NULL)
 		return (-1);
@@ -1557,7 +1621,7 @@
 
 		(void) strlcpy(zc.zc_value, tryname, sizeof (zc.zc_value));
 
-		if (flags.verbose) {
+		if (flags->verbose) {
 			(void) printf("attempting rename %s to %s\n",
 			    zc.zc_name, zc.zc_value);
 		}
@@ -1576,19 +1640,19 @@
 		    "recv-%u-%u", getpid(), seq);
 		(void) strlcpy(zc.zc_value, newname, sizeof (zc.zc_value));
 
-		if (flags.verbose) {
+		if (flags->verbose) {
 			(void) printf("failed - trying rename %s to %s\n",
 			    zc.zc_name, zc.zc_value);
 		}
 		err = ioctl(hdl->libzfs_fd, ZFS_IOC_RENAME, &zc);
 		if (err == 0)
 			changelist_rename(clp, name, newname);
-		if (err && flags.verbose) {
+		if (err && flags->verbose) {
 			(void) printf("failed (%u) - "
 			    "will try again on next pass\n", errno);
 		}
 		err = EAGAIN;
-	} else if (flags.verbose) {
+	} else if (flags->verbose) {
 		if (err == 0)
 			(void) printf("success\n");
 		else
@@ -1603,7 +1667,7 @@
 
 static int
 recv_destroy(libzfs_handle_t *hdl, const char *name, int baselen,
-    char *newname, recvflags_t flags)
+    char *newname, recvflags_t *flags)
 {
 	zfs_cmd_t zc = { 0 };
 	int err = 0;
@@ -1616,7 +1680,7 @@
 	if (zhp == NULL)
 		return (-1);
 	clp = changelist_gather(zhp, ZFS_PROP_NAME, 0,
-	    flags.force ? MS_FORCE : 0);
+	    flags->force ? MS_FORCE : 0);
 	if (zfs_get_type(zhp) == ZFS_TYPE_SNAPSHOT &&
 	    zfs_spa_version(zhp, &spa_version) == 0 &&
 	    spa_version >= SPA_VERSION_USERREFS)
@@ -1632,11 +1696,11 @@
 	zc.zc_defer_destroy = defer;
 	(void) strlcpy(zc.zc_name, name, sizeof (zc.zc_name));
 
-	if (flags.verbose)
+	if (flags->verbose)
 		(void) printf("attempting destroy %s\n", zc.zc_name);
 	err = ioctl(hdl->libzfs_fd, ZFS_IOC_DESTROY, &zc);
 	if (err == 0) {
-		if (flags.verbose)
+		if (flags->verbose)
 			(void) printf("success\n");
 		changelist_remove(clp, zc.zc_name);
 	}
@@ -1659,6 +1723,7 @@
 typedef struct guid_to_name_data {
 	uint64_t guid;
 	char *name;
+	char *skip;
 } guid_to_name_data_t;
 
 static int
@@ -1667,21 +1732,35 @@
 	guid_to_name_data_t *gtnd = arg;
 	int err;
 
+	if (gtnd->skip != NULL &&
+	    strcmp(zhp->zfs_name, gtnd->skip) == 0) {
+		return (0);
+	}
+
 	if (zhp->zfs_dmustats.dds_guid == gtnd->guid) {
 		(void) strcpy(gtnd->name, zhp->zfs_name);
 		zfs_close(zhp);
 		return (EEXIST);
 	}
+
 	err = zfs_iter_children(zhp, guid_to_name_cb, gtnd);
 	zfs_close(zhp);
 	return (err);
 }
 
+/*
+ * Attempt to find the local dataset associated with this guid.  In the case of
+ * multiple matches, we attempt to find the "best" match by searching
+ * progressively larger portions of the hierarchy.  This allows one to send a
+ * tree of datasets individually and guarantee that we will find the source
+ * guid within that hierarchy, even if there are multiple matches elsewhere.
+ */
 static int
 guid_to_name(libzfs_handle_t *hdl, const char *parent, uint64_t guid,
     char *name)
 {
 	/* exhaustive search all local snapshots */
+	char pname[ZFS_MAXNAMELEN];
 	guid_to_name_data_t gtnd;
 	int err = 0;
 	zfs_handle_t *zhp;
@@ -1689,35 +1768,42 @@
 
 	gtnd.guid = guid;
 	gtnd.name = name;
-
-	if (strchr(parent, '@') == NULL) {
-		zhp = make_dataset_handle(hdl, parent);
-		if (zhp != NULL) {
-			err = zfs_iter_children(zhp, guid_to_name_cb, &gtnd);
-			zfs_close(zhp);
-			if (err == EEXIST)
-				return (0);
-		}
-	}
-
-	cp = strchr(parent, '/');
-	if (cp)
+	gtnd.skip = NULL;
+
+	(void) strlcpy(pname, parent, sizeof (pname));
+
+	/*
+	 * Search progressively larger portions of the hierarchy.  This will
+	 * select the "most local" version of the origin snapshot in the case
+	 * that there are multiple matching snapshots in the system.
+	 */
+	while ((cp = strrchr(pname, '/')) != NULL) {
+
+		/* Chop off the last component and open the parent */
 		*cp = '\0';
-	zhp = make_dataset_handle(hdl, parent);
-	if (cp)
-		*cp = '/';
-
-	if (zhp) {
+		zhp = make_dataset_handle(hdl, pname);
+
+		if (zhp == NULL)
+			continue;
+
 		err = zfs_iter_children(zhp, guid_to_name_cb, &gtnd);
 		zfs_close(zhp);
+		if (err == EEXIST)
+			return (0);
+
+		/*
+		 * Remember the dataset that we already searched, so we
+		 * skip it next time through.
+		 */
+		gtnd.skip = pname;
 	}
 
-	return (err == EEXIST ? 0 : ENOENT);
-
+	return (ENOENT);
 }
 
 /*
- * Return true if dataset guid1 is created before guid2.
+ * Return +1 if guid1 is before guid2, 0 if they are the same, and -1 if
+ * guid1 is after guid2.
  */
 static int
 created_before(libzfs_handle_t *hdl, avl_tree_t *avl,
@@ -1727,7 +1813,8 @@
 	char *fsname, *snapname;
 	char buf[ZFS_MAXNAMELEN];
 	int rv;
-	zfs_node_t zn1, zn2;
+	zfs_handle_t *guid1hdl, *guid2hdl;
+	uint64_t create1, create2;
 
 	if (guid2 == 0)
 		return (0);
@@ -1737,30 +1824,38 @@
 	nvfs = fsavl_find(avl, guid1, &snapname);
 	VERIFY(0 == nvlist_lookup_string(nvfs, "name", &fsname));
 	(void) snprintf(buf, sizeof (buf), "%s@%s", fsname, snapname);
-	zn1.zn_handle = zfs_open(hdl, buf, ZFS_TYPE_SNAPSHOT);
-	if (zn1.zn_handle == NULL)
+	guid1hdl = zfs_open(hdl, buf, ZFS_TYPE_SNAPSHOT);
+	if (guid1hdl == NULL)
 		return (-1);
 
 	nvfs = fsavl_find(avl, guid2, &snapname);
 	VERIFY(0 == nvlist_lookup_string(nvfs, "name", &fsname));
 	(void) snprintf(buf, sizeof (buf), "%s@%s", fsname, snapname);
-	zn2.zn_handle = zfs_open(hdl, buf, ZFS_TYPE_SNAPSHOT);
-	if (zn2.zn_handle == NULL) {
-		zfs_close(zn2.zn_handle);
+	guid2hdl = zfs_open(hdl, buf, ZFS_TYPE_SNAPSHOT);
+	if (guid2hdl == NULL) {
+		zfs_close(guid1hdl);
 		return (-1);
 	}
 
-	rv = (zfs_snapshot_compare(&zn1, &zn2) == -1);
-
-	zfs_close(zn1.zn_handle);
-	zfs_close(zn2.zn_handle);
+	create1 = zfs_prop_get_int(guid1hdl, ZFS_PROP_CREATETXG);
+	create2 = zfs_prop_get_int(guid2hdl, ZFS_PROP_CREATETXG);
+
+	if (create1 < create2)
+		rv = -1;
+	else if (create1 > create2)
+		rv = +1;
+	else
+		rv = 0;
+
+	zfs_close(guid1hdl);
+	zfs_close(guid2hdl);
 
 	return (rv);
 }
 
 static int
 recv_incremental_replication(libzfs_handle_t *hdl, const char *tofs,
-    recvflags_t flags, nvlist_t *stream_nv, avl_tree_t *stream_avl,
+    recvflags_t *flags, nvlist_t *stream_nv, avl_tree_t *stream_avl,
     nvlist_t *renamed)
 {
 	nvlist_t *local_nv;
@@ -1777,7 +1872,7 @@
 	recursive = (nvlist_lookup_boolean(stream_nv, "not_recursive") ==
 	    ENOENT);
 
-	if (flags.dryrun)
+	if (flags->dryrun)
 		return (0);
 
 again:
@@ -1837,7 +1932,7 @@
 				nvlist_t *origin_nvfs;
 				char *origin_fsname;
 
-				if (flags.verbose)
+				if (flags->verbose)
 					(void) printf("promoting %s\n", fsname);
 
 				origin_nvfs = fsavl_find(local_avl, originguid,
@@ -1885,7 +1980,7 @@
 			if (found == NULL) {
 				char name[ZFS_MAXNAMELEN];
 
-				if (!flags.force)
+				if (!flags->force)
 					continue;
 
 				(void) snprintf(name, sizeof (name), "%s@%s",
@@ -1943,7 +2038,7 @@
 
 		/* check for delete */
 		if (stream_nvfs == NULL) {
-			if (!flags.force)
+			if (!flags->force)
 				continue;
 
 			error = recv_destroy(hdl, fsname, strlen(tofs)+1,
@@ -1956,7 +2051,7 @@
 		}
 
 		if (fromguid == 0) {
-			if (flags.verbose) {
+			if (flags->verbose) {
 				(void) printf("local fs %s does not have "
 				    "fromsnap (%s in stream); must have "
 				    "been deleted locally; ignoring\n",
@@ -1981,7 +2076,7 @@
 		if ((stream_parent_fromsnap_guid != 0 &&
 		    parent_fromsnap_guid != 0 &&
 		    stream_parent_fromsnap_guid != parent_fromsnap_guid) ||
-		    ((flags.isprefix || strcmp(tofs, fsname) != 0) &&
+		    ((flags->isprefix || strcmp(tofs, fsname) != 0) &&
 		    (s1 != NULL) && (s2 != NULL) && strcmp(s1, s2) != 0)) {
 			nvlist_t *parent;
 			char tryname[ZFS_MAXNAMELEN];
@@ -2004,7 +2099,7 @@
 				    "%s%s", pname, strrchr(stream_fsname, '/'));
 			} else {
 				tryname[0] = '\0';
-				if (flags.verbose) {
+				if (flags->verbose) {
 					(void) printf("local fs %s new parent "
 					    "not found\n", fsname);
 				}
@@ -2032,7 +2127,7 @@
 
 	if (needagain && progress) {
 		/* do another pass to fix up temporary names */
-		if (flags.verbose)
+		if (flags->verbose)
 			(void) printf("another pass:\n");
 		goto again;
 	}
@@ -2042,7 +2137,7 @@
 
 static int
 zfs_receive_package(libzfs_handle_t *hdl, int fd, const char *destname,
-    recvflags_t flags, dmu_replay_record_t *drr, zio_cksum_t *zc,
+    recvflags_t *flags, dmu_replay_record_t *drr, zio_cksum_t *zc,
     char **top_zfs, int cleanup_fd, uint64_t *action_handlep)
 {
 	nvlist_t *stream_nv = NULL;
@@ -2071,7 +2166,7 @@
 	 */
 	if (drr->drr_payloadlen != 0) {
 		error = recv_read_nvlist(hdl, fd, drr->drr_payloadlen,
-		    &stream_nv, flags.byteswap, zc);
+		    &stream_nv, flags->byteswap, zc);
 		if (error) {
 			error = zfs_error(hdl, EZFS_BADSTREAM, errbuf);
 			goto out;
@@ -2092,9 +2187,9 @@
 	 * Read in the end record and verify checksum.
 	 */
 	if (0 != (error = recv_read(hdl, fd, &drre, sizeof (drre),
-	    flags.byteswap, NULL)))
+	    flags->byteswap, NULL)))
 		goto out;
-	if (flags.byteswap) {
+	if (flags->byteswap) {
 		drre.drr_type = BSWAP_32(drre.drr_type);
 		drre.drr_u.drr_end.drr_checksum.zc_word[0] =
 		    BSWAP_64(drre.drr_u.drr_end.drr_checksum.zc_word[0]);
@@ -2135,11 +2230,11 @@
 			nvpair_t *pair = NULL;
 
 			(void) strlcpy(tofs, destname, ZFS_MAXNAMELEN);
-			if (flags.isprefix) {
+			if (flags->isprefix) {
 				struct drr_begin *drrb = &drr->drr_u.drr_begin;
 				int i;
 
-				if (flags.istail) {
+				if (flags->istail) {
 					cp = strrchr(drrb->drr_toname, '/');
 					if (cp == NULL) {
 						(void) strlcat(tofs, "/",
@@ -2157,7 +2252,7 @@
 				*strchr(tofs, '@') = '\0';
 			}
 
-			if (recursive && !flags.dryrun && !flags.nomount) {
+			if (recursive && !flags->dryrun && !flags->nomount) {
 				VERIFY(0 == nvlist_alloc(&renamed,
 				    NV_UNIQUE_NAME, 0));
 			}
@@ -2331,7 +2426,7 @@
  */
 static int
 zfs_receive_one(libzfs_handle_t *hdl, int infd, const char *tosnap,
-    recvflags_t flags, dmu_replay_record_t *drr,
+    recvflags_t *flags, dmu_replay_record_t *drr,
     dmu_replay_record_t *drr_noswap, const char *sendfs,
     nvlist_t *stream_nv, avl_tree_t *stream_avl, char **top_zfs, int cleanup_fd,
     uint64_t *action_handlep)
@@ -2373,7 +2468,7 @@
 		if (err)
 			VERIFY(0 == nvlist_alloc(&props, NV_UNIQUE_NAME, 0));
 
-		if (flags.canmountoff) {
+		if (flags->canmountoff) {
 			VERIFY(0 == nvlist_add_uint64(props,
 			    zfs_prop_to_name(ZFS_PROP_CANMOUNT), 0));
 		}
@@ -2400,7 +2495,7 @@
 	 * If they specified a snapshot, chop the entire name stored in
 	 * the stream.
 	 */
-	if (flags.istail) {
+	if (flags->istail) {
 		/*
 		 * A filesystem was specified with -e. We want to tack on only
 		 * the tail of the sent snapshot path.
@@ -2426,7 +2521,7 @@
 		} else {
 			chopprefix = drrb->drr_toname + (chopprefix - sendfs);
 		}
-	} else if (flags.isprefix) {
+	} else if (flags->isprefix) {
 		/*
 		 * A filesystem was specified with -d. We want to tack on
 		 * everything but the first element of the sent snapshot path
@@ -2480,7 +2575,7 @@
 	 * Determine the name of the origin snapshot, store in zc_string.
 	 */
 	if (drrb->drr_flags & DRR_FLAG_CLONE) {
-		if (guid_to_name(hdl, tosnap,
+		if (guid_to_name(hdl, zc.zc_value,
 		    drrb->drr_fromguid, zc.zc_string) != 0) {
 			zcmd_free_nvlists(&zc);
 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
@@ -2488,7 +2583,7 @@
 			    zc.zc_value);
 			return (zfs_error(hdl, EZFS_NOENT, errbuf));
 		}
-		if (flags.verbose)
+		if (flags->verbose)
 			(void) printf("found clone origin %s\n", zc.zc_string);
 	}
 
@@ -2511,7 +2606,7 @@
 		    !zfs_dataset_exists(hdl, zc.zc_name, ZFS_TYPE_DATASET)) {
 			char suffix[ZFS_MAXNAMELEN];
 			(void) strcpy(suffix, strrchr(zc.zc_value, '/'));
-			if (guid_to_name(hdl, tosnap, parent_snapguid,
+			if (guid_to_name(hdl, zc.zc_name, parent_snapguid,
 			    zc.zc_value) == 0) {
 				*strchr(zc.zc_value, '@') = '\0';
 				(void) strcat(zc.zc_value, suffix);
@@ -2533,12 +2628,12 @@
 		 * topmost path in the stream, then if the fs does not exist we
 		 * should look no further.
 		 */
-		if ((flags.isprefix || (*(chopprefix = drrb->drr_toname +
+		if ((flags->isprefix || (*(chopprefix = drrb->drr_toname +
 		    strlen(sendfs)) != '\0' && *chopprefix != '@')) &&
 		    !zfs_dataset_exists(hdl, zc.zc_name, ZFS_TYPE_DATASET)) {
 			char snap[ZFS_MAXNAMELEN];
 			(void) strcpy(snap, strchr(zc.zc_value, '@'));
-			if (guid_to_name(hdl, tosnap, drrb->drr_fromguid,
+			if (guid_to_name(hdl, zc.zc_name, drrb->drr_fromguid,
 			    zc.zc_value) == 0) {
 				*strchr(zc.zc_value, '@') = '\0';
 				(void) strcat(zc.zc_value, snap);
@@ -2560,7 +2655,7 @@
 		 * snapshots).
 		 */
 		if (stream_wantsnewfs) {
-			if (!flags.force) {
+			if (!flags->force) {
 				zcmd_free_nvlists(&zc);
 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
 				    "destination '%s' exists\n"
@@ -2596,7 +2691,7 @@
 			return (zfs_error(hdl, EZFS_EXISTS, errbuf));
 		}
 
-		if (!flags.dryrun && zhp->zfs_type == ZFS_TYPE_FILESYSTEM &&
+		if (!flags->dryrun && zhp->zfs_type == ZFS_TYPE_FILESYSTEM &&
 		    stream_wantsnewfs) {
 			/* We can't do online recv in this case */
 			clp = changelist_gather(zhp, ZFS_PROP_NAME, 0, 0);
@@ -2635,7 +2730,7 @@
 		 */
 		*cp = '\0';
 
-		if (flags.isprefix && !flags.istail && !flags.dryrun &&
+		if (flags->isprefix && !flags->istail && !flags->dryrun &&
 		    create_parents(hdl, zc.zc_value, strlen(tosnap)) != 0) {
 			zcmd_free_nvlists(&zc);
 			return (zfs_error(hdl, EZFS_BADRESTORE, errbuf));
@@ -2646,18 +2741,18 @@
 
 	zc.zc_begin_record = drr_noswap->drr_u.drr_begin;
 	zc.zc_cookie = infd;
-	zc.zc_guid = flags.force;
-	if (flags.verbose) {
+	zc.zc_guid = flags->force;
+	if (flags->verbose) {
 		(void) printf("%s %s stream of %s into %s\n",
-		    flags.dryrun ? "would receive" : "receiving",
+		    flags->dryrun ? "would receive" : "receiving",
 		    drrb->drr_fromguid ? "incremental" : "full",
 		    drrb->drr_toname, zc.zc_value);
 		(void) fflush(stdout);
 	}
 
-	if (flags.dryrun) {
+	if (flags->dryrun) {
 		zcmd_free_nvlists(&zc);
-		return (recv_skip(hdl, infd, flags.byteswap));
+		return (recv_skip(hdl, infd, flags->byteswap));
 	}
 
 	zc.zc_nvlist_dst = (uint64_t)(uintptr_t)prop_errbuf;
@@ -2738,12 +2833,12 @@
 			nvlist_free(local_nv);
 
 			if (fs != NULL) {
-				if (flags.verbose) {
+				if (flags->verbose) {
 					(void) printf("snap %s already exists; "
 					    "ignoring\n", zc.zc_value);
 				}
 				err = ioctl_err = recv_skip(hdl, infd,
-				    flags.byteswap);
+				    flags->byteswap);
 			}
 		}
 		*cp = '@';
@@ -2795,7 +2890,7 @@
 		case EDQUOT:
 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
 			    "destination %s space quota exceeded"), zc.zc_name);
-			(void) zfs_error(hdl, EZFS_BADRESTORE, errbuf);
+			(void) zfs_error(hdl, EZFS_NOSPC, errbuf);
 			break;
 		default:
 			(void) zfs_standard_error(hdl, ioctl_errno, errbuf);
@@ -2853,7 +2948,7 @@
 
 	*action_handlep = zc.zc_action_handle;
 
-	if (flags.verbose) {
+	if (flags->verbose) {
 		char buf1[64];
 		char buf2[64];
 		uint64_t bytes = zc.zc_cookie;
@@ -2871,7 +2966,7 @@
 }
 
 static int
-zfs_receive_impl(libzfs_handle_t *hdl, const char *tosnap, recvflags_t flags,
+zfs_receive_impl(libzfs_handle_t *hdl, const char *tosnap, recvflags_t *flags,
     int infd, const char *sendfs, nvlist_t *stream_nv, avl_tree_t *stream_avl,
     char **top_zfs, int cleanup_fd, uint64_t *action_handlep)
 {
@@ -2886,7 +2981,7 @@
 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
 	    "cannot receive"));
 
-	if (flags.isprefix &&
+	if (flags->isprefix &&
 	    !zfs_dataset_exists(hdl, tosnap, ZFS_TYPE_DATASET)) {
 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "specified fs "
 		    "(%s) does not exist"), tosnap);
@@ -2906,7 +3001,7 @@
 	/* the kernel needs the non-byteswapped begin record */
 	drr_noswap = drr;
 
-	flags.byteswap = B_FALSE;
+	flags->byteswap = B_FALSE;
 	if (drrb->drr_magic == BSWAP_64(DMU_BACKUP_MAGIC)) {
 		/*
 		 * We computed the checksum in the wrong byteorder in
@@ -2914,7 +3009,7 @@
 		 */
 		bzero(&zcksum, sizeof (zio_cksum_t));
 		fletcher_4_incremental_byteswap(&drr, sizeof (drr), &zcksum);
-		flags.byteswap = B_TRUE;
+		flags->byteswap = B_TRUE;
 
 		drr.drr_type = BSWAP_32(drr.drr_type);
 		drr.drr_payloadlen = BSWAP_32(drr.drr_payloadlen);
@@ -2982,7 +3077,7 @@
  * (-1 will override -2).
  */
 int
-zfs_receive(libzfs_handle_t *hdl, const char *tosnap, recvflags_t flags,
+zfs_receive(libzfs_handle_t *hdl, const char *tosnap, recvflags_t *flags,
     int infd, avl_tree_t *stream_avl)
 {
 	char *top_zfs = NULL;
@@ -2998,7 +3093,7 @@
 
 	VERIFY(0 == close(cleanup_fd));
 
-	if (err == 0 && !flags.nomount && top_zfs) {
+	if (err == 0 && !flags->nomount && top_zfs) {
 		zfs_handle_t *zhp;
 		prop_changelist_t *clp;
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/cddl/contrib/opensolaris/lib/libzfs/common/libzfs_util.c
--- a/head/cddl/contrib/opensolaris/lib/libzfs/common/libzfs_util.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/cddl/contrib/opensolaris/lib/libzfs/common/libzfs_util.c	Tue Dec 06 20:26:16 2011 +0200
@@ -20,6 +20,7 @@
  */
 /*
  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011 by Delphix. All rights reserved.
  */
 
 /*
@@ -351,6 +352,7 @@
 	switch (error) {
 	case ENXIO:
 	case ENODEV:
+	case EPIPE:
 		zfs_verror(hdl, EZFS_IO, fmt, ap);
 		break;
 
@@ -1324,7 +1326,8 @@
 	 * dataset property,
 	 */
 	if (prop == ZPROP_INVAL && (type == ZFS_TYPE_POOL ||
-	    (!zfs_prop_user(propname) && !zfs_prop_userquota(propname)))) {
+	    (!zfs_prop_user(propname) && !zfs_prop_userquota(propname) &&
+	    !zfs_prop_written(propname)))) {
 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
 		    "invalid property '%s'"), propname);
 		return (zfs_error(hdl, EZFS_BADPROP,
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/cddl/lib/drti/Makefile
--- a/head/cddl/lib/drti/Makefile	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/cddl/lib/drti/Makefile	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-# $FreeBSD$
+# $FreeBSD: head/cddl/lib/drti/Makefile 228057 2011-11-28 10:01:36Z rwatson $
 
 .PATH:		${.CURDIR}/../../../cddl/contrib/opensolaris/lib/libdtrace/common
 
@@ -18,4 +18,4 @@
 		-I${OPENSOLARIS_SYS_DISTDIR}/uts/common \
 		-DPIC ${PICFLAG}
 
-.include <bsd.prog.mk>
+.include <bsd.lib.mk>
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/cddl/lib/libzfs/Makefile
--- a/head/cddl/lib/libzfs/Makefile	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/cddl/lib/libzfs/Makefile	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-# $FreeBSD: head/cddl/lib/libzfs/Makefile 226940 2011-10-30 16:29:04Z rmh $
+# $FreeBSD: head/cddl/lib/libzfs/Makefile 228103 2011-11-28 21:40:00Z mm $
 
 .PATH: ${.CURDIR}/../../../cddl/compat/opensolaris/misc
 .PATH: ${.CURDIR}/../../../sys/cddl/contrib/opensolaris/common/zfs
@@ -20,8 +20,8 @@
 	libzfs_config.c \
 	libzfs_dataset.c \
 	libzfs_diff.c \
-	libzfs_graph.c \
 	libzfs_import.c \
+	libzfs_iter.c \
 	libzfs_mount.c \
 	libzfs_pool.c \
 	libzfs_sendrecv.c \
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/AUTHORS
--- a/head/contrib/gperf/AUTHORS	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/contrib/gperf/AUTHORS	Tue Dec 06 20:26:16 2011 +0200
@@ -1,2 +1,2 @@
 Douglas C. Schmidt  <schmidt at ics.uci.edu>
-Bruno Haible        <haible at clisp.cons.org>
+Bruno Haible        <bruno at clisp.org>
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/COPYING
--- a/head/contrib/gperf/COPYING	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/contrib/gperf/COPYING	Tue Dec 06 20:26:16 2011 +0200
@@ -2,7 +2,7 @@
                        Version 2, June 1991
 
  Copyright (C) 1989, 1991 Free Software Foundation, Inc.
-                          59 Temple Place, Suite 330, Boston, MA 02111-1307,
+                          51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
                           USA.
  Everyone is permitted to copy and distribute verbatim copies
  of this license document, but changing it is not allowed.
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/ChangeLog
--- a/head/contrib/gperf/ChangeLog	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/contrib/gperf/ChangeLog	Tue Dec 06 20:26:16 2011 +0200
@@ -1,3 +1,1646 @@
+2007-04-30  Brendan Kehoe  <brendan at zen.org>
+
+	* gperf-3.0.3 released.
+	* src/version.cc: Bump to 3.0.3.
+	* tests/*.exp: Bump to 3.0.3 in header.
+	* doc/gperf.1: Regenerate with gperf 3.0.3.
+
+2007-04-06  Bruno Haible  <bruno at clisp.org>
+
+	Improve support for mingw.
+	* tests/Makefile.in (check-c, check-ada, check-modula3, check-pascal,
+	check-lang-utf8, check-lang-ucs2): Remove '\r' from output before diff.
+	(POSTPROCESS_FOR_MINGW): New variable.
+	(check-test): Use it to postprocess output before diff.
+
+2007-04-04  Bruno Haible  <bruno at clisp.org>
+
+	Support for newer GNU standards.
+	* doc/configure.ac (mandir): Remove assignment.
+	* doc/Makefile.in (datarootdir): New variable.
+	(docdir, dvidir, psdir, pdfdir, htmldir): Use value determined by
+	autoconf.
+	* configure.ac: Require autoconf >= 2.60.
+	* doc/configure.ac: Likewise.
+	* lib/configure.ac: Likewise.
+	* src/configure.ac: Likewise.
+	* tests/configure.ac: Likewise.
+	* configure: Regenerated with autoconf-2.61.
+	* doc/configure: Likewise.
+	* lib/configure: Likewise.
+	* src/configure: Likewise.
+	* tests/configure: Likewise.
+	* src/config.h.in: Likewise.
+	* src/config.h.msvc: Likewise.
+	* src/config.h_vms: Likewise.
+
+2007-04-04  Bruno Haible  <bruno at clisp.org>
+
+	* doc/Makefile.in (MAKEINFO): Disable also the LC_MESSAGES and LC_ALL
+	environment variables.
+
+2007-04-04  Bruno Haible  <bruno at clisp.org>
+
+	* configure.ac: Renamed from configure.in.
+	* doc/configure.ac: Renamed from doc/configure.in.
+	* lib/configure.ac: Renamed from lib/configure.in.
+	* src/configure.ac: Renamed from src/configure.in.
+	* tests/configure.ac: Renamed from tests/configure.in.
+	* Makefile.devel: Update.
+	* INSTALL: Update.
+
+2007-03-31  Bruno Haible  <bruno at clisp.org>
+
+	* tests/test.c (in_word_set): New declaration.
+	* tests/test2.c (in_word_set): Likewise.
+
+2007-03-31  Bruno Haible  <bruno at clisp.org>
+
+	* src/options.cc (Options::parse_options): Bump copyright year.
+
+2007-03-31  Bruno Haible  <bruno at clisp.org>
+
+	* doc/gperf.texi: Fix typo.
+
+2007-03-31  Bruno Haible  <bruno at clisp.org>
+
+	Change generated code after the meaning of __inline is changed in
+	GCC 4.3.
+	* src/output.cc (Output::output_lookup_function): Emit an inline
+	marker that also works with gcc-4.3 in c99 or gnu99 mode.
+	* tests/c-parse.exp, tests/charsets.exp, tests/chill.exp,
+	tests/cplusplus.exp, tests/gpc.exp, tests/incomplete.exp,
+	tests/java.exp, tests/languages.exp, tests/modula2.exp,
+	tests/objc.exp, tests/permut2.exp, tests/permut3.exp,
+	tests/permutc2.exp, tests/test-4.exp: Update.
+	Reported by Bruce Korb <Bruce.Korb at gmail.com>.
+
+2006-06-29  Brendan Kehoe  <brendan at zen.org>
+
+	* gperf-3.0.2 released.
+
+	* doc/Makefile.in (all): No longer depend on dvi.
+
+2006-01-22  Brendan Kehoe  <brendan at zen.org>
+
+	* doc/gperf.texi: Update copyright to be 1989-2006.
+	(UPDATED): Change to 22 January 2006.
+	* doc/gperf.1 (TH): Fix date.
+	* configure.in: Update copyright years.
+	* configure: Regenerate.
+	* src/Makefile.in: Update copyright years.
+
+	* doc/gperf.{dvi,ps,pdf}: Regenerated by manually invoking tex
+	instead of trying to use texi2dvi, whose run of etex ends up
+	actually always running pdfetex, thus always recreating gperf.pdf.
+
+2006-01-13  Brendan Kehoe  <brendan at zen.org>
+
+	* NEWS: Add note about #line directive fix.
+	* doc/gperf.1: Regenerate with Makefile.devel.
+
+	* doc/gperf.texi (UPDATED): Correct to be today.
+	* doc: Regenerated by doing make in a configured tree.
+	Requires makeinfo, texi2dvi, texi2pdf, and texi2html.
+
+	* configure.in: Add AC_OBJEXT and AC_EXEEXT.
+	* lib/Makefile.in (OBJEXT): Define for subst.
+	(OBJECTS): Use $(OBJEXT) instead of '.o'.
+	* src/Makefile.in: Make dependencies use $(OBJEXT).
+	(OBJEXT, EXEEXT): Define for subst.
+	(TARGETPROG): Add $(EXEEXT).
+	(OBJECTS): Use $(OBJEXT) instead of '.o'.
+	(clean): Remove *.$(OBJEXT) instead of *.o.
+
+2006-01-13  Bruno Haible  <bruno at clisp.org>
+
+	Fix #line directives for filenames containing backslashes.
+	* src/output.cc (output_line_directive): New function.
+	(output_keyword_entry, Output::output): Use it.
+	Reported by Alexander <alexander.me at gmail.com>.
+
+	* src/options.cc (Options::parse_options): Update years in --version
+	output.
+
+2005-08-29  Brendan Kehoe  <brendan at zen.org>
+
+	* src/keyword.cc: Tweak comment to avoid nesting.
+
+2005-08-27  Bruno Haible  <bruno at clisp.org>
+
+	Fix missing ranlib detection when cross-compiling.
+	* aclocal.m4 (CL_PROG_RANLIB): Remove macro.
+	* lib/configure.in: Use AC_PROG_RANLIB instead of CL_PROG_RANLIB.
+
+2005-07-30  Bruno Haible  <bruno at clisp.org>
+
+	* src/version.cc: Bump version number to 3.0.2.
+	* doc/gperf.texi: Likewise.
+	* tests/c-parse.exp, tests/charsets.exp, tests/chill.exp,
+	tests/cplusplus.exp, tests/gpc.exp, tests/incomplete.exp,
+	tests/java.exp, tests/languages.exp, tests/modula2.exp,
+	tests/objc.exp, tests/permut2.exp, tests/permut3.exp,
+	tests/permutc2.exp, tests/test-4.exp: Update.
+
+2005-07-30  Bruno Haible  <bruno at clisp.org>
+
+	* src/positions.h: Add forward declarations of friend classes.
+	Needed for compilation with g++ 4.0.
+
+2004-08-22  Bruno Haible  <bruno at clisp.org>
+
+	* tests/Makefile.in (check-lang-syntax): Add test for the
+	--length-table-name option.
+	* tests/test-6.exp: Update.
+
+2004-08-21  Bruce Lilly <blilly at erols.com>
+
+	* src/input.cc (Input::read_input): Accept length-table-name
+	declaration.
+	* src/options.h (Options::get_lengthtable_name,
+	Options::set_lengthtable_name): New declarations.
+	(Options): Add field _lengthtable_name.
+	* src/options.icc (Options::get_lengthtable_name): New inline method.
+	* src/options.cc (DEFAULT_LENGTHTABLE_NAME): New constant.
+	(Options::long_usage): Document --length-table-name option.
+	(Options::Options): Initialize _lengthtable_name field.
+	(Options::~Options): Update.
+	(Options::set_lengthtable_name): New method.
+	(long_options): Add option --length-table-name.
+	(Options::parse_options): Implement --length-table-name option.
+	* src/output.cc (Output::output_keylength_table, output_switch_case,
+	Output::output_lookup_function_body): Use option.get_lengthtable_name.
+	* doc/gperf.texi (Gperf Declarations): Document %define
+	length-table-name.
+	(Output Details): Document --length-table-name option.
+
+2003-06-12  Bruno Haible  <bruno at clisp.org>
+
+	* gperf-3.0.1 released.
+
+	* src/version.cc: Bump version number to 3.0.1.
+	* doc/gperf.texi: Likewise.
+	* tests/c-parse.exp, tests/charsets.exp, tests/chill.exp,
+	tests/cplusplus.exp, tests/gpc.exp, tests/incomplete.exp,
+	tests/java.exp, tests/languages.exp, tests/modula2.exp,
+	tests/objc.exp, tests/permut2.exp, tests/permut3.exp,
+	tests/permutc2.exp, tests/test-4.exp: Update.
+
+2003-05-31  Bruno Haible  <bruno at clisp.org>
+
+	* doc/gperf.texi (User-supplied Struct): Mention the possibility of an
+	abbreviated struct declaration.
+	* src/input.cc (Input::read_input): Support struct declarations of the
+	form "struct foo;".
+	* tests/incomplete.gperf: New file.
+	* tests/incomplete.exp: New file.
+	* tests/Makefile.in (check-test): Check incomplete.gperf too.
+	Reported by Rob Leslie <rob at mars.org>.
+
+2003-05-20  Bruno Haible  <bruno at clisp.org>
+
+	* doc/Makefile.in (gperf.ps): Don't use $< in a target rule.
+
+2003-05-27  Bruno Haible  <bruno at clisp.org>
+
+	* Makefile.vms (CC): Correct value.
+	(getopt.obj, getopt1.obj, getline.obj, hash.obj): Don't set
+	HAVE_CONFIG_H.
+
+2003-05-17  Bruno Haible  <bruno at clisp.org>
+
+	* Makefile.msvc (DEBUGFLAGS): New variable.
+	(gperf.exe): Use it, and MFLAGS too.
+
+2003-05-08  Bruno Haible  <bruno at clisp.org>
+
+	* gperf-3.0 released.
+
+2003-05-07  Bruno Haible  <bruno at clisp.org>
+
+	* src/version.cc: Bump version number to 3.0.
+	* doc/gperf.texi: Likewise.
+	* tests/c-parse.exp, tests/charsets.exp, tests/chill.exp,
+	tests/cplusplus.exp, tests/gpc.exp, tests/java.exp,
+	tests/languages.exp, tests/modula2.exp, tests/objc.exp,
+	tests/permut2.exp, tests/permut3.exp, tests/permutc2.exp,
+	tests/test-4.exp: Update.
+
+	* src/configure.in: Fix AC_INIT argument.
+
+	* Makefile.devel (configure, lib/configure, src/configure,
+	tests/configure, doc/configure): Use the newest autoconf.
+	(src/config.h.in): Use the newest autoheader.
+
+2003-05-03  Bruno Haible  <bruno at clisp.org>
+
+	* doc/gperf.texi: Use two spaces as sentence separator, as recommended
+	by the texinfo manual.
+
+2003-04-12  Bruno Haible  <bruno at clisp.org>
+
+	* doc/configure.in (mandir): Change default value.
+	* doc/Makefile.in (docdir): Use datadir instead of prefix.
+	* Makefile.msvc (datadir): New variable.
+	(mandir, docdir): Use it instead of prefix.
+	(install, installdirs): Update.
+	* Makefile.vms (datadir): New variable.
+	(mandir, docdir): Use it instead of prefix.
+	(install, installdirs): Update.
+
+2003-04-12  Bruno Haible  <bruno at clisp.org>
+
+	* README.vms: New file.
+	* Makefile.vms: New file.
+	* Makefile.devel (src/config.h_vms): New rule.
+	(all): Depend on it.
+
+2003-03-19  Bruno Haible  <bruno at clisp.org>
+
+	* src/input.cc (Input::read_input): Ignore comments at the beginning
+	of the declarations section.
+	* doc/gperf.texi (Controls for GNU indent): New section.
+	Reported by Bruce Lilly <blilly at erols.com>.
+
+2003-03-19  Bruno Haible  <bruno at clisp.org>
+
+	* src/output.cc (Output::output_hash_function): Avoid lint warning if
+	not all arguments of the hash function are used. Avoid lint warning
+	for fallthrough in switch.
+	* tests/c-parse.exp, tests/charsets.exp, tests/chill.exp,
+	tests/cplusplus.exp, tests/java.exp, tests/languages.exp,
+	tests/modula2.exp, tests/objc.exp: All /*FALLTHROUGH*/ to expected
+	output.
+	Reported by Bruce Lilly <blilly at erols.com>.
+
+2003-03-01  Bruno Haible  <bruno at clisp.org>
+
+	* src/options.h (Options::set_initializer_suffix): New declaration.
+	* src/options.cc (Options::set_initializer_suffix): New method.
+	* src/input.cc (Input::read_input): Recognize %define
+	initializer-suffix.
+	* doc/gperf.texi (Gperf Declarations): Document %define
+	initializer-suffix.
+	* NEWS: Update.
+
+2003-02-26  Bruno Haible  <bruno at clisp.org>
+
+	* Makefile.msvc: New file.
+	* README.woe32: New file.
+	* Makefile.devel (all): Depend on src/config.h.msvc.
+	(src/config.h.msvc): New rule.
+
+2003-01-07  Bruno Haible  <bruno at clisp.org>
+
+	* src/input.h (Input::_charset_dependent): New field.
+	* src/input.cc (Input::read_input): Also set _charset_dependent.
+	* src/main.cc (main): Pass _charset_dependent from Input to Output.
+	* src/output.h (Output::Output): Add charset_dependent argument.
+	(Output::_charset_dependent): New field.
+	* src/output.cc (Output::Output): Add charset_dependent argument.
+	(Output::output): Provoke a compilation error if the execution
+	character set doesn't match the expectations.
+	* tests/c-parse.exp, tests/charsets.exp, tests/chill.exp,
+	tests/cplusplus.exp, tests/gpc.exp, tests/java.exp,
+	tests/languages.exp, tests/modula2.exp, tests/objc.exp,
+	tests/permut2.exp, tests/permut3.exp, tests/permutc2.exp,
+	tests/test-4.exp: Update.
+
+	* src/options.cc (Options::long_usage): Change bug report address to
+	<bug-gnu-gperf at gnu.org>.
+	* tests/test-6.exp: Update.
+
+	* src/output.cc (USE_DOWNCASE_TABLE): New macro.
+	(output_upperlower_table): New function.
+	(output_upperlower_strcmp, output_upperlower_strncmp,
+	output_upperlower_memcmp): Emit gperf_downcase array accesses.
+	(Output::output): Call output_upperlower_table.
+	* tests/permutc2.exp: Update.
+
+	* src/keyword-list.icc (KeywordExt_List::rest): Use a portable cast.
+	(Only in GCC a cast of an lvalue is an lvalue.)
+
+2003-01-01  Bruno Haible  <bruno at clisp.org>
+
+	* src/options.cc (Options::parse_options): Update copyright year.
+
+	* doc/gperf.texi (@author): Add me.
+
+	* src/options.h (NULLSTRINGS): New enum value.
+	(Options::get_stringpool_name, Options::set_stringpool_name): New
+	method declarations.
+	(Options::_stringpool_name): New field.
+	* src/options.icc (Options::get_stringpool_name): New method.
+	* src/options.cc (DEFAULT_STRINGPOOL_NAME): New variable.
+	(Options::long_usage): Document -Q and --null-strings.
+	(Options::Options): Initialize _stringpool_name.
+	(Options::~Options): Output _stringpool_name, NULLSTRINGS values too.
+	(Options::set_stringpool_name): New method.
+	(long_options): Add options --string-pool-name, --null-strings.
+	(Options::parse_options): Implement options -P, -Q and --null-strings.
+	* src/input.cc (Input::read_input): Recognize declarations %pic,
+	%define string-pool-name, %null-strings.
+	* src/output.h (Output::output_string_pool,
+	Output::output_lookup_pools): New method declarations.
+	(Output::_wordlist_eltype): New field.
+	* src/output.cc (Output::output_keylength_table): Trivial
+	simplification.
+	(Output::output_string_pool): New method.
+	(output_keyword_entry): Add stringpool_index argument. For SHAREDLIB,
+	use struct offsets.
+	(output_keyword_blank_entries): For SHAREDLIB, use -1 instead of "".
+	(Output::output_keyword_table): Use _wordlist_eltype instead of
+	_struct_tag. Compute stringpool_index for output_keyword_entry.
+	(Output::output_lookup_pools): New method.
+	(Output::output_lookup_function_body): Use _wordlist_eltype instead of
+	_struct_tag. For SHAREDLIB, use "+ stringpool" to convert offsets to
+	strings. Use "o >= 0" to test for nonempty table entry.
+	(Output::output_lookup_function): Call output_lookup_pools.
+	(Output::output): Initialize _wordlist_eltype. Call
+	output_lookup_pools.
+	* tests/jstest4.gperf: New file.
+	* tests/test-6.exp: Update.
+	* tests/Makefile.in (check-lang-syntax): Drop test of -p. Add tests of
+	-P and -Q.
+	* doc/gperf.texi (User-supplied Struct): Mention that first field has
+	to be of type 'int' if -P is given.
+	(Gperf Declarations): Document %pic, %define string-pool-name,
+	%null-strings.
+	(Output Details): Update description of option -P. Document options -Q
+	and --null-strings.
+
+	* tests/Makefile.in (check-link-c, check-ada, check-pascal,
+	check-test): Omit option -p.
+	* tests/c-parse.exp: Regenerated.
+	* tests/chill.exp: Regenerated.
+	* tests/cplusplus.exp: Regenerated.
+	* tests/gpc.exp: Regenerated.
+	* tests/java.exp: Regenerated.
+	* tests/objc.exp: Regenerated.
+	* tests/test-4.exp: Regenerated.
+
+	* src/output.cc (Output::output_lookup_function_body): Omit the
+	multicompare code section and its variables when it is not used.
+	* tests/chill.exp: Regenerated.
+
+	* src/output.c (Output_Compare::output_firstchar_comparison): New
+	method.
+	(Output_Compare_Strcmp::output_comparison,
+	Output_Compare_Strncmp::output_comparison,
+	Output_Compare_Memcmp::output_comparison): Use it.
+	* tests/permutc2.exp: Update.
+
+	* tests/smtp.gperf: New file, based on a contribution by Bruce Lilly.
+	* tests/Makefile.in (check-smtp): New rule.
+	(check): Depend on it.
+	(clean): Update.
+
+2002-12-12  Bruno Haible  <bruno at clisp.org>
+
+	* src/search.h (Search::init_selchars_tuple,
+	Search::count_duplicates_tuple): Add alpha_unify argument.
+	(Search::count_duplicates_tuple): New method declaration.
+	* src/search.cc (Search::init_selchars_tuple,
+	Search::count_duplicates_tuple): Add alpha_unify argument.
+	(Search::find_positions): Update.
+	(Search::count_duplicates_tuple): New method.
+	(Search::count_duplicates_multiset): Free temp alpha_unify vector.
+	(Search::find_alpha_inc): Call count_duplicates_tuple.
+
+	* src/configure.in: Add test for stack-allocated variable-size arrays.
+	* src/config.h.in: Regenerated.
+	* src/search.cc: Include config.h.
+	(DYNAMIC_ARRAY, FREE_DYNAMIC_ARRAY): New macros.
+	(Search::find_alpha_inc, Search::count_possible_collisions,
+	Search::find_asso_values): Use them.
+	* src/Makefile.in (search.o): Depend on config.h.
+
+	* src/search.h (Search::keyword_list_length, Search::max_key_length,
+	Search::get_max_keysig_size, Search::prepare): Remove declarations.
+	(Search::prepare): Renamed from Search::preprepare.
+	(Search::_max_selchars_length): New field.
+	* src/search.cc (Search::prepare): Renamed from Search::preprepare.
+	(Search::prepare_asso_values): Merged with old Search::prepare.
+	Initialize _max_selchars_length.
+	(Search::keyword_list_length): Remove function. Use _list_len instead.
+	(Search::max_key_length): Remove function. Use _max_key_len instead.
+	(Search::get_max_keysig_size): Remove function. Use
+	_max_selchars_length instead.
+	(Search::count_possible_collisions, Search::find_asso_values): Update.
+	(Search::find_good_asso_values): Call just prepare_asso_values.
+	(Search::~Search): Update.
+
+	* src/output.h (Output::output_asso_values_ref): New declaration.
+	* src/output.cc (char_to_index): Remove variable.
+	(Output::output_asso_values_ref): New function.
+	(Output::output_hash_function): Use it.
+	(Output::output): Update.
+
+	* src/positions.h (Positions::is_useall, Positions::set_useall,
+	Positions::iterator, Positions::reviterator): New method declarations.
+	(Positions::_useall): New field.
+	(PositionIterator): Make constructor private. Add a constructor and a
+	copy constructor.
+	(PositionIterator::remaining): New declaration.
+	(PositionReverseIterator): Make constructor private. Add a constructor
+	and a copy constructor.
+	(PositionReverseIterator::remaining): New declaration.
+	(PositionReverseIterator::_minindex): New field.
+	* src/positions.icc (Positions::Positions): Initialize _useall.
+	(Positions::operator=): Likewise.
+	(Positions::is_useall, Positions::set_useall): New methods.
+	(Positions::sort): Do nothing if _useall is set.
+	(Positions::iterator, Positions::reviterator): New methods.
+	(PositionIterator::PositionIterator): New constructor.
+	(PositionIterator::remaining): New method.
+	(PositionReverseIterator::PositionReverseIterator): New constructor.
+	(PositionReverseIterator::next): Use _minindex as bound.
+	(PositionReverseIterator::remaining): New method.
+	* src/positions.cc (Positions::add, Positions::remove): Reset the
+	useall flag.
+	(Positions::print): Handle the useall case.
+	* src/options.h (ALLCHARS): Remove.
+	* src/options.cc (Options::~Options): Update.
+	(Options::parse_options): Use Positions::set_useall().
+	* src/keyword.h (KeywordExt::init_selchars_tuple,
+	KeywordExt::init_selchars_multiset, KeywordExt::init_selchars_low):
+	Remove use_all_chars argument.
+	* src/keyword.cc (KeywordExt::init_selchars_low): Remove use_all_chars
+	argument. Tell the position iterator to stop at _allchars_length.
+	Remove special case code for -k'*'.
+	(KeywordExt::init_selchars_tuple, KeywordExt::init_selchars_multiset):
+	Remove use_all_chars argument.
+	* src/search.h (Search::init_selchars_tuple): Remove use_all_chars
+	argument.
+	(Search::init_selchars_multiset): Likewise.
+	* src/search.cc (Search::init_selchars_tuple): Remove use_all_chars
+	argument.
+	(Search::count_duplicates_tuple, Search::find_positions): Update.
+	(Search::compute_alpha_unify): Remove special case code for -k'*'.
+	(Search::init_selchars_multiset): Remove use_all_chars argument.
+	(Search::count_duplicates_multiset): Update.
+	(Search::find_alpha_inc): Remove special case code for -k'*'.
+	(Search::prepare): Update.
+	(Search::get_max_keysig_size): Update.
+	* src/output.cc (Output::output_hash_function): Remove special case
+	code for -k'*'.
+	* tests/chill.exp: Regenerated.
+
+2002-12-11  Bruno Haible  <bruno at clisp.org>
+
+	Change the positions to be 0-based, instead of 1-based.
+	* src/positions.h (Positions::LASTCHAR): Set to -1.
+	(Positions::MAX_SIZE): New constant.
+	(Positions::pointer): Change return type.
+	(Positions::_positions): Change element type.
+	(PositionIterator::EOS, PositionReverseIterator::EOS): Set to -2.
+	* src/positions.icc (Positions::pointer): Change return type.
+	(Positions::sort): Update.
+	* src/positions.cc (Positions::contains, Positions::add,
+	Positions::remove): Update.
+	(Positions::print): Update. Fix off-by-one bug.
+	* src/options.cc (Options::~Options): Update.
+	(Options::parse_options): Set BAD_VALUE to -3. Update.
+	* src/keyword.cc (KeywordExt::init_selchars_low): Update.
+	* src/search.cc (Search::find_positions, Search::compute_alpha_unify,
+	Search::find_alpha_inc): Update.
+	* src/output.cc (Output::output_hash_function): Update. Don't emit
+	a 'case' statement right after 'default:'.
+	* tests/c-parse.exp: Regenerated.
+	* tests/charsets.exp: Regenerated.
+	* tests/cplusplus.exp: Regenerated.
+	* tests/java.exp: Regenerated.
+	* tests/languages.exp: Regenerated.
+	* tests/modula2.exp: Regenerated.
+	* tests/objc.exp: Regenerated.
+
+2002-12-10  Bruno Haible  <bruno at clisp.org>
+
+	* src/options.h: Reorder enum values.
+	(Options::short_usage, Options::long_usage): Make static.
+	* src/options.cc (Options::short_usage); No longer print a monster
+	usage line.
+	(Options::print_options): Improve output of options like
+	--key-positions=1,2,$.
+	(Options::~Options): Update.
+
+	* src/options.h (UPPERLOWER): New enum value.
+	* src/options.cc (Options::long_usage): Document option --ignore-case.
+	(Options::~Options): Update.
+	(long_options): Add option --ignore-case.
+	(Options::parse_options): Handle option --ignore-case.
+	* src/input.cc (Input::read_input): Recognize option %ignore-case.
+	* src/keyword.h (KeywordExt::init_selchars_tuple,
+	KeywordExt::init_selchars_multiset, KeywordExt::init_selchars_low):
+	Add alpha_unify argument.
+	* src/keyword.cc (KeywordExt::init_selchars_low): Add alpha_unify
+	argument.
+	(KeywordExt::init_selchars_tuple): Add alpha_unify argument.
+	(KeywordExt::init_selchars_multiset): Add alpha_unify argument.
+	* src/search.h (Search::compute_alpha_size,
+	Search::compute_alpha_unify): New declarations.
+	(Search::init_selchars_multiset): Add alpha_unify argument.
+	(Search::_alpha_unify): New field.
+	* src/search.cc (Search::compute_alpha_size,
+	Search::compute_alpha_unify): New functions.
+	(Search::init_selchars_tuple): Update.
+	(Search::find_positions): Temporarily set _alpha_unify. Perform a
+	case insensitive comparison if needed.
+	(Search::init_selchars_multiset): Add alpha_unify argument.
+	(Search::count_duplicates_multiset): Call compute_alpha_unify.
+	(Search::find_alpha_inc): Temporarily set _alpha_unify. At the end,
+	set _alpha_size and _alpha_unify.
+	(Search::prepare): Update. Don't compute _alpga_size here.
+	(Search::optimize): Propagate unified asso_values.
+	(Search::~Search) Delete _alpha_unify.
+	* src/output.cc (output_upperlower_strcmp, output_upperlower_strncmp,
+	output_upperlower_memcmp): New functions.
+	(Output_Compare_Strcmp::output_comparison,
+	Output_Compare_Strncmp::output_comparison,
+	Output_Compare_Memcmp::output_comparison): Use the case-insensitive
+	comparison function if --ignore-case was given.
+	(Output::output): Emit the auxiliary case-insensitive comparison
+	function if needed.
+	* tests/permutc2.gperf, tests/permutc2.exp: New files.
+	* tests/Makefile.in (check-test): Also check permutc2.gperf.
+	* tests/test-6.exp: Update.
+	* doc/gperf.texi (Gperf Declarations): Document %ignore-case.
+	(Input Details): Document option --ignore-case.
+	* NEWS: Update.
+
+	* src/search.cc (Search::optimize): Fill unused asso_values[] entries
+	with a large value.
+	* src/output.h (Output::Output): Remove occurrences argument.
+	(Output::_occurrences): Remove field.
+	* src/output.cc (Output::Output): Remove occurrences argument.
+	(Output::output_hash_function): Ignore _occurrences.
+	* src/main.cc (main): Don't pass the _occurrences to Output.
+
+	* src/search.cc (Search::preprepare): Exit if keywords contain
+	out-of-range characters.
+
+	* src/search.cc (for): Define so as to avoid errors with old compilers.
+
+	* src/options.h (SHAREDLIB): New enum value.
+	* src/options.cc (Options::short_usage): Mention option -P.
+	(Options::long_usage): Document option -P.
+	(long_options): Add option --pic.
+	(Options::parse_options): Handle option -P/--pic.
+	* src/output.cc (output_keyword_blank_entries): When SHAREDLIB is
+	specified, emit NULL pointers instead of "".
+	(Output::output_lookup_function_body): When SHAREDLIB is specified
+	and SWITCH and DUP and not specified, test the table entry against
+	NULL before the string comparison.
+	* tests/test-6.exp: Update.
+	* doc/gperf.texi (Output Details): Document option -P.
+	* NEWS: Update.
+	Suggested by Ulrich Drepper.
+
+2002-12-08  Bruno Haible  <bruno at clisp.org>
+
+	* tests/permut2.gperf, tests/permut2.exp: New files.
+	* tests/permut3.gperf, tests/permut3.exp: New files.
+	* tests/charsets.gperf: New file, from Bruce Lilly.
+	* tests/charsets.exp: New file.
+	* tests/languages.gperf: New file, from Bruce Lilly.
+	* tests/languages.exp: New file.
+	* Makefile.in (check-test): Test them all.
+
+	Completely new asso_values search algorithm.
+	* src/search.h (Search::compute_occurrence, Search::clear_determined,
+	Search::set_determined, Search::already_determined, Search::reorder):
+	Remove functions.
+	(Search::init_asso_values, Search::sort_by_occurrence,
+	Search::compute_occurrence, Search::sort_by_occurrence,
+	Search::has_collisions, Search::collision_prior_to): Remove functions.
+	(Search::compute_partition, Search::count_possible_collisions,
+	Search::unchanged_partition): New method declarations.
+	(Search::_determined): Remove field.
+	* src/search.cc (Search::prepare): Don't initialize _determined.
+	(Search::compute_occurrence, greater_by_occurrence,
+	Search::clear_determined, Search::set_determined,
+	Search::already_determined, Search::reorder): Remove functions.
+	(Search::init_asso_values, compute_disjoint_union,
+	Search::sort_by_occurrence, Search::compute_occurrence,
+	Search::sort_by_occurrence, Search::has_collisions,
+	Search::collision_prior_to): Remove functions.
+	(StackEntry): Remove class.
+	(EquivalenceClass, Step): New classes.
+	(equals, Search::compute_partition, delete_partition,
+	Search::count_possible_collisions, Search::unchanged_partition): New
+	functions.
+	(Search::find_asso_values): Completely rewritten.
+	(Search::find_good_asso_values): Don't call reorder().
+	(Search::~Search): Don't free _determined.
+	* src/keyword.h (KeywordExt::_occurrence): Remove field.
+	* src/options.h (ORDER, FAST, OPT_CHOICE): Remove enum values.
+	(Options::_iterations): Remove field.
+	* src/options.icc (Options::get_iterations): Remove method.
+	* src/options.cc (Options::long_usage): Remove mention of -f and -o.
+	(Options::Options): Don't initialize _iterations.
+	(Options::~Options): Update.
+	(Options::parse_options): Do nothing for options -f, -o, -O.
+	* doc/gperf.texi: (Contributors): Update.
+	(Algorithmic Details): Remove options -f and -o. Update description
+	of option -s.
+	* tests/c-parse.exp, tests/chill.exp, tests/cplusplus.exp,
+	tests/gpc.exp, tests/java.exp, tests/modula2.exp, tests/objc.exp,
+	tests/test-4.exp): Regenerated, smaller than before.
+	* tests/test-6.exp: Update.
+	* NEWS: Update.
+
+2002-12-08  Bruno Haible  <bruno at clisp.org>
+
+	* src/search.h (Search::_alpha_size): Change type to 'unsigned int'.
+	(Search::_asso_value_max): Likewise.
+	* src/search.cc (Search::prepare_asso_values): Update.
+	(Search::init_asso_values): Update.
+	(Search::~Search): Update.
+	* src/output.h (Output::Output): Change alpha_size type to
+	'unsigned int'.
+	(Output::_alpha_size): Change type to 'unsigned int'.
+	* src/output.cc (Output::Output): Change alpha_size type to
+	'unsigned int'.
+	(Output::output_hash_function): Update.
+
+2002-12-07  Bruno Haible  <bruno at clisp.org>
+
+	* src/options.h (OPT_CHOICE): New enum value.
+	* src/options.cc (Options::~Options): Update.
+	(long_options): New option --optimized-collision-resolution.
+	(Options::parse_options): Accept option -O.
+	* src/search.h (Search::sort_by_occurrence): Change argument to
+	'unsigned int'.
+	(Search::compute_occurrence, Search::sort_by_occurrence): New method
+	declarations.
+	* src/search.cc (Search::sort_by_occurrence): Change argument to
+	'unsigned int'.
+	(Search::compute_occurrence, Search::sort_by_occurrence): New methods.
+	(Search::find_asso_values): Implement OPT_CHOICE. More debugging
+	output.
+
+	* src/search.cc (Search::prepare_asso_values) [DEBUG]: Also print
+	the keyword list in order.
+	(Search::find_asso_values) [DEBUG]: Upon failure, print the union_set.
+
+	* src/options.h (Options::get_size_multiple): Change return type to
+	float.
+	(Options::_size_multiple): Change type to float.
+	* src/options.icc (Options::get_size_multiple): Change return type to
+	float.
+	* src/options.cc (Options::long_usage): Update description of option
+	-s.
+	(Options::~Options): Update.
+	(Options::parse_options): For option -s, accept a fraction.
+	* src/search.cc (Search::prepare_asso_values): Use get_size_multiple
+	as it is.
+	* tests/test-6.exp: Update.
+	* doc/gperf.texi (Algorithmic Details): Update description of option
+	-s.
+
+2002-12-04  Bruno Haible  <bruno at clisp.org>
+
+	Improve debugging output.
+	* src/hash-table.h (Hash_Table::dump): New method.
+	* src/hash-table.cc (Hash_Table::dump): New method, extracted from
+	destructor.
+	(Hash_Table::~Hash_Table): No longer print the contents.
+	* src/positions.h (PositionReverseIterator): New class.
+	* src/positions.icc (PositionReverseIterator::PositionReverseIterator,
+	PositionReverseIterator::next): New methods.
+	* src/search.cc (Search::find_positions): If debugging, print the
+	result.
+	(Search::find_alpha_inc): If debugging, print the result.
+	(Search::prepare): Explicitly dump the hash table's contents here.
+
+	Portability fixes.
+	* src/positions.h (Positions::LASTCHAR, Positions::MAX_KEY_POS,
+	PositionIterator::EOS): Define as compile-time constants using enum.
+	* src/bool-array.cc (Bool_Array::~Bool_Array): Remove const qualifier
+	of pointer to be deleted.
+	* src/input.cc (Input::~Input): Likewise.
+	* src/keyword.cc (KeywordExt::delete_selchars): Likewise.
+	* src/main.cc (main): Likewise.
+	* src/hash-table.cc (Hash_Table::~Hash_Table): Limit scope of 'for'
+	variables.
+	* src/search.cc (Search::prepare_asso_values): Use a static_cast to
+	convert from time_t to long. This is possible because ISO C 99 says
+	time_t is a numeric type.
+
+2002-11-20  Bruno Haible  <bruno at clisp.org>
+
+	* src/search.cc (Search::find_asso_values): Avoid gcc warnings about
+	uninitialized variables.
+
+	Implement backtracking.
+	* src/search.h (Search::has_collisions): Renamed from
+	Search::less_collisions. Return a boolean.
+	* src/search.cc (Search::has_collisions): Renamed from
+	Search::less_collisions. Return a boolean.
+	(StackEntry): Remove field _collisions_so_far.
+	(Search::find_asso_values): Backtrack when encountering an unresolved
+	collision. Assume collisions_so_far is always zero.
+	(Search::optimize): Exit if there are accidental duplicates at the end.
+	* src/output.cc (Output::num_hash_values): Simply return the list
+	length.
+	(Output::output_keylength_table): Remove handling of accidental
+	duplicates.
+	(Output::output_keyword_table, Output::output_lookup_array): Likewise.
+	(output_switch_case, output_switches): Likewise.
+	* doc/gperf.texi (Algorithmic Details): Adjust description of options
+	-D, -f, -o, -r.
+	(Bugs): Remove note about missing backtracking.
+	(Projects): Likewise.
+
+2002-11-19  Bruno Haible  <bruno at clisp.org>
+
+	Prepare for backtracking.
+	* src/search.h (Search::try_asso_value, Search::change_some_asso_value):
+	Remove declarations.
+	(Search::less_collisions, Search::collision_prior_to): New declarations.
+	(Search::_fewest_collisions, Search::_union_set, Search::_num_done):
+	Remove fields.
+	* src/search.cc (Search::prepare_asso_values): Don't initialize
+	_union_set.
+	(Search::try_asso_value, Search::change_some_asso_value): Remove
+	methods.
+	(Search::less_collisions, Search::collision_prior_to): New methods.
+	(StackEntry): New class.
+	(Search::find_asso_values): Reorganized to use pseudo-recursion.
+	(Search::~Search): Don't free _union_set.
+
+	* src/search.h (Search::find_good_asso_values): New declaration.
+	* src/search.cc: Add comments about the basic structure of the
+	algorithm.
+	(Search::find_positions): Move the option[POSITIONS] test to here.
+	(Search::find_good_asso_values): New method, extracted from
+	Search::optimize.
+	(Search::optimize): Remove option[POSITIONS] test. Call
+	find_good_asso_values.
+
+2002-11-17  Bruno Haible  <bruno at clisp.org>
+
+	* src/options.cc (Options::parse_options): Include copyright notice
+	and authors in --version output.
+
+	Avoid artificial duplicates.
+	* src/keyword.h (KeywordExt::init_selchars_tuple): New declaration.
+	(KeywordExt::init_selchars_multiset): Renamed from
+	KeywordExt::init_selchars.
+	(KeywordExt::init_selchars_low): New declaration.
+	* src/keyword.cc (KeywordExt::init_selchars_low): Renamed from
+	KeywordExt::init_selchars. Add alpha_inc argument. Remove sorting.
+	(KeywordExt::init_selchars_tuple): New method.
+	(KeywordExt::init_selchars_multiset): New method, replaces
+	KeywordExt::init_selchars.
+	* src/search.h (Search::init_selchars_tuple): Renamed from
+	Search::init_selchars.
+	(Search::count_duplicates_tuple): Renamed from Search::count_duplicates.
+	(Search::init_selchars_multiset, Search::count_duplicates_multiset,
+	Search::find_alpha_inc): New declarations.
+	(Search::_alpha_inc): New field.
+	(Search::_alpha_size, Search::_occurrences, Search::_asso_values,
+	Search::_determined): Make non-const.
+	* src/search.cc (Search::Search): Don't initialize _key_positions,
+	_alpha_size, _occurrences, _asso_values, _determined here.
+	(Search::init_selchars_tuple): Renamed from Search::init_selchars.
+	(Search::count_duplicates_tuple): Renamed from Search::count_duplicates.
+	(Search::find_positions): Update.
+	(Search::init_selchars_multiset, Search::count_duplicates_multiset,
+	Search::find_alpha_inc): New methods.
+	(Search::prepare): Move preprepare, find_positions calls away.
+	Initialize _alpha_size, _occurrences, _asso_values, _determined here.
+	(Search::optimize): Call preprepare, find_positions here. Initialize
+	_key_positions here.
+	(Search::~Search): Deallocate _alpha_inc.
+	* src/output.cc (Output::Output): Add alpha_inc argument.
+	(Output::output_hash_function): Use _alpha_inc.
+	* src/output.h (Output::Output): Add alpha_inc argument.
+	(Output::_alpha_inc): New field.
+	* src/main.cc (main): Pass _alpha_inc from Search to Output.
+	* tests/chill.exp: Update.
+	* doc/gperf.texi (Algorithmic Details): Remove description of
+	artificial duplicates.
+
+	* src/keyword.h (KeywordExt::_selchars): Change type to
+	'const unsigned int *'.
+	* src/keyword.cc (sort_char_set): Change argument type to
+	'unsigned int *'.
+	(KeywordExt::init_selchars): Update.
+	* src/search.h (Search::sort_by_occurrence): Change argument type to
+	'unsigned int *'.
+	(Search::try_asso_value): Change argument type to 'unsigned int'.
+	(Search::_union_set): Change type to 'unsigned int *'.
+	* src/search.cc (Search::prepare, Search::compute_occurrence,
+	Search::set_determined, Search::already_determined,
+	Search::prepare_asso_values, Search::compute_hash): Update.
+	(compute_disjoint_union): Change argument types to 'unsigned int *'.
+	(Search::sort_by_occurrence): Likewise.
+	(Search::try_asso_value): Change argument type to 'unsigned int'.
+	(Search::change_some_asso_value, Search::~Search): Update.
+	* src/hash-table.cc (Hash_Table::~Hash_Table, Hash_Table::equal,
+	Hash_Table::insert): Update.
+
+	* src/positions.h: New file, extracted from options.h.
+	* src/positions.icc: New file, extracted from options.icc.
+	* src/positions.cc: New file, extracted from options.cc.
+	* src/options.h: Include positions.h. Move classes Positions and
+	PositionsIterator away.
+	* src/options.icc: Move classes Positions and PositionsIterator away.
+	* src/options.cc: Move class Positions away.
+	* src/keyword.cc: Include positions.h instead of options.h.
+	* src/output.h: Include positions.h instead of options.h.
+	* src/search.h: Include positions.h instead of options.h.
+	* src/Makefile.in (OBJECTS): Add positions.o.
+	(POSITIONS_H): New variable.
+	(OPTIONS_H, SEARCH_H, OUTPUT_H, keyword.o): Use it.
+	(positions.o): New rule.
+
+	* src/options.h (POSITIONS): New enum value.
+	(Positions::Positions): New copy constructor.
+	(Positions::operator=, Positions::contains, Position::add,
+	Positions::remove, Positions::print): New method declaration.
+	(Options::get_max_keysig_size): Remove method.
+	* src/options.icc (Positions::Positions): New copy constructor.
+	(Positions::operator=): New method.
+	(Options::get_max_keysig_size): Remove method.
+	* src/options.cc (Options::Options): Initialize _key_positions
+	trivially.
+	(Options::parse_options): Option -k sets POSITIONS.
+	(Positions::contains, Positions::add, Positions::remove,
+	Positions::print): New methods.
+	* src/hash-table.cc (Hash_Table::~Hash_Table): Compute the field
+	width explicitly, instead of using Options::get_max_keysig_size.
+	* src/keyword.h (KeywordExt::init_selchars): Add arguments
+	use_all_chars, positions.
+	(KeywordExt::delete_selchars): New declaration.
+	* src/keyword.cc (KeywordExt::init_selchars): Add arguments
+	use_all_chars, positions. Remove error message if there are no key
+	positions.
+	(KeywordExt::delete_selchars): New method.
+	* src/search.h: Include options.h.
+	(Search::preprepare, Search::init_selchars, Search::delete_selchars,
+	Search::count_duplicates, Search::find_positions): New declarations.
+	(Search::_key_positions): New field.
+	* src/search.cc (Search::Search): Initialize _key_positions.
+	(Search::preprepare, Search::init_selchars, Search::delete_selchars,
+	Search::count_duplicates, Search::find_positions): New functions.
+	(Search::prepare): Call preprepare and find_positions. Tweak error
+	message.
+	(Search::get_max_keysig_size): Use _key_positions instead of
+	option.get_key_positions().
+	(Search::optimize): Tweak error message.
+	* src/output.h: Include options.h.
+	(Output::Output): Add Positions argument.
+	(Output::_key_positions): New field.
+	* src/output.cc (Output::Output): Add Positions argument.
+	(Output::output_hash_function): Omit the table if there are no
+	positions at all. Use _key_positions instead of
+	option.get_key_positions().
+	(Output::output): Output the computed positions as a comment.
+	* src/main.cc (main): Pass the Positions from Searcher to Output.
+	* src/Makefile.in (SEARCH_H, OUTPUT_H): Include OPTIONS_H.
+	* tests/Makefile.in (check-test): Pass key positions explicitly.
+	* tests/gpc.exp: Update.
+	* tests/test-4.exp: Update.
+	* doc/gperf.texi (Algorithmic Details): Mention that -k is not needed
+	usually.
+
+2002-11-16  Bruno Haible  <bruno at clisp.org>
+
+	* src/options.h (Options::get_slot_name): Renamed from
+	Options::get_key_name.
+	(Options::set, Options::set_language, Options::set_total_switches,
+	Options::set_function_name, Options::set_slot_name,
+	Options::set_class_name, Options::set_hash_name,
+	Options::set_wordlist_name, Options::set_delimiters): New method
+	declarations.
+	(Options::_language): New field.
+	(Options::_slot_name): Renamed from Options::_key_name.
+	* src/options.icc (Options::set): New method.
+	(Options::get_slot_name): Renamed from Options::get_key_name.
+	* src/options.cc (DEFAULT_FUNCTION_NAME): Renamed from DEFAULT_NAME.
+	(DEFAULT_SLOT_NAME): Renamed from DEFAULT_NAME.
+	(Options::Options): Initialize _language. Update.
+	(Options::~Options): Update.
+	(Options::set_language, Options::set_total_switches,
+	Options::set_function_name, Options::set_slot_name,
+	Options::set_class_name, Options::set_hash_name,
+	Options::set_wordlist_name, Options::set_delimiters): New methods.
+	(Options::parse_options): Call set_language. Update.
+	* src/input.cc (is_declaration, is_declaration_with_arg,
+	is_define_declaration): New functions.
+	(Input::read_input): Accept %DECL declarations.
+	* src/output.cc (Output::output_lookup_function_body): Update.
+	* doc/gperf.texi (Declarations): Add new subnodes.
+	(User-supplied Struct, Gperf Declarations, C Code Inclusion): New
+	nodes.
+	(Keywords, Output Format, Binary Strings, Options): Mention %
+	declarations as being equivalent to the command line options.
+
+	* src/options.cc (Options::long_usage): Rename options -H, -N, -l, -G.
+	(long_options): Add --hash-function-name, --lookup-function-name,
+	--compare-lengths.
+	* doc/gperf.texi (Output Details): Rename options -H, -N, -l, -G.
+	* tests/test-6.exp: Update.
+
+	* src/options.cc (DEFAULT_DELIMITERS): Remove newline.
+	* src/options.cc (Options::long_usage): Change default --delimiters.
+	* doc/gperf.texi (Input Details): Likewise.
+	* tests/test-6.exp: Update.
+
+	* doc/gperf.texi: Move description of option -l from section
+	Algorithmic Details to section Output Details.
+	* src/options.cc (Options::long_usage): Likewise.
+	* tests/test-6.exp: Update.
+
+2002-11-12  Bruno Haible  <bruno at clisp.org>
+
+	* src/options.h (Output::get_output_file_name): New method.
+	(Output::_output_file_name): New field.
+	* src/options.icc (Options::get_output_file_name): New method.
+	* src/options.cc (Options::long_usage): Document option --output-file.
+	(Options::Options): Initialize _output_file_name.
+	(long_options): Add --output-file.
+	(Options::parse_options): Handle it.
+	* src/main.cc (main): Open the output file if given by name.
+	* doc/gperf.texi (Output File): New section.
+	* tests/test-6.exp: Update.
+
+2002-11-10  Bruno Haible  <bruno at clisp.org>
+
+	* src/input.cc (pretty_input_file_name): New function.
+	(read_input): Use it in all error and warning messages.
+
+	* src/keyword.h (Keyword::_lineno): New field.
+	* src/input.h (Input::_struct_decl_lineno): New field.
+	* src/input.cc (Input::read_input): Set _struct_decl_lineno. Fill
+	each keyword's _lineno field.
+	* src/main.cc (main): Pass _struct_decl_lineno from Input to Output.
+	* src/output.h (Output::Output) Add struct_decl_lineno argument.
+	(Output::_struct_decl_lineno): New field.
+	* src/output.cc (Output::Output) Add struct_decl_lineno argument.
+	(output_keyword_entry): Emit #line directive before table entry.
+	(Output::output): Emit #line directive before _struct_decl.
+
+	Fix memory leaks.
+	* src/keyword.h (empty_string): New declaration.
+	* src/keyword.cc (empty_string): New variable.
+	* src/input.h (Input::_input): Make public.
+	(Input::_input_end): New field.
+	* src/input.cc (read_input): When removing leading whitespace from
+	struct_decl, reallocate it. For rest, use empty_string instead of "".
+	Set _input_end.
+	(Input::~Input): Delete _struct_decl, _struct_tag, _return_type.
+	* src/search.cc (Search::prepare): When removing an element from
+	the keyword list, delete the list node.
+	(Search::~Search): Delete _occurrences, _asso_values.
+	* src/main.cc (main): Between Search::~Search and Input::~Input,
+	destroy the keyword list.
+
+	Rewrite the input routines.
+	* src/input.h: Don't include read-line.h.
+	(Input): Don't inherit from class Read_Line.
+	(Input::read_keys, Input::strcspn, Input::set_output_types,
+	Input::get_array_type, Input::save_include_src,
+	Input::get_special_input): Remove declarations.
+	(Input::read_input): New declaration.
+	(Input::_struct_decl): Renamed from Input::_array_type.
+	(Input::_verbatim_declarations): Renamed from Input::_include_src.
+	(Input::_verbatim_code): Replaces Input::_additional_code.
+	* src/input.cc: Completely rewritten.
+	* src/output.h (Output::Output): Update the verbatim_* arguments.
+	(Output::_struct_decl): Renamed from Output::_array_type.
+	(Output::_verbatim_declarations): Renamed from Output::_include_src.
+	(Output::_verbatim_code): Replaces Output::_additional_code.
+	* src/output.cc (Output::Output): Update the verbatim_* arguments.
+	(Output::output): Output the verbatim_* code pieces with #line.
+	* src/main.cc (main): Call Input::read_input instead of
+	Input::read_keys. Update Output::Output arguments.
+	* src/read-line.h: Remove file.
+	* src/read-line.cc, src/read-line.icc: Remove files.
+	* src/Makefile.in (OBJECTS): Remove read-line.o.
+	(READ_LINE_H): Remove variable.
+	(INPUT_H): Update.
+	(read-line.o): Remove rule.
+	* doc/gperf.texi (Declarations): Correct the example.
+	(Keywords): Mention that lines starting with % are forbidden here.
+	* tests/c-parse.exp: Update.
+	* tests/cplusplus.exp: Update.
+	* tests/gpc.exp: Update.
+	* tests/java.exp: Update.
+	* tests/objc.exp: Update.
+	* tests/test-4.exp: Update.
+
+	* src/options.h (Options::get_input_file_name): New declaration.
+	(Options::_input_file_name): New field.
+	* src/options.icc (Options::get_input_file_name): New method.
+	* src/options.cc (Options::Options): Initialize _input_file_name.
+	(Options::parse_options): Don't open input file, only store it in
+	_input_file_name.
+	* src/main.cc (main): Open input file here.
+	Print an error message upon write error on the output file.
+
+	Upgrade to autoconf-2.52.
+	* configure.in: Use AC_CONFIG_SUBDIRS instead of AC_OUTPUT_SUBDIRS.
+	* Makefile.devel (configure, lib/configure, src/configure,
+	tests/configure, doc/configure): Use autoconf-2.52.
+
+2002-11-09  Bruno Haible  <bruno at clisp.org>
+
+	* doc/gperf.texi: Talk about "bytes" instead of "characters". Talk
+	about "keywords", not "keys". Talk about "input file", not "keyfile".
+	(@menu): Fix a menu entry.
+	(Contributors): Don't mention cperf.
+	(Motivation): Fix an off-by-one error in the definition of "minimal".
+	Mention GNU Java. Recommend http URL instead of anonymous ftp.
+	(Search Structures): Mention GNU Java.
+	(Output Format): Drop reference to node 'Implementation'.
+	(Output Details): Talk about "slot-name" instead of "key name".
+	(Algorithmic Details): Talk about "selected byte positons", not
+	"key positions". Upper limit is now 255. Explain a third reason
+	why duplicates can occur. Describe negative effects of
+	--occurrence-sort.
+	(Implementation): Remove chapter.
+
+2002-11-07  Bruno Haible  <bruno at clisp.org>
+
+	* src/bool-array.cc (Bool_Array::~Bool_Array): Free _storage_array.
+	* src/search.cc (Search::~Search): Free _union_set, _determined.
+
+	* tests/Makefile.in (check-test): Don't redirect stderr.
+
+2002-11-05  Bruno Haible  <bruno at clisp.org>
+
+	* src/keyword-list.h (mergesort_list): New declarations.
+	* src/keyword-list.cc (Keyword_Comparison): New type.
+	(merge, mergesort_list): New functions, moved here from search.cc.
+	* src/search.h (Search::merge, Search::merge_sort): Remove methods.
+	(Search::_occurrence_sort, Search::_hash_sort): Remove fields.
+	* src/search.cc (Search::merge, Search::merge_sort): Remove methods.
+	(greater_by_occurrence, less_by_hash_value): New functions.
+	(Search::reorder, Search::sort): Use mergesort_list.
+
+2002-11-04  Bruno Haible  <bruno at clisp.org>
+
+	* src/options.h (Options::_asso_iterations): New field.
+	(Options::get_asso_iterations): New method declaration.
+	* src/options.icc (Options::get_asso_iterations): New method.
+	* src/options.cc (Options::short_usage): Mention j<jump> and m<num>.
+	(Options::long_usage): Document option -m.
+	(Options::Options): Initialize _asso_iterations.
+	(Options::~Options): Print _asso_iterations too.
+	(long_options): Add --multiple-iterations.
+	(Options::parse_options): Handle option -m.
+	* src/keyword-list.h (copy_list, delete_list): New declarations.
+	* src/keyword-list.cc (copy_list, delete_list): New functions.
+	* src/search.h (Search::_initial_asso_value, Search::_jump): New fields.
+	* src/search.cc (Search::prepare_asso_values): Initialize
+	_initial_asso_value and _jump here.
+	(Search::init_asso_values): Use _initial_asso_value.
+	(Search::try_asso_value): Use _jump.
+	(Search::optimize): If option -m was given, iterate over different
+	values for _initial_asso_value and _jump.
+	* doc/gperf.texi (Algorithmic Details): Document option -m.
+	* tests/test-6.exp: Update.
+
+2002-11-03  Bruno Haible  <bruno at clisp.org>
+
+	Bug fix: When option -j 0 was used without option -r, the output was
+	not random.
+	* src/search.h (Search::prepare_asso_values): New method declaration.
+	* src/search.cc (Search::prepare_asso_values): New method, extracted
+	from Search::init_asso_values. Call srand also when "-j 0" was given.
+	(Search::optimize): Call prepare_asso_values().
+
+	* src/hash-table.h (Hash_Table::_ignore_length, Hash_Table::equal):
+	Declare as const.
+	* src/hash-table.cc (Hash_Table::equal): Declare as const.
+	* src/input.h (Input::_factory): Declare as const.
+	* src/keyword-list.h (Keyword_List::first, KeywordExt_List::first):
+	Declare as const.
+	* src/keyword-list.icc (Keyword_List::first, KeywordExt_List::first):
+	Declare as const.
+	* src/output.h (Output::num_hash_values, Output::output_constants,
+	Output::output_hash_function, Output::output_keylength_table,
+	Output::output_keyword_table, Output::output_lookup_array,
+	Output::output_lookup_tables, Output::output_lookup_function_body,
+	Output::output_lookup_function, Output::_array_type,
+	Output::_additional_code, Output::_include_src, Output::_total_keys,
+	Output::_total_duplicates, Output::_max_key_len, Output::_min_key_len):
+	Declare as const.
+	* src/output.cc (Output::num_hash_values, Output::output_constants,
+	Output::output_hash_function, Output::output_keylength_table,
+	Output::output_keyword_table, Output::output_lookup_array,
+	Output::output_lookup_tables, Output::output_lookup_function_body,
+	Output::output_lookup_function): Declare as const.
+	* src/search.h (Search::merge, Search::merge_sort,
+	Search::compute_occurrence, Search::already_determined,
+	Search::keyword_list_length, Search::max_key_length,
+	Search::get_max_keysig_size, Search::compute_hash,
+	Search::sort_by_occurrence): Declare as const.
+	* src/search.cc (Search::merge, Search::merge_sort,
+	Search::compute_occurrence, Search::already_determined,
+	Search::keyword_list_length, Search::max_key_length,
+	Search::get_max_keysig_size, Search::compute_hash,
+	Search::sort_by_occurrence): Declare as const.
+
+	* src/output.cc (Output::output): Set char_to_index to a cast in all
+	cases. Avoids gcc warnings on the generated code.
+
+	* src/output.cc (Output_Enum): Prepend an underscore to field names.
+	(Output_Expr1): Likewise.
+	(Output::output_hash_function): Simplify the special case for "-k 1,$".
+
+	* src/search.h (Search::init_asso_values, Search::find_asso_values):
+	New declarations.
+	(Search::try_asso_value): Renamed from Search::affects_prev.
+	(Search::change_some_asso_value): Renamed from Search::change.
+	(Search::set_asso_max, Search::get_asso_max): Remove methods.
+	(Search::_union_set): New field.
+	* src/search.cc (Search::init_asso_values): New method, extracted
+	from Search::optimize.
+	(Search::try_asso_value): Renamed from Search::affects_prev. Take the
+	iteration count as argument.
+	(Search::change_some_asso_value): Renamed from Search::change. Don't
+	make union_set static. Don't increment _fewest_collisions here.
+	(Search::find_asso_values): New method, extracted from
+	Search::optimize.
+	(Search::optimize); Update.
+
+	* src/search.h (Search::compute_hash): Renamed from Search::hash.
+	(Search::compute_disjoint_union): Remove declaration.
+	(Search::sort_by_occurrence): Renamed from Search::sort_set.
+	* src/search.cc (Search::compute_hash): Renamed from Search::hash.
+	(compute_disjoint_union): Renamed from Search::compute_disjoint_union.
+	(Search::sort_by_occurrence): Renamed from Search::sort_set.
+	(Search::change): Simplify loop.
+
+	* src/search.h (Search::clear_determined): New declaration.
+	* src/search.cc (Search::clear_determined): New method.
+	(Search::already_determined): Optimize.
+	(Search::reorder): Even when the next keyword after the current one
+	is completely determined, move all determined keywords after the
+	current one.
+
+	Compute the occurrences after removal of duplicates, not before.
+	* src/keyword.h (KeywordExt::init_selchars): Remove occurrences
+	argument.
+	* src/keyword.cc (KeywordExt::init_selchars): Likewise.
+	* src/search.cc (Search::prepare): Reorder the code. Compute the
+	occurrences after removal of duplicates.
+	(Search::merge_sort): Optimize the loop.
+	(Search::compute_occurrence): Renamed from Search::get_occurrence.
+	* src/search.h (Search::compute_occurrence): Renamed from
+	Search::get_occurrence.
+	* tests/chill.exp: Regenerated.
+
+	Bug fix: The hash table could fail to detect duplicates, between
+	keywords of different length, when option -n (option[NOLENGTH]) was
+	given.
+	* src/hash-table.h (Hash_Table::Hash_Table): Pass table size, not
+	vector and vector size as arguments.
+	(Hash_Table::_log_size): New field.
+	(Hash_Table::equal): New declaration.
+	* src/hash-table.cc (size_factor): New variable.
+	(Hash_Table::Hash_Table): Pass table size, not vector and vector size
+	as arguments. Allocate the vector here.
+	(Hash_Table::~Hash_Table): Deallocate the vector here.
+	(Hash_Table::equal): New function.
+	(Hash_Table::insert): Use it. Don't use item->_allchars_length for the
+	increment if _ignore_length is true.
+	* src/search.cc (TABLE_MULTIPLE): Remove variable.
+	(Search::prepare): Update.
+
+2002-11-02  Bruno Haible  <bruno at clisp.org>
+
+	Provide documentation also in PDF format.
+	* doc/Makefile.in (pdfdir, TEXI2PDF): New variables.
+	(all): Depend on pdf.
+	(pdf, gperf.pdf): New rules.
+	(maintainer-clean): Remove the PDF file.
+
+	* src/keyword-list.icc: New file, extracted from keyword-list.h.
+	* src/keyword-list.h: Include keyword-list.icc. Move inline methods
+	to there.
+	* src/keyword-list.cc: Include keyword-list.icc.
+	* src/Makefile.in (KEYWORD_LIST_H): Add keyword-list.icc.
+
+	* lib/hashpjw.h (hashpjw): Change argument type to 'unsigned char *'.
+	* lib/hash.cc (hashpjw): Likewise.
+	* src/keyword.icc: New file.
+	* src/keyword.h: Include keyword.icc.
+	(KeywordExt::_selchars): Change type to 'unsigned char *'.
+	* src/keyword.cc: Include keyword.icc.
+	(Keyword::Keyword, KeywordExt::KeywordExt): Move to keyword.icc.
+	(sort_char_set): Change argument type to 'unsigned char *'.
+	(KeywordExt::init_selchars): Update.
+	* src/search.h (Search::compute_disjoint_union): Change argument types
+	to 'unsigned char *'.
+	(Search::sort_set): Likewise.
+	(Search::affects_prev): Change argument type to 'unsigned char'.
+	* src/search.cc (Search::prepare): Initialize _duplicate_link here.
+	(Search::get_occurrence, Search::set_determined,
+	Search::already_determined, Search::hash): Update.
+	(Search::compute_disjoint_union): Change argument types to
+	'unsigned char *'.
+	(Search::sort_set): Likewise.
+	(Search::affects_prev): Change argument type to 'unsigned char'.
+	(Search::change): Update.
+	* src/Makefile.in (KEYWORD_H): Add keyword.icc.
+
+	* src/options.cc (Options::parse_options): Fix error message.
+
+	* src/read-line.h (Read_Line::Read_Line): Make FILE* argument
+	mandatory. Move body to read-line.icc.
+	* src/read-line.icc (Read_Line::Read_Line): New constructor.
+	* src/input.h (Input::Input): Add FILE* argument.
+	* src/input.cc (Input::Input): Likewise.
+	* src/main.cc (main): Pass stdin to Input constructor.
+
+	* src/options.h (DEFAULTCHARS): Remove.
+	(Positions::MAX_KEY_POS): Set to 255.
+	(Positions::_positions): Increase array size.
+	(PositionIterator::EOS): Set to -1.
+	(PositionIterator::_index): Change type to 'unsigned int'.
+	* src/options.icc (Positions::Positions): Don't store
+	PositionIterator::EOS.
+	(PositionIterator::next): Produce PositionIterator::EOS here.
+	* src/options.cc (Options::long_usage): Use MAX_KEY_POS, not
+	MAX_KEY_POS-1.
+	(PositionStringParser): Rename field _size to _in_range. Rename
+	field _curr_value to _range_curr_value. Rename field _upper_bound
+	to _range_upper_bound.
+	(PositionStringParser::nextPosition): Comments.
+	(Options::Options): Update.
+	(Options::~Options): Update.
+	(long_options): Use NULL, not 0.
+	(Options::parse_options): Set BAD_VALUE to -2; -1 is now EOS. Bug fix:
+	Check against array overflow when more than MAX_KEY_POS positions are
+	given. Don't store PositionIterator::EOS.
+	Check against extra arguments before opening the input file.
+	* src/output.cc (Output::output_hash_function): Change test which
+	was for option[DEFAULTCHARS].
+	* tests/test-6.exp: Update.
+
+	* src/options.h (Options::get_delimiters): Renamed from
+	Options::get_delimiter.
+	* src/options.icc (Options::get_delimiters): Renamed from
+	Options::get_delimiter.
+	* src/input.cc (Input::read_keys): Update.
+
+	Bug fix.
+	* src/options.cc (Options::print_options): Escape backquote inside
+	double-quoted strings.
+
+	Bug fix.
+	* src/keyword.cc (KeywordExt::init_selchars): Avoid comparison with
+	uninitialized member variable. Found with 'valgrind'.
+
+	* src/version.cc: Include version.h.
+	* src/Makefile.in (OBJECTS): Reorder.
+	(KEYWORD_H, KEYWORD_LIST_H, INPUT_H, SEARCH_H, OUTPUT_H): New
+	variables.
+	(HASH_TABLE_H): Update.
+	(options.o, read-line.o, keyword.o, keyword-list.o, input.o, search.o,
+	output.o, main.o): Update dependencies.
+
+	* src/vectors.h: Remove file.
+	* src/vectors.cc: Remove file.
+	* src/search.h: Don't include vectors.h.
+	(Search): Don't inherit from Vectors. New fields _alpha_size,
+	_occurrences, _asso_values.
+	(Search::_determined, Search::get_occurrence, Search::set_determined,
+	Search::already_determined, Search::hash, Search::sort_set): Make
+	nonstatic.
+	* src/search.cc (Search::Search): Initialize _alpha_size, _occurrences,
+	_asso_values, _determined.
+	(Search::optimize, Search::~Search): Update.
+	* src/output.h: Don't include vectors.h.
+	(Output): Remove field _v. New fields _alpha_size, _occurrences,
+	_asso_values.
+	(Output::Output): Replace Vectors* argument with alpha_size,
+	occurrences, asso_values.
+	* src/output.cc (Output::Output): Replace Vectors* argument with
+	alpha_size, occurrences, asso_values.
+	(Output::output_hash_function): Update.
+	* src/main.cc (main): Don't set Vectors::ALPHA_SIZE.
+	Pass _alpha_size, _occurrences, _asso_values from Search to Output.
+	* src/keyword.h: Don't include vectors.h.
+	* src/Makefile.in (OBJECTS): Remove vectors.o.
+	(VECTORS_H): Remove variable.
+	(vectors.o): Remove rule.
+
+	* src/search.h: New file, combines src/key-list.h, src/gen-perf.h.
+	* src/search,cc: New file, combines src/key-list.cc, src/gen-perf.cc.
+	* src/key-list.h: Remove file.
+	* src/key-list.cc: Remove file.
+	* src/gen-perf.h: Remove file.
+	* src/gen-perf.cc: Remove file.
+	* src/main.cc (KeywordExt_Factory): Moved here from gen-perf.cc.
+	(main): Inline some code from gen-perf.cc.
+	* src/keyword.h (KeywordExt::init_selchars): Take the occurrences
+	vector as argument.
+	* src/keyword.cc (KeywordExt::init_selchars): Take the occurrences
+	vector as argument.
+	* src/input.cc (Input::set_output_types): Initialize _array_type,
+	_return_type, _struct_tag.
+	(Input::read_keys): Initialize _additional_code.
+	* src/Makefile.in (OBJECTS): Add search.o.
+	Remove key-list.o, gen-perf.o.
+	(KEY_LIST_H, GEN_PERF_H): Remove variables.
+	(gen-perf.o, key-list.o): Remove rules.
+	(search.o): New rule.
+
+	* *, */*: Update copyright notice to GPL version 2.
+
+	* src/keyword-list.h (Keyword_List): New class.
+	(KeywordExt_List): Inherit from it.
+	* src/keyword-list.cc (Keyword_List::Keyword_List): New constructor.
+	(KeywordExt_List::KeywordExt_List): Update.
+	* src/input.h (Input::Input): Add Keyword_Factory argument.
+	(Input::_factory): New field.
+	(Input::_head): Change type to Keyword_List*.
+	(Input::parse_line): New declaration.
+	* src/input.cc (Input::Input): New constructor.
+	(Input::parse_line): Renamed from parse_line. Use the _factory.
+	(Input::read_keys): Update.
+	* src/key-list.cc (KeywordExt_Factory): New class.
+	(Key_List::read_keys): Pass a KeywordExt_Factory as Input constructor
+	argument.
+
+	Avoid g++ -Wold-style-cast warnings.
+	* src/bool-array.icc: Use new-style casts.
+	* src/gen-perf.cc: Likewise.
+	* src/input.cc: Likewise.
+	* src/key-list.cc: Likewise.
+	* src/keyword.cc: Likewise.
+	* src/options.cc: Likewise.
+	* src/output.cc: Likewise.
+	* src/hash-table.cc: Likewise. Remove (char *) cast in memset argument.
+
+	* src/keyword-list.h (KeywordExt_List): Don't inherit from KeywordExt.
+	(KeywordExt_List::KeywordExt_List): Take a KeywordExt* as argument.
+	(KeywordExt_List::_car): New field.
+	(KeywordExt_List::first): Use it.
+	* src/keyword-list.cc (KeywordExt_List::KeywordExt_List): Take a
+	KeywordExt* as argument.
+	* src/input.cc (parse_line): Create the KeywordExt separately.
+
+	Start using bool.
+	* src/bool-array.h (Bool_Array::set_bit): Change return type to bool.
+	* src/bool-array.icc (Bool_Array::set_bit): Likewise.
+	* src/gen-perf.h (Gen_Perf::affects_prev): Likewise.
+	* src/gen-perf.cc (Gen_Perf::affects_prev): Likewise.
+	* src/hash-table.h (Hash_Table::_ignore_length): Change type to bool.
+	(Hash_Table::Hash_Table): Change 3rd argument type to bool.
+	* src/hash-table.cc (Hash_Table::Hash_Table): Likewise.
+	* src/input.h (Input::_additional_code): Change type to bool.
+	* src/input.cc (Input::read_keys): Update.
+	* src/key-list.h (Key_List::_occurrence_sort, Key_List::_hash_sort,
+	Key_List::_additional_code): Change type to bool.
+	(Key_List::_determined): Change element type to bool.
+	(Key_List::already_determined): Change return type to bool.
+	* src/key-list.cc (Key_List::_determined): Change element type to bool.
+	(Key_List::set_determined): Update.
+	(Key_List::already_determined): Change return type to bool.
+	(Key_List::reorder, Key_List::sort, Key_List::Key_List): Update.
+	* src/options.h (Positions::sort): Change return type to bool.
+	(Options::operator[]): Likewise.
+	* src/options.icc (Positions::sort): Change return type to bool.
+	(Options::operator[]): Likewise.
+	* src/output.h (Output::Output): Change 5th argument type to bool.
+	(Output::_additional_code): Change type to bool.
+	* src/output.cc (Output::Output): Change 5th argument type to bool.
+
+2002-10-16  Bruno Haible  <bruno at clisp.org>
+
+	* src/*.h: Align all member names at column 24.
+
+2002-10-15  Bruno Haible  <bruno at clisp.org>
+
+	* src/input.h: New file.
+	* src/input.cc: New file, extracted from key-list.cc.
+	* src/key-list.h (Key_List): Don't inherit from Read_Line.
+	(Key_List::get_special_input,
+	Key_List::save_include_src, Key_List::get_array_type,
+	Key_List::strcspn, Key_List::set_output_types): Remove methods.
+	* src/key-list.cc (Key_List::get_special_input,
+	Key_List::save_include_src, Key_List::get_array_type,
+	Key_List::strcspn, Key_List::set_output_types, parse_line): Move to
+	src/input.cc.
+	(Key_List::read_keys): Use Input::read_keys.
+	(Key_List::Key_List): Update.
+	* src/gen-perf.cc: Update.
+	* src/Makefile.in (OBJECTS): Add input.o.
+	(input.o): New rule.
+
+2002-10-14  Bruno Haible  <bruno at clisp.org>
+
+	* src/options.cc: Don't include "vector.h".
+	(Options::parse_options): Don't initialize Vectors::ALPHA_SIZE here.
+	* src/vectors.cc (Vectors::ALPHA_SIZE): Don't initialize here.
+	* src/gen-perf.cc (Gen_Perf::Gen_Perf): Initialize Vectors::ALPHA_SIZE.
+
+	* src/options.h (Positions): New class.
+	(PositionIterator): New class.
+	(Options::parse_options): Renamed from Options::operator().
+	(Options::get_asso_max, Options::set_asso_max): Move to class Key_List.
+	(Options::reset, Options::get): Remove, replaced by class
+	PositionIterator.
+	(Options::get_initial_asso_value): Renamed from Options::initial_value.
+	(Options::key_sort): Remove, replaced by Positions::sort.
+	(Options): Make all fields and methods non-static.
+	* src/options.icc (Positions::Positions, Positions::operator[],
+	Positions::get_size, Positions::pointer, Positions::set_size,
+	Positions::sort, PositionIterator::PositionIterator,
+	PositionIterator::next): New methods.
+	(Options::get_initial_asso_value): Renamed from Options::initial_value.
+	(Options::get_size_multiple): New method.
+	(Options::get_key_positions): New method.
+	(Options::get_max_keysig_size): Implement using _key_positions.
+	* src/options.cc (Options::long_usage): Split big string into small
+	pieces.
+	(PositionStringParser): Prefix field names with _.
+	(Options::Options): Update.
+	(Options::~Options): Fix explanation of of _size_multiple. Don't print
+	_key_positions if it is effectively ignored.
+	(Options::parse_options): Renamed from Options::operator(). Update.
+	* src/key-list.h (Key_List): New field _size. New methods get_asso_max,
+	set_asso_max, get_max_keysig_size.
+	* src/key-list.cc (Key_List::read_keys): Don't make side effects on
+	options.
+	(Key_List::dump): Use Key_List::get_max_keysig_size() instead of
+	Options::get_max_keysig_size().
+	(Key_List::get_max_keysig_size): New function.
+	* src/hash-table.cc (Hash_Table::~Hash_Table): Compute the field
+	width on the fly if option[ALLCHARS].
+	* src/gen-perf.cc (Gen_Perf::Gen_Perf): Update,
+	Use Options::get_size_multiple() instead of Options::get_asso_max().
+	Use Key_List::get_asso_max() instead of Options::get_asso_max(). Use
+	Key_List::get_max_keysig_size() instead of
+	Options::get_max_keysig_size().
+	(Gen_Perf::affects_prev): Likewise.
+	(Gen_Perf::change): Likewise.
+	* src/keyword.cc: Update.
+	* src/main.cc: Update.
+	* src/output.cc: Update.
+	* tests/test-6.exp: Update.
+
+2002-10-13  Bruno Haible  <bruno at clisp.org>
+
+	* src/bool-array.*: Some polishing.
+
+	* src/options.h (Options::operator=, Options::operator!=): Remove
+	unused methods.
+	* src/options.icc (Options::operator=, Options::operator!=): Remove.
+
+	* src/*.h: Prefix all field names with _.
+	* src/*.cc, src/*.icc: Update.
+
+	* src/*: Simplify declarations of functions without arguments.
+
+2002-10-04  Bruno Haible  <bruno at clisp.org>
+
+	* src/output.h: New file, extracted from key-list.h.
+	* src/output.cc: New file, extracted from key-list.cc.
+	* src/key-list.h (Key_List): Make some fields protected. Move output
+	routines to src/output.h.
+	* src/key-list.cc: Move output routines to src/output.cc.
+	* src/gen-perf.cc (Gen_Perf::doit_all): Use class Output.
+	* src/Makefile.in (OBJECTS): Add output.o.
+	(output.o): New rule.
+
+2002-10-03  Bruno Haible  <bruno at clisp.org>
+
+	* src/iterator.h: Remove file.
+	* src/iterator.cc: Remove file.
+	* src/options.cc: (PositionStringParser): New class, taken from old
+	iterator.cc.
+	* src/Makefile.in (OBJECTS): Remove iterator.o.
+	(ITERATOR_H): Remove variable.
+	(iterator.o): Remove rule.
+
+	* src/keyword-list.h: New file.
+	* src/keyword-list.cc: New file.
+	* src/list-node.h: Remove file.
+	* src/list-node.cc: Remove file.
+	* src/keyword.h (KeywordExt::init_selchars): New declaration.
+	* src/keyword.cc (sort_char_set, KeywordExt::init_selchars): New, from
+	old list-node.cc.
+	* src/gen-perf.cc: Replace List_Node by KeywordExt or KeywordExt_List,
+	as appropriate.
+	* src/hash-table.h: Likewise.
+	* src/key-list.h: Likewise.
+	* src/key-list.cc: Likewise.
+	* src/Makefile.in (OBJECTS): Remove list-node.o, add keyword-list.o.
+	(LIST_NODE_H): Remove macro.
+	(list-node.o): Remove rule.
+	(keyword-list.o): New rule.
+
+	* src/keyword.h (KeywordExt): New class.
+	* src/keyword.cc (KeywordExt): New constructor.
+	* src/list-node.h (List_Node): Inherit from KeywordExt.
+	* src/list-node.cc: Update.
+	* src/gen-perf.cc: Update.
+	* src/hash-table.cc: Update.
+	* src/key-list.cc: Update.
+	(output_keyword_entry): Change argument type to KeywordExt*.
+
+	* src/keyword.h: New file.
+	* src/keyword.cc: New file.
+	* src/list-node.h (List_Node): Extend Keyword.
+	* src/list-node.cc: Update.
+	* src/gen-perf.cc: Update.
+	* src/hash-table.cc: Update.
+	* src/key-list.cc: Update.
+	* src/Makefile.in (OBJECTS): Add keyword.o.
+	(keyword.o): New rule.
+
+	* src/key-list.cc (Key_List::read_keys): Allocate the memory for the
+	hash table using 'new'.
+	(Key_List::output_lookup_array): Allocate the memory for the duplicates
+	array using 'new'.
+	* src/options.h (LARGE_STACK_ARRAYS): Remove definition.
+	* src/main.cc (main): Remove setrlimit call.
+	* src/configure.in: Don't test for unistd.h, sys/time.h,
+	sys/resource.h, getrlimit, setrlimit.
+
+	* src/bool-array.h (Bool_Array): Make all members non-static.
+	Add an argument to the constructor. Remove init(), rename reset() to
+	clear(), rename find() to set_bit().
+	* src/bool-array.icc: Move init() code into the constructor.
+	Rename reset() to clear(), rename find() to set_bit().
+	* src/gen-perf.h (Gen_Perf): Add collision_detector member.
+	* src/gen-perf.cc: Update.
+
+	* src/gen-perf.h (Gen_Perf::doit_all): Renamed from
+	Gen_Perf::operator ().
+	* src/gen-perf.cc (Gen_Perf::doit_all): Renamed from
+	Gen_Perf::operator ().
+	* src/main.cc: Update.
+
+	* src/read-line.h (Read_Line::read_next_line): Renamed from
+	Read_Line::get_line.
+	* src/read-line.icc: Likewise.
+	* src/read-line.cc: Update.
+	* src/key-list.cc: Update.
+
+	* lib/getline.h: New file.
+	* lib/getline.cc: New file.
+	* lib/Makefile.in (OBJECTS): Add getline.o.
+	(getline.o): New rule.
+	* src/read-line.h (Read_Line::readln_aux): Remove declaration.
+	* src/read-line.cc (Read_Line::readln_aux): Remove function.
+	* src/read-line.icc (Read_Line::get_line): Use ::get_line.
+	* src/options.h (LARGE_STACK): Remove macro.
+
+	* src/bool-array.h (STORAGE_TYPE): Remove type.
+	Use 'unsigned int' instead of STORAGE_TYPE.
+	* src/bool-array.cc: Likewise.
+	* src/bool-array.icc: Likewise.
+	* src/gen-perf.cc: Likewise.
+
+	* src/new.cc: Remove file.
+	* src/Makefile.in (OBJECTS): Remove new.o.
+	(new.o): Remove rule.
+	* src/configure.in: Remove test for HAVE_THROW_DECL.
+	* acconfig.h: Remove file.
+
+	* src/trace.h: Remove file.
+	* src/trace.cc: Remove file.
+	* src/Makefile.in (OBJECTS): Remove trace.o.
+	(TRACE_H): Remove variable.
+	(trace.o): Remove rule.
+	Update all dependencies.
+	* src/bool-array.h, src/bool-array.cc, src/bool-array.icc: Don't use T.
+	* src/gen-perf.cc: Likewise.
+	* src/hash-table.cc: Likewise.
+	* src/iterator.cc: Likewise.
+	* src/key-list.cc: Likewise.
+	* src/list-node.cc: Likewise.
+	* src/main.cc: Likewise.
+	* src/new.cc: Likewise.
+	* src/options.h, src/options.cc, src/options.icc: Likewise.
+	* src/read-line.h, src/read-line.cc, src/read-line.icc: Likewise.
+
+	* tests/Makefile.in: Use gperf option -I, to avoid gcc-3.x warnings.
+	* tests/test.c: Don't use gets(), to avoid warnings.
+
+2001-08-02  Bruno Haible  <bruno at linuix.math.u-bordeaux.fr>
+
+	* doc/gperf.texi: Change bug report address to <bug-gnu-gperf at gnu.org>.
+	* README: Updated.
+
+2000-12-18  Bruno Haible  <bruno at linuix.math.u-bordeaux.fr>
+
+        * src/configure.in: Add check for rand() in libm. Needed for BeOS.
+        * src/Makefile.in (LIBS): Use @GPERF_LIBM@ instead of hardwiring -lm.
+
+2000-11-20  Bruno Haible  <bruno at linuix.math.u-bordeaux.fr>
+
+        * doc/help2man: Update to version 1.23.
+
 2000-09-26  Bruno Haible  <bruno at linuix.math.u-bordeaux.fr>
 
         * gperf-2.7.2 released.
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/FREEBSD-Xlist
--- a/head/contrib/gperf/FREEBSD-Xlist	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/contrib/gperf/FREEBSD-Xlist	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-$FreeBSD$
+$FreeBSD: head/contrib/gperf/FREEBSD-Xlist 228068 2011-11-28 14:23:09Z bapt $
 */*.dvi
 */*.html
 */*.info
@@ -6,3 +6,7 @@
 */texinfo.tex
 */tests
 */getopt*
+*/*.pdf
+*/*.vms
+*/*.msvc
+*/*.woe32
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/INSTALL
--- a/head/contrib/gperf/INSTALL	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/contrib/gperf/INSTALL	Tue Dec 06 20:26:16 2011 +0200
@@ -19,8 +19,8 @@
 be considered for the next release.  If at some point `config.cache'
 contains results you don't want to keep, you may remove or edit it.
 
-   The file `configure.in' is used to create `configure' by a program
-called `autoconf'.  You only need `configure.in' if you want to change
+   The file `configure.ac' is used to create `configure' by a program
+called `autoconf'.  You only need `configure.ac' if you want to change
 it or regenerate `configure' using a newer version of `autoconf'.
 
 The simplest way to compile this package is:
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/Makefile.devel
--- a/head/contrib/gperf/Makefile.devel	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/contrib/gperf/Makefile.devel	Tue Dec 06 20:26:16 2011 +0200
@@ -4,32 +4,38 @@
 SHELL = /bin/sh
 MAKE = make
 
-all : configures src/config.h.in doc/gperf.1
+all : configures src/config.h.in src/config.h.msvc src/config.h_vms doc/gperf.1
 
 CONFIGURES = configure lib/configure src/configure tests/configure doc/configure
 
 configures : $(CONFIGURES)
 
-configure : configure.in aclocal.m4
-	autoconf -l .
+configure : configure.ac aclocal.m4
+	autoconf -I .
 
-lib/configure : lib/configure.in aclocal.m4
-	cd lib && autoconf -l ..
+lib/configure : lib/configure.ac aclocal.m4
+	cd lib && autoconf -I ..
 
-src/configure : src/configure.in aclocal.m4
-	cd src && autoconf -l ..
+src/configure : src/configure.ac aclocal.m4
+	cd src && autoconf -I ..
 
-tests/configure : tests/configure.in aclocal.m4
-	cd tests && autoconf -l ..
+tests/configure : tests/configure.ac aclocal.m4
+	cd tests && autoconf -I ..
 
-doc/configure : doc/configure.in aclocal.m4
-	cd doc && autoconf -l ..
+doc/configure : doc/configure.ac aclocal.m4
+	cd doc && autoconf -I ..
 
 check-configures : $(CONFIGURES)
 	set -e; for f in $(CONFIGURES); do bash -x -n $$f; done
 
-src/config.h.in : src/configure.in aclocal.m4
-	cd src && autoheader -l ..
+src/config.h.in : src/configure.ac aclocal.m4
+	cd src && autoheader -I ..
+
+src/config.h.msvc : src/config.h.in
+	cp src/config.h.in src/config.h.msvc
+
+src/config.h_vms : src/config.h.in
+	cp src/config.h.in src/config.h_vms
 
 doc/gperf.1 : force
 	prog=`PATH=build/src:src:$$PATH which gperf`; if test -n "$$prog"; then doc/help2man --name='generate a perfect hash function from a key set' --section=1 $$prog > doc/gperf.1; fi
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/Makefile.in
--- a/head/contrib/gperf/Makefile.in	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/contrib/gperf/Makefile.in	Tue Dec 06 20:26:16 2011 +0200
@@ -1,13 +1,14 @@
 # Makefile for gperf
 
-# Copyright (C) 1989, 1992, 1993, 1998 Free Software Foundation, Inc.
-# written by Douglas C. Schmidt (schmidt at ics.uci.edu)
+# Copyright (C) 1989, 1992, 1993, 1998, 2002 Free Software Foundation, Inc.
+# Written by Douglas C. Schmidt <schmidt at ics.uci.edu>
+# and Bruno Haible <bruno at clisp.org>.
 #
 # This file is part of GNU GPERF.
 #
 # GNU GPERF 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 1, or (at your option)
+# the Free Software Foundation; either version 2, or (at your option)
 # any later version.
 #
 # GNU GPERF is distributed in the hope that it will be useful,
@@ -16,8 +17,9 @@
 # GNU General Public License for more details.
 #
 # You should have received a copy of the GNU General Public License
-# along with GNU GPERF; see the file COPYING.  If not, write to
-# Software Foundation, 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+# along with this program; see the file COPYING.
+# If not, write to the Free Software Foundation, Inc.,
+# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
 
 #### Start of system configuration section. ####
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/NEWS
--- a/head/contrib/gperf/NEWS	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/contrib/gperf/NEWS	Tue Dec 06 20:26:16 2011 +0200
@@ -1,3 +1,73 @@
+New in 3.0.3:
+
+* The generated C code is compatible with gcc-4.3.x in c99 or gnu99 mode.
+
+New in 3.0.2:
+
+* Compiles with g++-4.0.x.
+* Added option --length-table-name.
+* Added declaration %define length-table-name.
+* Fixed  #line directives for filenames containing backslashes.
+
+New in 3.0.1:
+
+* Bug fix.
+
+New in 3.0:
+
+* Added option --output that allows to specify the output file name.
+* Some options have been renamed:
+    --hash-fn-name=NAME     -->   --hash-function-name=NAME
+    --lookup-fn-name=NAME   -->   --lookup-function-name=NAME
+    --compare-strlen        -->   --compare-lengths
+    --global                -->   --global-table
+  The older variants are still supported for backward compatibility.
+* The following options can now be specified inside the input file:
+    %delimiters=DELIMITER-LIST
+    %struct-type
+    %ignore-case
+    %language=LANGUAGE-NAME
+    %define slot-name NAME
+    %define initializer-suffix INITIALIZERS
+    %define hash-function-name NAME
+    %define lookup-function-name NAME
+    %define class-name NAME
+    %7bit
+    %compare-lengths
+    %compare-strncmp
+    %readonly-tables
+    %enum
+    %includes
+    %global-table
+    %pic
+    %define string-pool-name NAME
+    %null-strings
+    %define word-array-name NAME
+    %switch=COUNT
+    %omit-struct-type
+* When the option -k is not given, the default key positions are now
+  computed depending on the set of keywords.
+* If the input file is given by name, the output file will now contain
+  #line directives referring to the input file.
+* Some keyword sets containing permutations, like { "xy", "yx", "xz", "zx" }
+  or { "abc", "acb", "bca", "cab" }, are now handled by gperf without
+  requiring the option -D.
+* The generated table is usually much smaller than it was with earlier
+  versions of gperf.
+* Added option -m/--multiple-iterations that allows to further reduce the
+  size of the generated table.
+* When the search for a good hash function is not immediately successful,
+  the table's size will grow as needed. Earlier versions of gperf bailed
+  out with an "Internal error, duplicate hash code value".
+* The options -f/--fast and -o/--occurrence-sort have no effect any more.
+* Added options -P/--pic and --null-strings that optimize the generated code
+  for use in shared libraries. -P/--pic does a perfect optimization but may
+  require some small code changes (see the documentation for details), whereas
+  --null-strings does only a half-hearted optimization but works without
+  needing any change to surrounding code.
+* Added option --ignore-case that produces a case independent lookup function.
+* Bug fixes.
+
 New in 2.7.2:
 
 * Keywords may now be enclosed in double quotes; this permits the use of
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/README
--- a/head/contrib/gperf/README	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/contrib/gperf/README	Tue Dec 06 20:26:16 2011 +0200
@@ -22,8 +22,7 @@
 ftp://ftp.gnu.org/pub/gnu/standards.*, especially the 'Makefile
 Conventions', 'Configuration', and 'User Interfaces' sections.
 
-Mail suggestions and bug reports to both <bug-gnu-utils at gnu.org> and
-<gperf-bugs at lists.sourceforge.net>.  When reporting bugs, please
-include in the subject line the package name and version (output of
-'gperf --version') for which you found a problem.
+Mail suggestions and bug reports to <bug-gnu-gperf at gnu.org>.  When
+reporting bugs, please include in the subject line the package name
+and version (output of 'gperf --version') for which you found a problem.
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/acconfig.h
--- a/head/contrib/gperf/acconfig.h	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,4 +0,0 @@
-
-/* Define if the C++ compiler supports "throw ()" declarations.  */
-#undef HAVE_THROW_DECL
-
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/aclocal.m4
--- a/head/contrib/gperf/aclocal.m4	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/contrib/gperf/aclocal.m4	Tue Dec 06 20:26:16 2011 +0200
@@ -1,7 +1,5 @@
 AC_PREREQ(2.12)
 
-AC_DEFUN(CL_PROG_RANLIB, [AC_CHECK_PROG(RANLIB, ranlib, ranlib, true)])
-
 AC_DEFUN(CL_PROG_INSTALL,
 [dnl This is mostly copied from AC_PROG_INSTALL.
 # Find a good install program.  We prefer a C program (faster),
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/configure
--- a/head/contrib/gperf/configure	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/contrib/gperf/configure	Tue Dec 06 20:26:16 2011 +0200
@@ -1,26 +1,637 @@
 #! /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.
+# Generated by GNU Autoconf 2.61.
 #
+# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001,
+# 2002, 2003, 2004, 2005, 2006 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=
+## --------------------- ##
+## M4sh Initialization.  ##
+## --------------------- ##
+
+# Be more Bourne compatible
+DUALCASE=1; export DUALCASE # for MKS sh
+if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
+  emulate sh
+  NULLCMD=:
+  # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
+  # is contrary to our usage.  Disable this feature.
+  alias -g '${1+"$@"}'='"$@"'
+  setopt NO_GLOB_SUBST
+else
+  case `(set -o) 2>/dev/null` in
+  *posix*) set -o posix ;;
+esac
+
+fi
+
+
+
+
+# PATH needs CR
+# Avoid depending upon Character Ranges.
+as_cr_letters='abcdefghijklmnopqrstuvwxyz'
+as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
+as_cr_Letters=$as_cr_letters$as_cr_LETTERS
+as_cr_digits='0123456789'
+as_cr_alnum=$as_cr_Letters$as_cr_digits
+
+# The user is always right.
+if test "${PATH_SEPARATOR+set}" != set; then
+  echo "#! /bin/sh" >conf$$.sh
+  echo  "exit 0"   >>conf$$.sh
+  chmod +x conf$$.sh
+  if (PATH="/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then
+    PATH_SEPARATOR=';'
+  else
+    PATH_SEPARATOR=:
+  fi
+  rm -f conf$$.sh
+fi
+
+# Support unset when possible.
+if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then
+  as_unset=unset
+else
+  as_unset=false
+fi
+
+
+# IFS
+# We need space, tab and new line, in precisely that order.  Quoting is
+# there to prevent editors from complaining about space-tab.
+# (If _AS_PATH_WALK were called with IFS unset, it would disable word
+# splitting by setting IFS to empty value.)
+as_nl='
+'
+IFS=" ""	$as_nl"
+
+# Find who we are.  Look in the path if we contain no directory separator.
+case $0 in
+  *[\\/]* ) as_myself=$0 ;;
+  *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+  test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break
+done
+IFS=$as_save_IFS
+
+     ;;
+esac
+# We did not find ourselves, most probably we were run as `sh COMMAND'
+# in which case we are not to be found in the path.
+if test "x$as_myself" = x; then
+  as_myself=$0
+fi
+if test ! -f "$as_myself"; then
+  echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2
+  { (exit 1); exit 1; }
+fi
+
+# Work around bugs in pre-3.0 UWIN ksh.
+for as_var in ENV MAIL MAILPATH
+do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var
+done
+PS1='$ '
+PS2='> '
+PS4='+ '
+
+# NLS nuisances.
+for as_var in \
+  LANG LANGUAGE LC_ADDRESS LC_ALL LC_COLLATE LC_CTYPE LC_IDENTIFICATION \
+  LC_MEASUREMENT LC_MESSAGES LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER \
+  LC_TELEPHONE LC_TIME
+do
+  if (set +x; test -z "`(eval $as_var=C; export $as_var) 2>&1`"); then
+    eval $as_var=C; export $as_var
+  else
+    ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var
+  fi
+done
+
+# Required to use basename.
+if expr a : '\(a\)' >/dev/null 2>&1 &&
+   test "X`expr 00001 : '.*\(...\)'`" = X001; then
+  as_expr=expr
+else
+  as_expr=false
+fi
+
+if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then
+  as_basename=basename
+else
+  as_basename=false
+fi
+
+
+# Name of the executable.
+as_me=`$as_basename -- "$0" ||
+$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
+	 X"$0" : 'X\(//\)$' \| \
+	 X"$0" : 'X\(/\)' \| . 2>/dev/null ||
+echo X/"$0" |
+    sed '/^.*\/\([^/][^/]*\)\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\/\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\/\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+
+# CDPATH.
+$as_unset CDPATH
+
+
+if test "x$CONFIG_SHELL" = x; then
+  if (eval ":") 2>/dev/null; then
+  as_have_required=yes
+else
+  as_have_required=no
+fi
+
+  if test $as_have_required = yes && 	 (eval ":
+(as_func_return () {
+  (exit \$1)
+}
+as_func_success () {
+  as_func_return 0
+}
+as_func_failure () {
+  as_func_return 1
+}
+as_func_ret_success () {
+  return 0
+}
+as_func_ret_failure () {
+  return 1
+}
+
+exitcode=0
+if as_func_success; then
+  :
+else
+  exitcode=1
+  echo as_func_success failed.
+fi
+
+if as_func_failure; then
+  exitcode=1
+  echo as_func_failure succeeded.
+fi
+
+if as_func_ret_success; then
+  :
+else
+  exitcode=1
+  echo as_func_ret_success failed.
+fi
+
+if as_func_ret_failure; then
+  exitcode=1
+  echo as_func_ret_failure succeeded.
+fi
+
+if ( set x; as_func_ret_success y && test x = \"\$1\" ); then
+  :
+else
+  exitcode=1
+  echo positional parameters were not saved.
+fi
+
+test \$exitcode = 0) || { (exit 1); exit 1; }
+
+(
+  as_lineno_1=\$LINENO
+  as_lineno_2=\$LINENO
+  test \"x\$as_lineno_1\" != \"x\$as_lineno_2\" &&
+  test \"x\`expr \$as_lineno_1 + 1\`\" = \"x\$as_lineno_2\") || { (exit 1); exit 1; }
+") 2> /dev/null; then
+  :
+else
+  as_candidate_shells=
+    as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+  case $as_dir in
+	 /*)
+	   for as_base in sh bash ksh sh5; do
+	     as_candidate_shells="$as_candidate_shells $as_dir/$as_base"
+	   done;;
+       esac
+done
+IFS=$as_save_IFS
+
+
+      for as_shell in $as_candidate_shells $SHELL; do
+	 # Try only shells that exist, to save several forks.
+	 if { test -f "$as_shell" || test -f "$as_shell.exe"; } &&
+		{ ("$as_shell") 2> /dev/null <<\_ASEOF
+if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
+  emulate sh
+  NULLCMD=:
+  # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
+  # is contrary to our usage.  Disable this feature.
+  alias -g '${1+"$@"}'='"$@"'
+  setopt NO_GLOB_SUBST
+else
+  case `(set -o) 2>/dev/null` in
+  *posix*) set -o posix ;;
+esac
+
+fi
+
+
+:
+_ASEOF
+}; then
+  CONFIG_SHELL=$as_shell
+	       as_have_required=yes
+	       if { "$as_shell" 2> /dev/null <<\_ASEOF
+if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
+  emulate sh
+  NULLCMD=:
+  # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
+  # is contrary to our usage.  Disable this feature.
+  alias -g '${1+"$@"}'='"$@"'
+  setopt NO_GLOB_SUBST
+else
+  case `(set -o) 2>/dev/null` in
+  *posix*) set -o posix ;;
+esac
+
+fi
+
+
+:
+(as_func_return () {
+  (exit $1)
+}
+as_func_success () {
+  as_func_return 0
+}
+as_func_failure () {
+  as_func_return 1
+}
+as_func_ret_success () {
+  return 0
+}
+as_func_ret_failure () {
+  return 1
+}
+
+exitcode=0
+if as_func_success; then
+  :
+else
+  exitcode=1
+  echo as_func_success failed.
+fi
+
+if as_func_failure; then
+  exitcode=1
+  echo as_func_failure succeeded.
+fi
+
+if as_func_ret_success; then
+  :
+else
+  exitcode=1
+  echo as_func_ret_success failed.
+fi
+
+if as_func_ret_failure; then
+  exitcode=1
+  echo as_func_ret_failure succeeded.
+fi
+
+if ( set x; as_func_ret_success y && test x = "$1" ); then
+  :
+else
+  exitcode=1
+  echo positional parameters were not saved.
+fi
+
+test $exitcode = 0) || { (exit 1); exit 1; }
+
+(
+  as_lineno_1=$LINENO
+  as_lineno_2=$LINENO
+  test "x$as_lineno_1" != "x$as_lineno_2" &&
+  test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2") || { (exit 1); exit 1; }
+
+_ASEOF
+}; then
+  break
+fi
+
+fi
+
+      done
+
+      if test "x$CONFIG_SHELL" != x; then
+  for as_var in BASH_ENV ENV
+        do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var
+        done
+        export CONFIG_SHELL
+        exec "$CONFIG_SHELL" "$as_myself" ${1+"$@"}
+fi
+
+
+    if test $as_have_required = no; then
+  echo This script requires a shell more modern than all the
+      echo shells that I found on your system.  Please install a
+      echo modern shell, or manually run the script under such a
+      echo shell if you do have one.
+      { (exit 1); exit 1; }
+fi
+
+
+fi
+
+fi
+
+
+
+(eval "as_func_return () {
+  (exit \$1)
+}
+as_func_success () {
+  as_func_return 0
+}
+as_func_failure () {
+  as_func_return 1
+}
+as_func_ret_success () {
+  return 0
+}
+as_func_ret_failure () {
+  return 1
+}
+
+exitcode=0
+if as_func_success; then
+  :
+else
+  exitcode=1
+  echo as_func_success failed.
+fi
+
+if as_func_failure; then
+  exitcode=1
+  echo as_func_failure succeeded.
+fi
+
+if as_func_ret_success; then
+  :
+else
+  exitcode=1
+  echo as_func_ret_success failed.
+fi
+
+if as_func_ret_failure; then
+  exitcode=1
+  echo as_func_ret_failure succeeded.
+fi
+
+if ( set x; as_func_ret_success y && test x = \"\$1\" ); then
+  :
+else
+  exitcode=1
+  echo positional parameters were not saved.
+fi
+
+test \$exitcode = 0") || {
+  echo No shell found that supports shell functions.
+  echo Please tell autoconf at gnu.org about your system,
+  echo including any error possibly output before this
+  echo message
+}
+
+
+
+  as_lineno_1=$LINENO
+  as_lineno_2=$LINENO
+  test "x$as_lineno_1" != "x$as_lineno_2" &&
+  test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2" || {
+
+  # Create $as_me.lineno as a copy of $as_myself, but with $LINENO
+  # uniformly replaced by the line number.  The first 'sed' inserts a
+  # line-number line after each line using $LINENO; the second 'sed'
+  # does the real work.  The second script uses 'N' to pair each
+  # line-number line with the line containing $LINENO, and appends
+  # trailing '-' during substitution so that $LINENO is not a special
+  # case at line end.
+  # (Raja R Harinath suggested sed '=', and Paul Eggert wrote the
+  # scripts with optimization help from Paolo Bonzini.  Blame Lee
+  # E. McMahon (1931-1989) for sed's syntax.  :-)
+  sed -n '
+    p
+    /[$]LINENO/=
+  ' <$as_myself |
+    sed '
+      s/[$]LINENO.*/&-/
+      t lineno
+      b
+      :lineno
+      N
+      :loop
+      s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/
+      t loop
+      s/-\n.*//
+    ' >$as_me.lineno &&
+  chmod +x "$as_me.lineno" ||
+    { echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2
+   { (exit 1); exit 1; }; }
+
+  # Don't try to exec as it changes $[0], causing all sort of problems
+  # (the dirname of $[0] is not the place where we might find the
+  # original and so on.  Autoconf is especially sensitive to this).
+  . "./$as_me.lineno"
+  # Exit status is that of the last command.
+  exit
+}
+
+
+if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then
+  as_dirname=dirname
+else
+  as_dirname=false
+fi
+
+ECHO_C= ECHO_N= ECHO_T=
+case `echo -n x` in
+-n*)
+  case `echo 'x\c'` in
+  *c*) ECHO_T='	';;	# ECHO_T is single tab character.
+  *)   ECHO_C='\c';;
+  esac;;
+*)
+  ECHO_N='-n';;
+esac
+
+if expr a : '\(a\)' >/dev/null 2>&1 &&
+   test "X`expr 00001 : '.*\(...\)'`" = X001; then
+  as_expr=expr
+else
+  as_expr=false
+fi
+
+rm -f conf$$ conf$$.exe conf$$.file
+if test -d conf$$.dir; then
+  rm -f conf$$.dir/conf$$.file
+else
+  rm -f conf$$.dir
+  mkdir conf$$.dir
+fi
+echo >conf$$.file
+if ln -s conf$$.file conf$$ 2>/dev/null; then
+  as_ln_s='ln -s'
+  # ... but there are two gotchas:
+  # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail.
+  # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable.
+  # In both cases, we have to default to `cp -p'.
+  ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe ||
+    as_ln_s='cp -p'
+elif ln conf$$.file conf$$ 2>/dev/null; then
+  as_ln_s=ln
+else
+  as_ln_s='cp -p'
+fi
+rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file
+rmdir conf$$.dir 2>/dev/null
+
+if mkdir -p . 2>/dev/null; then
+  as_mkdir_p=:
+else
+  test -d ./-p && rmdir ./-p
+  as_mkdir_p=false
+fi
+
+if test -x / >/dev/null 2>&1; then
+  as_test_x='test -x'
+else
+  if ls -dL / >/dev/null 2>&1; then
+    as_ls_L_option=L
+  else
+    as_ls_L_option=
+  fi
+  as_test_x='
+    eval sh -c '\''
+      if test -d "$1"; then
+        test -d "$1/.";
+      else
+	case $1 in
+        -*)set "./$1";;
+	esac;
+	case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in
+	???[sx]*):;;*)false;;esac;fi
+    '\'' sh
+  '
+fi
+as_executable_p=$as_test_x
+
+# Sed expression to map a string onto a valid CPP name.
+as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
+
+# Sed expression to map a string onto a valid variable name.
+as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'"
+
+
+
+exec 7<&0 </dev/null 6>&1
+
+# Name of the host.
+# hostname on some systems (SVR3.2, Linux) returns a bogus exit status,
+# so uname gets run too.
+ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q`
+
+#
+# Initializations.
+#
 ac_default_prefix=/usr/local
-# Any additions from configure.in:
+ac_clean_files=
+ac_config_libobj_dir=.
+LIBOBJS=
+cross_compiling=no
+subdirs=
+MFLAGS=
+MAKEFLAGS=
+SHELL=${CONFIG_SHELL-/bin/sh}
+
+# Identity of this package.
+PACKAGE_NAME=
+PACKAGE_TARNAME=
+PACKAGE_VERSION=
+PACKAGE_STRING=
+PACKAGE_BUGREPORT=
+
+ac_unique_file="doc/gperf.1"
+ac_subst_vars='SHELL
+PATH_SEPARATOR
+PACKAGE_NAME
+PACKAGE_TARNAME
+PACKAGE_VERSION
+PACKAGE_STRING
+PACKAGE_BUGREPORT
+exec_prefix
+prefix
+program_transform_name
+bindir
+sbindir
+libexecdir
+datarootdir
+datadir
+sysconfdir
+sharedstatedir
+localstatedir
+includedir
+oldincludedir
+docdir
+infodir
+htmldir
+dvidir
+pdfdir
+psdir
+libdir
+localedir
+mandir
+DEFS
+ECHO_C
+ECHO_N
+ECHO_T
+LIBS
+build_alias
+host_alias
+target_alias
+SET_MAKE
+subdirs
+LIBOBJS
+LTLIBOBJS'
+ac_subst_files=''
+      ac_precious_vars='build_alias
+host_alias
+target_alias'
+ac_subdirs_all='lib src tests doc'
 
 # Initialize some variables set by options.
+ac_init_help=
+ac_init_version=false
 # The variables have the same names as the options, with
 # dashes changed to underlines.
-build=NONE
-cache_file=./config.cache
+cache_file=/dev/null
 exec_prefix=NONE
-host=NONE
 no_create=
-nonopt=NONE
 no_recursion=
 prefix=NONE
 program_prefix=NONE
@@ -29,94 +640,117 @@
 silent=
 site=
 srcdir=
-target=NONE
 verbose=
 x_includes=NONE
 x_libraries=NONE
+
+# Installation directory options.
+# These are left unexpanded so users can "make install exec_prefix=/foo"
+# and all the variables that are supposed to be based on exec_prefix
+# by default will actually change.
+# Use braces instead of parens because sh, perl, etc. also accept them.
+# (The list follows the same order as the GNU Coding Standards.)
 bindir='${exec_prefix}/bin'
 sbindir='${exec_prefix}/sbin'
 libexecdir='${exec_prefix}/libexec'
-datadir='${prefix}/share'
+datarootdir='${prefix}/share'
+datadir='${datarootdir}'
 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
+docdir='${datarootdir}/doc/${PACKAGE}'
+infodir='${datarootdir}/info'
+htmldir='${docdir}'
+dvidir='${docdir}'
+pdfdir='${docdir}'
+psdir='${docdir}'
+libdir='${exec_prefix}/lib'
+localedir='${datarootdir}/locale'
+mandir='${datarootdir}/man'
 
 ac_prev=
+ac_dashdash=
 for ac_option
 do
-
   # If the previous option needs an argument, assign it.
   if test -n "$ac_prev"; then
-    eval "$ac_prev=\$ac_option"
+    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= ;;
+  case $ac_option in
+  *=*)	ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;;
+  *)	ac_optarg=yes ;;
   esac
 
   # Accept the important Cygnus configure options, so we can diagnose typos.
 
-  case "$ac_option" in
+  case $ac_dashdash$ac_option in
+  --)
+    ac_dashdash=yes ;;
 
   -bindir | --bindir | --bindi | --bind | --bin | --bi)
     ac_prev=bindir ;;
   -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*)
-    bindir="$ac_optarg" ;;
+    bindir=$ac_optarg ;;
 
   -build | --build | --buil | --bui | --bu)
-    ac_prev=build ;;
+    ac_prev=build_alias ;;
   -build=* | --build=* | --buil=* | --bui=* | --bu=*)
-    build="$ac_optarg" ;;
+    build_alias=$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)
+    cache_file=$ac_optarg ;;
+
+  --config-cache | -C)
+    cache_file=config.cache ;;
+
+  -datadir | --datadir | --datadi | --datad)
     ac_prev=datadir ;;
-  -datadir=* | --datadir=* | --datadi=* | --datad=* | --data=* | --dat=* \
-  | --da=*)
-    datadir="$ac_optarg" ;;
+  -datadir=* | --datadir=* | --datadi=* | --datad=*)
+    datadir=$ac_optarg ;;
+
+  -datarootdir | --datarootdir | --datarootdi | --datarootd | --dataroot \
+  | --dataroo | --dataro | --datar)
+    ac_prev=datarootdir ;;
+  -datarootdir=* | --datarootdir=* | --datarootdi=* | --datarootd=* \
+  | --dataroot=* | --dataroo=* | --dataro=* | --datar=*)
+    datarootdir=$ac_optarg ;;
 
   -disable-* | --disable-*)
-    ac_feature=`echo $ac_option|sed -e 's/-*disable-//'`
+    ac_feature=`expr "x$ac_option" : 'x-*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" ;;
+    expr "x$ac_feature" : ".*[^-._$as_cr_alnum]" >/dev/null &&
+      { echo "$as_me: error: invalid feature name: $ac_feature" >&2
+   { (exit 1); exit 1; }; }
+    ac_feature=`echo $ac_feature | sed 's/[-.]/_/g'`
+    eval enable_$ac_feature=no ;;
+
+  -docdir | --docdir | --docdi | --doc | --do)
+    ac_prev=docdir ;;
+  -docdir=* | --docdir=* | --docdi=* | --doc=* | --do=*)
+    docdir=$ac_optarg ;;
+
+  -dvidir | --dvidir | --dvidi | --dvid | --dvi | --dv)
+    ac_prev=dvidir ;;
+  -dvidir=* | --dvidir=* | --dvidi=* | --dvid=* | --dvi=* | --dv=*)
+    dvidir=$ac_optarg ;;
 
   -enable-* | --enable-*)
-    ac_feature=`echo $ac_option|sed -e 's/-*enable-//' -e 's/=.*//'`
+    ac_feature=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'`
     # 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'" ;;
+    expr "x$ac_feature" : ".*[^-._$as_cr_alnum]" >/dev/null &&
+      { echo "$as_me: error: invalid feature name: $ac_feature" >&2
+   { (exit 1); exit 1; }; }
+    ac_feature=`echo $ac_feature | sed 's/[-.]/_/g'`
+    eval enable_$ac_feature=\$ac_optarg ;;
 
   -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \
   | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \
@@ -125,116 +759,77 @@
   -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \
   | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \
   | --exec=* | --exe=* | --ex=*)
-    exec_prefix="$ac_optarg" ;;
+    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 ;;
+  -help | --help | --hel | --he | -h)
+    ac_init_help=long ;;
+  -help=r* | --help=r* | --hel=r* | --he=r* | -hr*)
+    ac_init_help=recursive ;;
+  -help=s* | --help=s* | --hel=s* | --he=s* | -hs*)
+    ac_init_help=short ;;
 
   -host | --host | --hos | --ho)
-    ac_prev=host ;;
+    ac_prev=host_alias ;;
   -host=* | --host=* | --hos=* | --ho=*)
-    host="$ac_optarg" ;;
+    host_alias=$ac_optarg ;;
+
+  -htmldir | --htmldir | --htmldi | --htmld | --html | --htm | --ht)
+    ac_prev=htmldir ;;
+  -htmldir=* | --htmldir=* | --htmldi=* | --htmld=* | --html=* | --htm=* \
+  | --ht=*)
+    htmldir=$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" ;;
+    includedir=$ac_optarg ;;
 
   -infodir | --infodir | --infodi | --infod | --info | --inf)
     ac_prev=infodir ;;
   -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*)
-    infodir="$ac_optarg" ;;
+    infodir=$ac_optarg ;;
 
   -libdir | --libdir | --libdi | --libd)
     ac_prev=libdir ;;
   -libdir=* | --libdir=* | --libdi=* | --libd=*)
-    libdir="$ac_optarg" ;;
+    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" ;;
+    libexecdir=$ac_optarg ;;
+
+  -localedir | --localedir | --localedi | --localed | --locale)
+    ac_prev=localedir ;;
+  -localedir=* | --localedir=* | --localedi=* | --localed=* | --locale=*)
+    localedir=$ac_optarg ;;
 
   -localstatedir | --localstatedir | --localstatedi | --localstated \
-  | --localstate | --localstat | --localsta | --localst \
-  | --locals | --local | --loca | --loc | --lo)
+  | --localstate | --localstat | --localsta | --localst | --locals)
     ac_prev=localstatedir ;;
   -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \
-  | --localstate=* | --localstat=* | --localsta=* | --localst=* \
-  | --locals=* | --local=* | --loca=* | --loc=* | --lo=*)
-    localstatedir="$ac_optarg" ;;
+  | --localstate=* | --localstat=* | --localsta=* | --localst=* | --locals=*)
+    localstatedir=$ac_optarg ;;
 
   -mandir | --mandir | --mandi | --mand | --man | --ma | --m)
     ac_prev=mandir ;;
   -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*)
-    mandir="$ac_optarg" ;;
+    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-cr | --no-c | -n)
     no_create=yes ;;
 
   -no-recursion | --no-recursion | --no-recursio | --no-recursi \
@@ -248,26 +843,26 @@
   -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \
   | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \
   | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*)
-    oldincludedir="$ac_optarg" ;;
+    oldincludedir=$ac_optarg ;;
 
   -prefix | --prefix | --prefi | --pref | --pre | --pr | --p)
     ac_prev=prefix ;;
   -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*)
-    prefix="$ac_optarg" ;;
+    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_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_suffix=$ac_optarg ;;
 
   -program-transform-name | --program-transform-name \
   | --program-transform-nam | --program-transform-na \
@@ -284,7 +879,17 @@
   | --program-transfo=* | --program-transf=* \
   | --program-trans=* | --program-tran=* \
   | --progr-tra=* | --program-tr=* | --program-t=*)
-    program_transform_name="$ac_optarg" ;;
+    program_transform_name=$ac_optarg ;;
+
+  -pdfdir | --pdfdir | --pdfdi | --pdfd | --pdf | --pd)
+    ac_prev=pdfdir ;;
+  -pdfdir=* | --pdfdir=* | --pdfdi=* | --pdfd=* | --pdf=* | --pd=*)
+    pdfdir=$ac_optarg ;;
+
+  -psdir | --psdir | --psdi | --psd | --ps)
+    ac_prev=psdir ;;
+  -psdir=* | --psdir=* | --psdi=* | --psd=* | --ps=*)
+    psdir=$ac_optarg ;;
 
   -q | -quiet | --quiet | --quie | --qui | --qu | --q \
   | -silent | --silent | --silen | --sile | --sil)
@@ -294,7 +899,7 @@
     ac_prev=sbindir ;;
   -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \
   | --sbi=* | --sb=*)
-    sbindir="$ac_optarg" ;;
+    sbindir=$ac_optarg ;;
 
   -sharedstatedir | --sharedstatedir | --sharedstatedi \
   | --sharedstated | --sharedstate | --sharedstat | --sharedsta \
@@ -305,58 +910,53 @@
   | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \
   | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \
   | --sha=* | --sh=*)
-    sharedstatedir="$ac_optarg" ;;
+    sharedstatedir=$ac_optarg ;;
 
   -site | --site | --sit)
     ac_prev=site ;;
   -site=* | --site=* | --sit=*)
-    site="$ac_optarg" ;;
+    site=$ac_optarg ;;
 
   -srcdir | --srcdir | --srcdi | --srcd | --src | --sr)
     ac_prev=srcdir ;;
   -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*)
-    srcdir="$ac_optarg" ;;
+    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" ;;
+    sysconfdir=$ac_optarg ;;
 
   -target | --target | --targe | --targ | --tar | --ta | --t)
-    ac_prev=target ;;
+    ac_prev=target_alias ;;
   -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*)
-    target="$ac_optarg" ;;
+    target_alias=$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 ;;
+  -version | --version | --versio | --versi | --vers | -V)
+    ac_init_version=: ;;
 
   -with-* | --with-*)
-    ac_package=`echo $ac_option|sed -e 's/-*with-//' -e 's/=.*//'`
+    ac_package=`expr "x$ac_option" : 'x-*with-\([^=]*\)'`
     # 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'" ;;
+    expr "x$ac_package" : ".*[^-._$as_cr_alnum]" >/dev/null &&
+      { echo "$as_me: error: invalid package name: $ac_package" >&2
+   { (exit 1); exit 1; }; }
+    ac_package=`echo $ac_package | sed 's/[-.]/_/g'`
+    eval with_$ac_package=\$ac_optarg ;;
 
   -without-* | --without-*)
-    ac_package=`echo $ac_option|sed -e 's/-*without-//'`
+    ac_package=`expr "x$ac_option" : 'x-*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" ;;
+    expr "x$ac_package" : ".*[^-._$as_cr_alnum]" >/dev/null &&
+      { echo "$as_me: error: invalid package name: $ac_package" >&2
+   { (exit 1); exit 1; }; }
+    ac_package=`echo $ac_package | sed 's/[-.]/_/g'`
+    eval with_$ac_package=no ;;
 
   --x)
     # Obsolete; use --with-x.
@@ -367,187 +967,683 @@
     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_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; }
+    x_libraries=$ac_optarg ;;
+
+  -*) { echo "$as_me: error: unrecognized option: $ac_option
+Try \`$0 --help' for more information." >&2
+   { (exit 1); exit 1; }; }
     ;;
 
+  *=*)
+    ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='`
+    # Reject names that are not valid shell variable names.
+    expr "x$ac_envvar" : ".*[^_$as_cr_alnum]" >/dev/null &&
+      { echo "$as_me: error: invalid variable name: $ac_envvar" >&2
+   { (exit 1); exit 1; }; }
+    eval $ac_envvar=\$ac_optarg
+    export $ac_envvar ;;
+
   *)
-    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"
+    # FIXME: should be removed in autoconf 3.0.
+    echo "$as_me: WARNING: you should use --build, --host, --target" >&2
+    expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null &&
+      echo "$as_me: WARNING: invalid host type: $ac_option" >&2
+    : ${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$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; }
+  ac_option=--`echo $ac_prev | sed 's/_/-/g'`
+  { echo "$as_me: error: missing argument to $ac_option" >&2
+   { (exit 1); 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
+# Be sure to have absolute directory names.
+for ac_var in	exec_prefix prefix bindir sbindir libexecdir datarootdir \
+		datadir sysconfdir sharedstatedir localstatedir includedir \
+		oldincludedir docdir infodir htmldir dvidir pdfdir psdir \
+		libdir localedir mandir
+do
+  eval ac_val=\$$ac_var
+  case $ac_val in
+    [\\/$]* | ?:[\\/]* )  continue;;
+    NONE | '' ) case $ac_var in *prefix ) continue;; esac;;
+  esac
+  { echo "$as_me: error: expected an absolute directory name for --$ac_var: $ac_val" >&2
+   { (exit 1); exit 1; }; }
+done
+
+# There might be people who depend on the old broken behavior: `$host'
+# used to hold the argument of --host etc.
+# FIXME: To remove some day.
+build=$build_alias
+host=$host_alias
+target=$target_alias
+
+# FIXME: To remove some day.
+if test "x$host_alias" != x; then
+  if test "x$build_alias" = x; then
+    cross_compiling=maybe
+    echo "$as_me: WARNING: If you wanted to set the --build type, don't use --host.
+    If a cross compiler is detected then cross compile mode will be used." >&2
+  elif test "x$build_alias" != "x$host_alias"; then
+    cross_compiling=yes
+  fi
 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=doc/gperf.1
+
+ac_tool_prefix=
+test -n "$host_alias" && ac_tool_prefix=$host_alias-
+
+test "$silent" = yes && exec 6>/dev/null
+
+
+ac_pwd=`pwd` && test -n "$ac_pwd" &&
+ac_ls_di=`ls -di .` &&
+ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` ||
+  { echo "$as_me: error: Working directory cannot be determined" >&2
+   { (exit 1); exit 1; }; }
+test "X$ac_ls_di" = "X$ac_pwd_ls_di" ||
+  { echo "$as_me: error: pwd does not report name of working directory" >&2
+   { (exit 1); exit 1; }; }
+
 
 # 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=.
+  # Try the directory containing this script, then the parent directory.
+  ac_confdir=`$as_dirname -- "$0" ||
+$as_expr X"$0" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+	 X"$0" : 'X\(//\)[^/]' \| \
+	 X"$0" : 'X\(//\)$' \| \
+	 X"$0" : 'X\(/\)' \| . 2>/dev/null ||
+echo X"$0" |
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)[^/].*/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
   srcdir=$ac_confdir
-  if test ! -r $srcdir/$ac_unique_file; then
+  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
+if test ! -r "$srcdir/$ac_unique_file"; then
+  test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .."
+  { echo "$as_me: error: cannot find sources ($ac_unique_file) in $srcdir" >&2
+   { (exit 1); exit 1; }; }
 fi
-srcdir=`echo "${srcdir}" | sed 's%\([^/]\)/*$%\1%'`
-
+ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work"
+ac_abs_confdir=`(
+	cd "$srcdir" && test -r "./$ac_unique_file" || { echo "$as_me: error: $ac_msg" >&2
+   { (exit 1); exit 1; }; }
+	pwd)`
+# When building in place, set srcdir=.
+if test "$ac_abs_confdir" = "$ac_pwd"; then
+  srcdir=.
+fi
+# Remove unnecessary trailing slashes from srcdir.
+# Double slashes in file names in object file debugging info
+# mess up M-x gdb in Emacs.
+case $srcdir in
+*/) srcdir=`expr "X$srcdir" : 'X\(.*[^/]\)' \| "X$srcdir" : 'X\(.*\)'`;;
+esac
+for ac_var in $ac_precious_vars; do
+  eval ac_env_${ac_var}_set=\${${ac_var}+set}
+  eval ac_env_${ac_var}_value=\$${ac_var}
+  eval ac_cv_env_${ac_var}_set=\${${ac_var}+set}
+  eval ac_cv_env_${ac_var}_value=\$${ac_var}
+done
+
+#
+# Report the --help message.
+#
+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 this package to adapt to many kinds of systems.
+
+Usage: $0 [OPTION]... [VAR=VALUE]...
+
+To assign environment variables (e.g., CC, CFLAGS...), specify them as
+VAR=VALUE.  See below for descriptions of some of the useful variables.
+
+Defaults for the options are specified in brackets.
+
+Configuration:
+  -h, --help              display this help and exit
+      --help=short        display options specific to this package
+      --help=recursive    display the short help of all the included packages
+  -V, --version           display version information and exit
+  -q, --quiet, --silent   do not print \`checking...' messages
+      --cache-file=FILE   cache test results in FILE [disabled]
+  -C, --config-cache      alias for \`--cache-file=config.cache'
+  -n, --no-create         do not create output files
+      --srcdir=DIR        find the sources in DIR [configure dir or \`..']
+
+Installation directories:
+  --prefix=PREFIX         install architecture-independent files in PREFIX
+			  [$ac_default_prefix]
+  --exec-prefix=EPREFIX   install architecture-dependent files in EPREFIX
+			  [PREFIX]
+
+By default, \`make install' will install all the files in
+\`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc.  You can specify
+an installation prefix other than \`$ac_default_prefix' using \`--prefix',
+for instance \`--prefix=\$HOME'.
+
+For better control, use the options below.
+
+Fine tuning of the installation directories:
+  --bindir=DIR           user executables [EPREFIX/bin]
+  --sbindir=DIR          system admin executables [EPREFIX/sbin]
+  --libexecdir=DIR       program executables [EPREFIX/libexec]
+  --sysconfdir=DIR       read-only single-machine data [PREFIX/etc]
+  --sharedstatedir=DIR   modifiable architecture-independent data [PREFIX/com]
+  --localstatedir=DIR    modifiable single-machine data [PREFIX/var]
+  --libdir=DIR           object code libraries [EPREFIX/lib]
+  --includedir=DIR       C header files [PREFIX/include]
+  --oldincludedir=DIR    C header files for non-gcc [/usr/include]
+  --datarootdir=DIR      read-only arch.-independent data root [PREFIX/share]
+  --datadir=DIR          read-only architecture-independent data [DATAROOTDIR]
+  --infodir=DIR          info documentation [DATAROOTDIR/info]
+  --localedir=DIR        locale-dependent data [DATAROOTDIR/locale]
+  --mandir=DIR           man documentation [DATAROOTDIR/man]
+  --docdir=DIR           documentation root [DATAROOTDIR/doc/PACKAGE]
+  --htmldir=DIR          html documentation [DOCDIR]
+  --dvidir=DIR           dvi documentation [DOCDIR]
+  --pdfdir=DIR           pdf documentation [DOCDIR]
+  --psdir=DIR            ps documentation [DOCDIR]
+_ACEOF
+
+  cat <<\_ACEOF
+_ACEOF
+fi
+
+if test -n "$ac_init_help"; then
+
+  cat <<\_ACEOF
+
+_ACEOF
+ac_status=$?
+fi
+
+if test "$ac_init_help" = "recursive"; then
+  # If there are subdirs, report their specific --help.
+  for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue
+    test -d "$ac_dir" || continue
+    ac_builddir=.
+
+case "$ac_dir" in
+.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;
+*)
+  ac_dir_suffix=/`echo "$ac_dir" | sed 's,^\.[\\/],,'`
+  # A ".." for each directory in $ac_dir_suffix.
+  ac_top_builddir_sub=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,/..,g;s,/,,'`
+  case $ac_top_builddir_sub in
+  "") ac_top_builddir_sub=. ac_top_build_prefix= ;;
+  *)  ac_top_build_prefix=$ac_top_builddir_sub/ ;;
+  esac ;;
+esac
+ac_abs_top_builddir=$ac_pwd
+ac_abs_builddir=$ac_pwd$ac_dir_suffix
+# for backward compatibility:
+ac_top_builddir=$ac_top_build_prefix
+
+case $srcdir in
+  .)  # We are building in place.
+    ac_srcdir=.
+    ac_top_srcdir=$ac_top_builddir_sub
+    ac_abs_top_srcdir=$ac_pwd ;;
+  [\\/]* | ?:[\\/]* )  # Absolute name.
+    ac_srcdir=$srcdir$ac_dir_suffix;
+    ac_top_srcdir=$srcdir
+    ac_abs_top_srcdir=$srcdir ;;
+  *) # Relative name.
+    ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix
+    ac_top_srcdir=$ac_top_build_prefix$srcdir
+    ac_abs_top_srcdir=$ac_pwd/$srcdir ;;
+esac
+ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix
+
+    cd "$ac_dir" || { ac_status=$?; continue; }
+    # Check for guested configure.
+    if test -f "$ac_srcdir/configure.gnu"; then
+      echo &&
+      $SHELL "$ac_srcdir/configure.gnu" --help=recursive
+    elif test -f "$ac_srcdir/configure"; then
+      echo &&
+      $SHELL "$ac_srcdir/configure" --help=recursive
+    else
+      echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2
+    fi || ac_status=$?
+    cd "$ac_pwd" || { ac_status=$?; break; }
+  done
+fi
+
+test -n "$ac_init_help" && exit $ac_status
+if $ac_init_version; then
+  cat <<\_ACEOF
+configure
+generated by GNU Autoconf 2.61
+
+Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001,
+2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc.
+This configure script is free software; the Free Software Foundation
+gives unlimited permission to copy, distribute and modify it.
+_ACEOF
+  exit
+fi
+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 $as_me, which was
+generated by GNU Autoconf 2.61.  Invocation command line was
+
+  $ $0 $@
+
+_ACEOF
+exec 5>>config.log
+{
+cat <<_ASUNAME
+## --------- ##
+## Platform. ##
+## --------- ##
+
+hostname = `(hostname || uname -n) 2>/dev/null | sed 1q`
+uname -m = `(uname -m) 2>/dev/null || echo unknown`
+uname -r = `(uname -r) 2>/dev/null || echo unknown`
+uname -s = `(uname -s) 2>/dev/null || echo unknown`
+uname -v = `(uname -v) 2>/dev/null || echo unknown`
+
+/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown`
+/bin/uname -X     = `(/bin/uname -X) 2>/dev/null     || echo unknown`
+
+/bin/arch              = `(/bin/arch) 2>/dev/null              || echo unknown`
+/usr/bin/arch -k       = `(/usr/bin/arch -k) 2>/dev/null       || echo unknown`
+/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown`
+/usr/bin/hostinfo      = `(/usr/bin/hostinfo) 2>/dev/null      || echo unknown`
+/bin/machine           = `(/bin/machine) 2>/dev/null           || echo unknown`
+/usr/bin/oslevel       = `(/usr/bin/oslevel) 2>/dev/null       || echo unknown`
+/bin/universe          = `(/bin/universe) 2>/dev/null          || echo unknown`
+
+_ASUNAME
+
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+  echo "PATH: $as_dir"
+done
+IFS=$as_save_IFS
+
+} >&5
+
+cat >&5 <<_ACEOF
+
+
+## ----------- ##
+## Core tests. ##
+## ----------- ##
+
+_ACEOF
+
+
+# Keep a trace of the command line.
+# Strip out --no-create and --no-recursion so they do not pile up.
+# Strip out --silent because we don't want to record it for future runs.
+# Also quote any args containing shell meta-characters.
+# Make two passes to allow for proper duplicate-argument suppression.
+ac_configure_args=
+ac_configure_args0=
+ac_configure_args1=
+ac_must_keep_next=false
+for ac_pass in 1 2
+do
+  for ac_arg
+  do
+    case $ac_arg in
+    -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;;
+    -q | -quiet | --quiet | --quie | --qui | --qu | --q \
+    | -silent | --silent | --silen | --sile | --sil)
+      continue ;;
+    *\'*)
+      ac_arg=`echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;;
+    esac
+    case $ac_pass in
+    1) ac_configure_args0="$ac_configure_args0 '$ac_arg'" ;;
+    2)
+      ac_configure_args1="$ac_configure_args1 '$ac_arg'"
+      if test $ac_must_keep_next = true; then
+	ac_must_keep_next=false # Got value, back to normal.
+      else
+	case $ac_arg in
+	  *=* | --config-cache | -C | -disable-* | --disable-* \
+	  | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \
+	  | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \
+	  | -with-* | --with-* | -without-* | --without-* | --x)
+	    case "$ac_configure_args0 " in
+	      "$ac_configure_args1"*" '$ac_arg' "* ) continue ;;
+	    esac
+	    ;;
+	  -* ) ac_must_keep_next=true ;;
+	esac
+      fi
+      ac_configure_args="$ac_configure_args '$ac_arg'"
+      ;;
+    esac
+  done
+done
+$as_unset ac_configure_args0 || test "${ac_configure_args0+set}" != set || { ac_configure_args0=; export ac_configure_args0; }
+$as_unset ac_configure_args1 || test "${ac_configure_args1+set}" != set || { ac_configure_args1=; export ac_configure_args1; }
+
+# When interrupted or exit'd, cleanup temporary files, and complete
+# config.log.  We remove comments because anyway the quotes in there
+# would cause problems or look ugly.
+# WARNING: Use '\'' to represent an apostrophe within the trap.
+# WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug.
+trap 'exit_status=$?
+  # Save into config.log some information that might help in debugging.
+  {
+    echo
+
+    cat <<\_ASBOX
+## ---------------- ##
+## Cache variables. ##
+## ---------------- ##
+_ASBOX
+    echo
+    # The following way of writing the cache mishandles newlines in values,
+(
+  for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do
+    eval ac_val=\$$ac_var
+    case $ac_val in #(
+    *${as_nl}*)
+      case $ac_var in #(
+      *_cv_*) { echo "$as_me:$LINENO: WARNING: Cache variable $ac_var contains a newline." >&5
+echo "$as_me: WARNING: Cache variable $ac_var contains a newline." >&2;} ;;
+      esac
+      case $ac_var in #(
+      _ | IFS | as_nl) ;; #(
+      *) $as_unset $ac_var ;;
+      esac ;;
+    esac
+  done
+  (set) 2>&1 |
+    case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #(
+    *${as_nl}ac_space=\ *)
+      sed -n \
+	"s/'\''/'\''\\\\'\'''\''/g;
+	  s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p"
+      ;; #(
+    *)
+      sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p"
+      ;;
+    esac |
+    sort
+)
+    echo
+
+    cat <<\_ASBOX
+## ----------------- ##
+## Output variables. ##
+## ----------------- ##
+_ASBOX
+    echo
+    for ac_var in $ac_subst_vars
+    do
+      eval ac_val=\$$ac_var
+      case $ac_val in
+      *\'\''*) ac_val=`echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;;
+      esac
+      echo "$ac_var='\''$ac_val'\''"
+    done | sort
+    echo
+
+    if test -n "$ac_subst_files"; then
+      cat <<\_ASBOX
+## ------------------- ##
+## File substitutions. ##
+## ------------------- ##
+_ASBOX
+      echo
+      for ac_var in $ac_subst_files
+      do
+	eval ac_val=\$$ac_var
+	case $ac_val in
+	*\'\''*) ac_val=`echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;;
+	esac
+	echo "$ac_var='\''$ac_val'\''"
+      done | sort
+      echo
+    fi
+
+    if test -s confdefs.h; then
+      cat <<\_ASBOX
+## ----------- ##
+## confdefs.h. ##
+## ----------- ##
+_ASBOX
+      echo
+      cat confdefs.h
+      echo
+    fi
+    test "$ac_signal" != 0 &&
+      echo "$as_me: caught signal $ac_signal"
+    echo "$as_me: exit $exit_status"
+  } >&5
+  rm -f core *.core core.conftest.* &&
+    rm -f -r conftest* confdefs* conf$$* $ac_clean_files &&
+    exit $exit_status
+' 0
+for ac_signal in 1 2 13 15; do
+  trap 'ac_signal='$ac_signal'; { (exit 1); exit 1; }' $ac_signal
+done
+ac_signal=0
+
+# confdefs.h avoids OS command line length limits that DEFS can exceed.
+rm -f -r conftest* confdefs.h
+
+# Predefined preprocessor variables.
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_NAME "$PACKAGE_NAME"
+_ACEOF
+
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_TARNAME "$PACKAGE_TARNAME"
+_ACEOF
+
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_VERSION "$PACKAGE_VERSION"
+_ACEOF
+
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_STRING "$PACKAGE_STRING"
+_ACEOF
+
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT"
+_ACEOF
+
+
+# Let the site file select an alternate cache file if it wants to.
 # 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
+if test -n "$CONFIG_SITE"; then
+  set x "$CONFIG_SITE"
+elif test "x$prefix" != xNONE; then
+  set x "$prefix/share/config.site" "$prefix/etc/config.site"
+else
+  set x "$ac_default_prefix/share/config.site" \
+	"$ac_default_prefix/etc/config.site"
 fi
-for ac_site_file in $CONFIG_SITE; do
+shift
+for ac_site_file
+do
   if test -r "$ac_site_file"; then
-    echo "loading site script $ac_site_file"
+    { echo "$as_me:$LINENO: loading site script $ac_site_file" >&5
+echo "$as_me: loading site script $ac_site_file" >&6;}
+    sed 's/^/| /' "$ac_site_file" >&5
     . "$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 at 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=
+  # Some versions of bash will fail to source /dev/null (special
+  # files actually), so we avoid doing that.
+  if test -f "$cache_file"; then
+    { echo "$as_me:$LINENO: loading cache $cache_file" >&5
+echo "$as_me: loading cache $cache_file" >&6;}
+    case $cache_file in
+      [\\/]* | ?:[\\/]* ) . "$cache_file";;
+      *)                      . "./$cache_file";;
+    esac
   fi
 else
-  ac_n= ac_c='\c' ac_t=
+  { echo "$as_me:$LINENO: creating cache $cache_file" >&5
+echo "$as_me: creating cache $cache_file" >&6;}
+  >$cache_file
 fi
 
-
-echo $ac_n "checking whether ${MAKE-make} sets \${MAKE}""... $ac_c" 1>&6
-echo "configure:526: 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
+# Check that the precious variables saved in the cache have kept the same
+# value.
+ac_cache_corrupted=false
+for ac_var in $ac_precious_vars; do
+  eval ac_old_set=\$ac_cv_env_${ac_var}_set
+  eval ac_new_set=\$ac_env_${ac_var}_set
+  eval ac_old_val=\$ac_cv_env_${ac_var}_value
+  eval ac_new_val=\$ac_env_${ac_var}_value
+  case $ac_old_set,$ac_new_set in
+    set,)
+      { echo "$as_me:$LINENO: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5
+echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;}
+      ac_cache_corrupted=: ;;
+    ,set)
+      { echo "$as_me:$LINENO: error: \`$ac_var' was not set in the previous run" >&5
+echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;}
+      ac_cache_corrupted=: ;;
+    ,);;
+    *)
+      if test "x$ac_old_val" != "x$ac_new_val"; then
+	{ echo "$as_me:$LINENO: error: \`$ac_var' has changed since the previous run:" >&5
+echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;}
+	{ echo "$as_me:$LINENO:   former value:  $ac_old_val" >&5
+echo "$as_me:   former value:  $ac_old_val" >&2;}
+	{ echo "$as_me:$LINENO:   current value: $ac_new_val" >&5
+echo "$as_me:   current value: $ac_new_val" >&2;}
+	ac_cache_corrupted=:
+      fi;;
+  esac
+  # Pass precious variables to config.status.
+  if test "$ac_new_set" = set; then
+    case $ac_new_val in
+    *\'*) ac_arg=$ac_var=`echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;;
+    *) ac_arg=$ac_var=$ac_new_val ;;
+    esac
+    case " $ac_configure_args " in
+      *" '$ac_arg' "*) ;; # Avoid dups.  Use of quotes ensures accuracy.
+      *) ac_configure_args="$ac_configure_args '$ac_arg'" ;;
+    esac
+  fi
+done
+if $ac_cache_corrupted; then
+  { echo "$as_me:$LINENO: error: changes in the environment can compromise the build" >&5
+echo "$as_me: error: changes in the environment can compromise the build" >&2;}
+  { { echo "$as_me:$LINENO: error: run \`make distclean' and/or \`rm $cache_file' and start over" >&5
+echo "$as_me: error: run \`make distclean' and/or \`rm $cache_file' and start over" >&2;}
+   { (exit 1); exit 1; }; }
+fi
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+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: checking whether ${MAKE-make} sets \$(MAKE)" >&5
+echo $ECHO_N "checking whether ${MAKE-make} sets \$(MAKE)... $ECHO_C" >&6; }
+set x ${MAKE-make}; ac_make=`echo "$2" | sed 's/+/p/g; s/[^a-zA-Z0-9_]/_/g'`
+if { as_var=ac_cv_prog_make_${ac_make}_set; eval "test \"\${$as_var+set}\" = set"; }; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
 else
-  cat > conftestmake <<\EOF
+  cat >conftest.make <<\_ACEOF
+SHELL = /bin/sh
 all:
-	@echo 'ac_maketemp="${MAKE}"'
-EOF
+	@echo '@@@%%%=$(MAKE)=@@@%%%'
+_ACEOF
 # 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
+case `${MAKE-make} -f conftest.make 2>/dev/null` in
+  *@@@%%%=?*=@@@%%%*)
+    eval ac_cv_prog_make_${ac_make}_set=yes;;
+  *)
+    eval ac_cv_prog_make_${ac_make}_set=no;;
+esac
+rm -f conftest.make
 fi
-rm -f conftestmake
-fi
-if eval "test \"`echo '$ac_cv_prog_make_'${ac_make}_set`\" = yes"; then
-  echo "$ac_t""yes" 1>&6
+if eval test \$ac_cv_prog_make_${ac_make}_set = yes; then
+  { echo "$as_me:$LINENO: result: yes" >&5
+echo "${ECHO_T}yes" >&6; }
   SET_MAKE=
 else
-  echo "$ac_t""no" 1>&6
+  { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
   SET_MAKE="MAKE=${MAKE-make}"
 fi
 
+
+
+
+ac_aux_dir=$srcdir
+
+subdirs="$subdirs lib src tests doc"
+
+
 extrasub="$extrasub"'
 /@subdir@/{
 h
@@ -566,349 +1662,1183 @@
 d
 }
 '
-trap '' 1 2 15
-cat > confcache <<\EOF
+ac_config_files="$ac_config_files Makefile"
+
+cat >confcache <<\_ACEOF
 # 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.
+# scripts and configure runs, see configure's option --config-cache.
+# 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.
+# config.status only pays attention to the cache file if you give it
+# the --recheck option to rerun configure.
 #
-EOF
+# `ac_cv_env_foo' variables (set or unset) will be overridden when
+# loading this file, other *unset* `ac_cv_foo' will be assigned the
+# following values.
+
+_ACEOF
+
 # 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.
+# So, we kill variables containing newlines.
 # 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
+(
+  for ac_var in `(set) 2>&1 | sed -n 's/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'`; do
+    eval ac_val=\$$ac_var
+    case $ac_val in #(
+    *${as_nl}*)
+      case $ac_var in #(
+      *_cv_*) { echo "$as_me:$LINENO: WARNING: Cache variable $ac_var contains a newline." >&5
+echo "$as_me: WARNING: Cache variable $ac_var contains a newline." >&2;} ;;
+      esac
+      case $ac_var in #(
+      _ | IFS | as_nl) ;; #(
+      *) $as_unset $ac_var ;;
+      esac ;;
+    esac
+  done
+
+  (set) 2>&1 |
+    case $as_nl`(ac_space=' '; set) 2>&1` in #(
+    *${as_nl}ac_space=\ *)
+      # `set' does not quote correctly, so add quotes (double-quote
+      # substitution turns \\\\ into \\, and sed turns \\ into \).
+      sed -n \
+	"s/'/'\\\\''/g;
+	  s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p"
+      ;; #(
+    *)
+      # `set' quotes correctly as required by POSIX, so do not add quotes.
+      sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p"
+      ;;
+    esac |
+    sort
+) |
+  sed '
+     /^ac_cv_env_/b end
+     t clear
+     :clear
+     s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/
+     t end
+     s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/
+     :end' >>confcache
+if diff "$cache_file" confcache >/dev/null 2>&1; then :; else
+  if test -w "$cache_file"; then
+    test "x$cache_file" != "x/dev/null" &&
+      { echo "$as_me:$LINENO: updating cache $cache_file" >&5
+echo "$as_me: updating cache $cache_file" >&6;}
+    cat confcache >$cache_file
   else
-    echo "not updating unwritable cache $cache_file"
+    { echo "$as_me:$LINENO: not updating unwritable cache $cache_file" >&5
+echo "$as_me: not updating unwritable cache $cache_file" >&6;}
   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.
+#
+# If the first sed substitution is executed (which looks for macros that
+# take arguments), then branch to the quote section.  Otherwise,
+# look for a macro that doesn't take arguments.
+ac_script='
+t clear
+:clear
+s/^[	 ]*#[	 ]*define[	 ][	 ]*\([^	 (][^	 (]*([^)]*)\)[	 ]*\(.*\)/-D\1=\2/g
+t quote
+s/^[	 ]*#[	 ]*define[	 ][	 ]*\([^	 ][^	 ]*\)[	 ]*\(.*\)/-D\1=\2/g
+t quote
+b any
+:quote
+s/[	 `~#$^&*(){}\\|;'\''"<>?]/\\&/g
+s/\[/\\&/g
+s/\]/\\&/g
+s/\$/$$/g
+H
+:any
+${
+	g
+	s/^\n//
+	s/\n/ /g
+	p
+}
+'
+DEFS=`sed -n "$ac_script" confdefs.h`
+
+
+ac_libobjs=
+ac_ltlibobjs=
+for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue
+  # 1. Remove the extension, and $U if already installed.
+  ac_script='s/\$U\././;s/\.o$//;s/\.obj$//'
+  ac_i=`echo "$ac_i" | sed "$ac_script"`
+  # 2. Prepend LIBOBJDIR.  When used with automake>=1.10 LIBOBJDIR
+  #    will be set to the directory where LIBOBJS objects are built.
+  ac_libobjs="$ac_libobjs \${LIBOBJDIR}$ac_i\$U.$ac_objext"
+  ac_ltlibobjs="$ac_ltlibobjs \${LIBOBJDIR}$ac_i"'$U.lo'
+done
+LIBOBJS=$ac_libobjs
+
+LTLIBOBJS=$ac_ltlibobjs
+
+
+
 : ${CONFIG_STATUS=./config.status}
-
-echo creating $CONFIG_STATUS
-rm -f $CONFIG_STATUS
-cat > $CONFIG_STATUS <<EOF
-#! /bin/sh
-# Generated automatically by configure.
+ac_clean_files_save=$ac_clean_files
+ac_clean_files="$ac_clean_files $CONFIG_STATUS"
+{ echo "$as_me:$LINENO: creating $CONFIG_STATUS" >&5
+echo "$as_me: creating $CONFIG_STATUS" >&6;}
+cat >$CONFIG_STATUS <<_ACEOF
+#! $SHELL
+# Generated by $as_me.
 # Run this file to recreate the current configuration.
-# This directory was configured as follows,
-# on host `(hostname || uname -n) 2>/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
+# configure, is in config.log if it exists.
+
+debug=false
+ac_cs_recheck=false
+ac_cs_silent=false
+SHELL=\${CONFIG_SHELL-$SHELL}
+_ACEOF
+
+cat >>$CONFIG_STATUS <<\_ACEOF
+## --------------------- ##
+## M4sh Initialization.  ##
+## --------------------- ##
+
+# Be more Bourne compatible
+DUALCASE=1; export DUALCASE # for MKS sh
+if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
+  emulate sh
+  NULLCMD=:
+  # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
+  # is contrary to our usage.  Disable this feature.
+  alias -g '${1+"$@"}'='"$@"'
+  setopt NO_GLOB_SUBST
+else
+  case `(set -o) 2>/dev/null` in
+  *posix*) set -o posix ;;
+esac
+
+fi
+
+
+
+
+# PATH needs CR
+# Avoid depending upon Character Ranges.
+as_cr_letters='abcdefghijklmnopqrstuvwxyz'
+as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
+as_cr_Letters=$as_cr_letters$as_cr_LETTERS
+as_cr_digits='0123456789'
+as_cr_alnum=$as_cr_Letters$as_cr_digits
+
+# The user is always right.
+if test "${PATH_SEPARATOR+set}" != set; then
+  echo "#! /bin/sh" >conf$$.sh
+  echo  "exit 0"   >>conf$$.sh
+  chmod +x conf$$.sh
+  if (PATH="/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then
+    PATH_SEPARATOR=';'
+  else
+    PATH_SEPARATOR=:
+  fi
+  rm -f conf$$.sh
+fi
+
+# Support unset when possible.
+if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then
+  as_unset=unset
+else
+  as_unset=false
+fi
+
+
+# IFS
+# We need space, tab and new line, in precisely that order.  Quoting is
+# there to prevent editors from complaining about space-tab.
+# (If _AS_PATH_WALK were called with IFS unset, it would disable word
+# splitting by setting IFS to empty value.)
+as_nl='
+'
+IFS=" ""	$as_nl"
+
+# Find who we are.  Look in the path if we contain no directory separator.
+case $0 in
+  *[\\/]* ) as_myself=$0 ;;
+  *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
 do
-  case "\$ac_option" in
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+  test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break
+done
+IFS=$as_save_IFS
+
+     ;;
+esac
+# We did not find ourselves, most probably we were run as `sh COMMAND'
+# in which case we are not to be found in the path.
+if test "x$as_myself" = x; then
+  as_myself=$0
+fi
+if test ! -f "$as_myself"; then
+  echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2
+  { (exit 1); exit 1; }
+fi
+
+# Work around bugs in pre-3.0 UWIN ksh.
+for as_var in ENV MAIL MAILPATH
+do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var
+done
+PS1='$ '
+PS2='> '
+PS4='+ '
+
+# NLS nuisances.
+for as_var in \
+  LANG LANGUAGE LC_ADDRESS LC_ALL LC_COLLATE LC_CTYPE LC_IDENTIFICATION \
+  LC_MEASUREMENT LC_MESSAGES LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER \
+  LC_TELEPHONE LC_TIME
+do
+  if (set +x; test -z "`(eval $as_var=C; export $as_var) 2>&1`"); then
+    eval $as_var=C; export $as_var
+  else
+    ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var
+  fi
+done
+
+# Required to use basename.
+if expr a : '\(a\)' >/dev/null 2>&1 &&
+   test "X`expr 00001 : '.*\(...\)'`" = X001; then
+  as_expr=expr
+else
+  as_expr=false
+fi
+
+if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then
+  as_basename=basename
+else
+  as_basename=false
+fi
+
+
+# Name of the executable.
+as_me=`$as_basename -- "$0" ||
+$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
+	 X"$0" : 'X\(//\)$' \| \
+	 X"$0" : 'X\(/\)' \| . 2>/dev/null ||
+echo X/"$0" |
+    sed '/^.*\/\([^/][^/]*\)\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\/\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\/\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+
+# CDPATH.
+$as_unset CDPATH
+
+
+
+  as_lineno_1=$LINENO
+  as_lineno_2=$LINENO
+  test "x$as_lineno_1" != "x$as_lineno_2" &&
+  test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2" || {
+
+  # Create $as_me.lineno as a copy of $as_myself, but with $LINENO
+  # uniformly replaced by the line number.  The first 'sed' inserts a
+  # line-number line after each line using $LINENO; the second 'sed'
+  # does the real work.  The second script uses 'N' to pair each
+  # line-number line with the line containing $LINENO, and appends
+  # trailing '-' during substitution so that $LINENO is not a special
+  # case at line end.
+  # (Raja R Harinath suggested sed '=', and Paul Eggert wrote the
+  # scripts with optimization help from Paolo Bonzini.  Blame Lee
+  # E. McMahon (1931-1989) for sed's syntax.  :-)
+  sed -n '
+    p
+    /[$]LINENO/=
+  ' <$as_myself |
+    sed '
+      s/[$]LINENO.*/&-/
+      t lineno
+      b
+      :lineno
+      N
+      :loop
+      s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/
+      t loop
+      s/-\n.*//
+    ' >$as_me.lineno &&
+  chmod +x "$as_me.lineno" ||
+    { echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2
+   { (exit 1); exit 1; }; }
+
+  # Don't try to exec as it changes $[0], causing all sort of problems
+  # (the dirname of $[0] is not the place where we might find the
+  # original and so on.  Autoconf is especially sensitive to this).
+  . "./$as_me.lineno"
+  # Exit status is that of the last command.
+  exit
+}
+
+
+if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then
+  as_dirname=dirname
+else
+  as_dirname=false
+fi
+
+ECHO_C= ECHO_N= ECHO_T=
+case `echo -n x` in
+-n*)
+  case `echo 'x\c'` in
+  *c*) ECHO_T='	';;	# ECHO_T is single tab character.
+  *)   ECHO_C='\c';;
+  esac;;
+*)
+  ECHO_N='-n';;
+esac
+
+if expr a : '\(a\)' >/dev/null 2>&1 &&
+   test "X`expr 00001 : '.*\(...\)'`" = X001; then
+  as_expr=expr
+else
+  as_expr=false
+fi
+
+rm -f conf$$ conf$$.exe conf$$.file
+if test -d conf$$.dir; then
+  rm -f conf$$.dir/conf$$.file
+else
+  rm -f conf$$.dir
+  mkdir conf$$.dir
+fi
+echo >conf$$.file
+if ln -s conf$$.file conf$$ 2>/dev/null; then
+  as_ln_s='ln -s'
+  # ... but there are two gotchas:
+  # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail.
+  # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable.
+  # In both cases, we have to default to `cp -p'.
+  ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe ||
+    as_ln_s='cp -p'
+elif ln conf$$.file conf$$ 2>/dev/null; then
+  as_ln_s=ln
+else
+  as_ln_s='cp -p'
+fi
+rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file
+rmdir conf$$.dir 2>/dev/null
+
+if mkdir -p . 2>/dev/null; then
+  as_mkdir_p=:
+else
+  test -d ./-p && rmdir ./-p
+  as_mkdir_p=false
+fi
+
+if test -x / >/dev/null 2>&1; then
+  as_test_x='test -x'
+else
+  if ls -dL / >/dev/null 2>&1; then
+    as_ls_L_option=L
+  else
+    as_ls_L_option=
+  fi
+  as_test_x='
+    eval sh -c '\''
+      if test -d "$1"; then
+        test -d "$1/.";
+      else
+	case $1 in
+        -*)set "./$1";;
+	esac;
+	case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in
+	???[sx]*):;;*)false;;esac;fi
+    '\'' sh
+  '
+fi
+as_executable_p=$as_test_x
+
+# Sed expression to map a string onto a valid CPP name.
+as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
+
+# Sed expression to map a string onto a valid variable name.
+as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'"
+
+
+exec 6>&1
+
+# Save the log message, to keep $[0] and so on meaningful, and to
+# report actual input values of CONFIG_FILES etc. instead of their
+# values after options handling.
+ac_log="
+This file was extended by $as_me, which was
+generated by GNU Autoconf 2.61.  Invocation command line was
+
+  CONFIG_FILES    = $CONFIG_FILES
+  CONFIG_HEADERS  = $CONFIG_HEADERS
+  CONFIG_LINKS    = $CONFIG_LINKS
+  CONFIG_COMMANDS = $CONFIG_COMMANDS
+  $ $0 $@
+
+on `(hostname || uname -n) 2>/dev/null | sed 1q`
+"
+
+_ACEOF
+
+cat >>$CONFIG_STATUS <<_ACEOF
+# Files that config.status was made for.
+config_files="$ac_config_files"
+
+_ACEOF
+
+cat >>$CONFIG_STATUS <<\_ACEOF
+ac_cs_usage="\
+\`$as_me' instantiates files from templates according to the
+current configuration.
+
+Usage: $0 [OPTIONS] [FILE]...
+
+  -h, --help       print this help, then exit
+  -V, --version    print version number and configuration settings, then exit
+  -q, --quiet      do not print progress messages
+  -d, --debug      don't remove temporary files
+      --recheck    update $as_me by reconfiguring in the same conditions
+  --file=FILE[:TEMPLATE]
+		   instantiate the configuration file FILE
+
+Configuration files:
+$config_files
+
+Report bugs to <bug-autoconf at gnu.org>."
+
+_ACEOF
+cat >>$CONFIG_STATUS <<_ACEOF
+ac_cs_version="\\
+config.status
+configured by $0, generated by GNU Autoconf 2.61,
+  with options \\"`echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`\\"
+
+Copyright (C) 2006 Free Software Foundation, Inc.
+This config.status script is free software; the Free Software Foundation
+gives unlimited permission to copy, distribute and modify it."
+
+ac_pwd='$ac_pwd'
+srcdir='$srcdir'
+_ACEOF
+
+cat >>$CONFIG_STATUS <<\_ACEOF
+# If no file are specified by the user, then we need to provide default
+# value.  By we need to know if files were specified by the user.
+ac_need_defaults=:
+while test $# != 0
+do
+  case $1 in
+  --*=*)
+    ac_option=`expr "X$1" : 'X\([^=]*\)='`
+    ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'`
+    ac_shift=:
+    ;;
+  *)
+    ac_option=$1
+    ac_optarg=$2
+    ac_shift=shift
+    ;;
+  esac
+
+  case $ac_option in
+  # Handling of the options.
   -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 ;;
+    ac_cs_recheck=: ;;
+  --version | --versio | --versi | --vers | --ver | --ve | --v | -V )
+    echo "$ac_cs_version"; exit ;;
+  --debug | --debu | --deb | --de | --d | -d )
+    debug=: ;;
+  --file | --fil | --fi | --f )
+    $ac_shift
+    CONFIG_FILES="$CONFIG_FILES $ac_optarg"
+    ac_need_defaults=false;;
+  --he | --h |  --help | --hel | -h )
+    echo "$ac_cs_usage"; exit ;;
+  -q | -quiet | --quiet | --quie | --qui | --qu | --q \
+  | -silent | --silent | --silen | --sile | --sil | --si | --s)
+    ac_cs_silent=: ;;
+
+  # This is an error.
+  -*) { echo "$as_me: error: unrecognized option: $1
+Try \`$0 --help' for more information." >&2
+   { (exit 1); exit 1; }; } ;;
+
+  *) ac_config_targets="$ac_config_targets $1"
+     ac_need_defaults=false ;;
+
+  esac
+  shift
+done
+
+ac_configure_extra_args=
+
+if $ac_cs_silent; then
+  exec 6>/dev/null
+  ac_configure_extra_args="$ac_configure_extra_args --silent"
+fi
+
+_ACEOF
+cat >>$CONFIG_STATUS <<_ACEOF
+if \$ac_cs_recheck; then
+  echo "running CONFIG_SHELL=$SHELL $SHELL $0 "$ac_configure_args \$ac_configure_extra_args " --no-create --no-recursion" >&6
+  CONFIG_SHELL=$SHELL
+  export CONFIG_SHELL
+  exec $SHELL "$0"$ac_configure_args \$ac_configure_extra_args --no-create --no-recursion
+fi
+
+_ACEOF
+cat >>$CONFIG_STATUS <<\_ACEOF
+exec 5>>config.log
+{
+  echo
+  sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX
+## Running $as_me. ##
+_ASBOX
+  echo "$ac_log"
+} >&5
+
+_ACEOF
+cat >>$CONFIG_STATUS <<_ACEOF
+_ACEOF
+
+cat >>$CONFIG_STATUS <<\_ACEOF
+
+# Handling of arguments.
+for ac_config_target in $ac_config_targets
+do
+  case $ac_config_target in
+    "Makefile") CONFIG_FILES="$CONFIG_FILES Makefile" ;;
+
+  *) { { echo "$as_me:$LINENO: error: invalid argument: $ac_config_target" >&5
+echo "$as_me: error: invalid argument: $ac_config_target" >&2;}
+   { (exit 1); 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 <<EOF
-
-# Protect against being on the right side of a sed subst in config.status.
-sed 's/%@/@@/; s/@%/@@/; s/%g\$/@g/; /@g\$/s/[\\\\&%]/\\\\&/g;
- s/@@/%@/; s/@@/@%/; s/@g\$/%g/' > 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%@SET_MAKE@%$SET_MAKE%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
+
+# If the user did not use the arguments to specify the items to instantiate,
+# then the envvar interface is used.  Set only those that are not.
+# We use the long form for the default assignment because of an extremely
+# bizarre bug on SunOS 4.1.3.
+if $ac_need_defaults; then
+  test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files
+fi
+
+# Have a temporary directory for convenience.  Make it in the build tree
+# simply because there is no reason against having it here, and in addition,
+# creating and moving files from /tmp can sometimes cause problems.
+# Hook for its removal unless debugging.
+# Note that there is a small window in which the directory will not be cleaned:
+# after its creation but before its name has been assigned to `$tmp'.
+$debug ||
+{
+  tmp=
+  trap 'exit_status=$?
+  { test -z "$tmp" || test ! -d "$tmp" || rm -fr "$tmp"; } && exit $exit_status
+' 0
+  trap '{ (exit 1); exit 1; }' 1 2 13 15
+}
+# Create a (secure) tmp directory for tmp files.
+
+{
+  tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` &&
+  test -n "$tmp" && test -d "$tmp"
+}  ||
+{
+  tmp=./conf$$-$RANDOM
+  (umask 077 && mkdir "$tmp")
+} ||
+{
+   echo "$me: cannot create a temporary directory in ." >&2
+   { (exit 1); exit 1; }
+}
+
+#
+# Set up the sed scripts for CONFIG_FILES section.
+#
+
+# No need to generate the scripts if there are no CONFIG_FILES.
+# This happens for instance when ./config.status config.h
+if test -n "$CONFIG_FILES"; then
+
+_ACEOF
+
+
+
+ac_delim='%!_!# '
+for ac_last_try in false false false false false :; do
+  cat >conf$$subs.sed <<_ACEOF
+SHELL!$SHELL$ac_delim
+PATH_SEPARATOR!$PATH_SEPARATOR$ac_delim
+PACKAGE_NAME!$PACKAGE_NAME$ac_delim
+PACKAGE_TARNAME!$PACKAGE_TARNAME$ac_delim
+PACKAGE_VERSION!$PACKAGE_VERSION$ac_delim
+PACKAGE_STRING!$PACKAGE_STRING$ac_delim
+PACKAGE_BUGREPORT!$PACKAGE_BUGREPORT$ac_delim
+exec_prefix!$exec_prefix$ac_delim
+prefix!$prefix$ac_delim
+program_transform_name!$program_transform_name$ac_delim
+bindir!$bindir$ac_delim
+sbindir!$sbindir$ac_delim
+libexecdir!$libexecdir$ac_delim
+datarootdir!$datarootdir$ac_delim
+datadir!$datadir$ac_delim
+sysconfdir!$sysconfdir$ac_delim
+sharedstatedir!$sharedstatedir$ac_delim
+localstatedir!$localstatedir$ac_delim
+includedir!$includedir$ac_delim
+oldincludedir!$oldincludedir$ac_delim
+docdir!$docdir$ac_delim
+infodir!$infodir$ac_delim
+htmldir!$htmldir$ac_delim
+dvidir!$dvidir$ac_delim
+pdfdir!$pdfdir$ac_delim
+psdir!$psdir$ac_delim
+libdir!$libdir$ac_delim
+localedir!$localedir$ac_delim
+mandir!$mandir$ac_delim
+DEFS!$DEFS$ac_delim
+ECHO_C!$ECHO_C$ac_delim
+ECHO_N!$ECHO_N$ac_delim
+ECHO_T!$ECHO_T$ac_delim
+LIBS!$LIBS$ac_delim
+build_alias!$build_alias$ac_delim
+host_alias!$host_alias$ac_delim
+target_alias!$target_alias$ac_delim
+SET_MAKE!$SET_MAKE$ac_delim
+subdirs!$subdirs$ac_delim
+LIBOBJS!$LIBOBJS$ac_delim
+LTLIBOBJS!$LTLIBOBJS$ac_delim
+_ACEOF
+
+  if test `sed -n "s/.*$ac_delim\$/X/p" conf$$subs.sed | grep -c X` = 41; then
+    break
+  elif $ac_last_try; then
+    { { echo "$as_me:$LINENO: error: could not make $CONFIG_STATUS" >&5
+echo "$as_me: error: could not make $CONFIG_STATUS" >&2;}
+   { (exit 1); exit 1; }; }
   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`
+    ac_delim="$ac_delim!$ac_delim _$ac_delim!! "
   fi
 done
-if test -z "$ac_sed_cmds"; then
-  ac_sed_cmds=cat
+
+ac_eof=`sed -n '/^CEOF[0-9]*$/s/CEOF/0/p' conf$$subs.sed`
+if test -n "$ac_eof"; then
+  ac_eof=`echo "$ac_eof" | sort -nru | sed 1q`
+  ac_eof=`expr $ac_eof + 1`
 fi
-EOF
-
-cat >> $CONFIG_STATUS <<EOF
-
-CONFIG_FILES=\${CONFIG_FILES-"Makefile"}
-EOF
-cat >> $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" ;;
+
+cat >>$CONFIG_STATUS <<_ACEOF
+cat >"\$tmp/subs-1.sed" <<\CEOF$ac_eof
+/@[a-zA-Z_][a-zA-Z_0-9]*@/!b end
+_ACEOF
+sed '
+s/[,\\&]/\\&/g; s/@/@|#_!!_#|/g
+s/^/s,@/; s/!/@,|#_!!_#|/
+:n
+t n
+s/'"$ac_delim"'$/,g/; t
+s/$/\\/; p
+N; s/^.*\n//; s/[,\\&]/\\&/g; s/@/@|#_!!_#|/g; b n
+' >>$CONFIG_STATUS <conf$$subs.sed
+rm -f conf$$subs.sed
+cat >>$CONFIG_STATUS <<_ACEOF
+:end
+s/|#_!!_#|//g
+CEOF$ac_eof
+_ACEOF
+
+
+# VPATH may cause trouble with some makes, so we remove $(srcdir),
+# ${srcdir} and @srcdir@ from VPATH if srcdir is ".", strip leading and
+# trailing colons and then remove the whole line if VPATH becomes empty
+# (actually we leave an empty line to preserve line numbers).
+if test "x$srcdir" = x.; then
+  ac_vpsub='/^[	 ]*VPATH[	 ]*=/{
+s/:*\$(srcdir):*/:/
+s/:*\${srcdir}:*/:/
+s/:*@srcdir@:*/:/
+s/^\([^=]*=[	 ]*\):*/\1/
+s/:*$//
+s/^[^=]*=[	 ]*$//
+}'
+fi
+
+cat >>$CONFIG_STATUS <<\_ACEOF
+fi # test -n "$CONFIG_FILES"
+
+
+for ac_tag in  :F $CONFIG_FILES
+do
+  case $ac_tag in
+  :[FHLC]) ac_mode=$ac_tag; continue;;
   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" ;;
+  case $ac_mode$ac_tag in
+  :[FHL]*:*);;
+  :L* | :C*:*) { { echo "$as_me:$LINENO: error: Invalid tag $ac_tag." >&5
+echo "$as_me: error: Invalid tag $ac_tag." >&2;}
+   { (exit 1); exit 1; }; };;
+  :[FH]-) ac_tag=-:-;;
+  :[FH]*) ac_tag=$ac_tag:$ac_tag.in;;
   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= ;;
+  ac_save_IFS=$IFS
+  IFS=:
+  set x $ac_tag
+  IFS=$ac_save_IFS
+  shift
+  ac_file=$1
+  shift
+
+  case $ac_mode in
+  :L) ac_source=$1;;
+  :[FH])
+    ac_file_inputs=
+    for ac_f
+    do
+      case $ac_f in
+      -) ac_f="$tmp/stdin";;
+      *) # Look for the file first in the build tree, then in the source tree
+	 # (if the path is not absolute).  The absolute path cannot be DOS-style,
+	 # because $ac_f cannot contain `:'.
+	 test -f "$ac_f" ||
+	   case $ac_f in
+	   [\\/$]*) false;;
+	   *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";;
+	   esac ||
+	   { { echo "$as_me:$LINENO: error: cannot find input file: $ac_f" >&5
+echo "$as_me: error: cannot find input file: $ac_f" >&2;}
+   { (exit 1); exit 1; }; };;
+      esac
+      ac_file_inputs="$ac_file_inputs $ac_f"
+    done
+
+    # Let's still pretend it is `configure' which instantiates (i.e., don't
+    # use $as_me), people would be surprised to read:
+    #    /* config.h.  Generated by config.status.  */
+    configure_input="Generated from "`IFS=:
+	  echo $* | sed 's|^[^:]*/||;s|:[^:]*/|, |g'`" by configure."
+    if test x"$ac_file" != x-; then
+      configure_input="$ac_file.  $configure_input"
+      { echo "$as_me:$LINENO: creating $ac_file" >&5
+echo "$as_me: creating $ac_file" >&6;}
+    fi
+
+    case $ac_tag in
+    *:-:* | *:-) cat >"$tmp/stdin";;
+    esac
+    ;;
   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 <<EOF
-
-EOF
-cat >> $CONFIG_STATUS <<\EOF
-
-exit 0
-EOF
+  ac_dir=`$as_dirname -- "$ac_file" ||
+$as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+	 X"$ac_file" : 'X\(//\)[^/]' \| \
+	 X"$ac_file" : 'X\(//\)$' \| \
+	 X"$ac_file" : 'X\(/\)' \| . 2>/dev/null ||
+echo X"$ac_file" |
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)[^/].*/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+  { as_dir="$ac_dir"
+  case $as_dir in #(
+  -*) as_dir=./$as_dir;;
+  esac
+  test -d "$as_dir" || { $as_mkdir_p && mkdir -p "$as_dir"; } || {
+    as_dirs=
+    while :; do
+      case $as_dir in #(
+      *\'*) as_qdir=`echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #(
+      *) as_qdir=$as_dir;;
+      esac
+      as_dirs="'$as_qdir' $as_dirs"
+      as_dir=`$as_dirname -- "$as_dir" ||
+$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+	 X"$as_dir" : 'X\(//\)[^/]' \| \
+	 X"$as_dir" : 'X\(//\)$' \| \
+	 X"$as_dir" : 'X\(/\)' \| . 2>/dev/null ||
+echo X"$as_dir" |
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)[^/].*/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+      test -d "$as_dir" && break
+    done
+    test -z "$as_dirs" || eval "mkdir $as_dirs"
+  } || test -d "$as_dir" || { { echo "$as_me:$LINENO: error: cannot create directory $as_dir" >&5
+echo "$as_me: error: cannot create directory $as_dir" >&2;}
+   { (exit 1); exit 1; }; }; }
+  ac_builddir=.
+
+case "$ac_dir" in
+.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;
+*)
+  ac_dir_suffix=/`echo "$ac_dir" | sed 's,^\.[\\/],,'`
+  # A ".." for each directory in $ac_dir_suffix.
+  ac_top_builddir_sub=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,/..,g;s,/,,'`
+  case $ac_top_builddir_sub in
+  "") ac_top_builddir_sub=. ac_top_build_prefix= ;;
+  *)  ac_top_build_prefix=$ac_top_builddir_sub/ ;;
+  esac ;;
+esac
+ac_abs_top_builddir=$ac_pwd
+ac_abs_builddir=$ac_pwd$ac_dir_suffix
+# for backward compatibility:
+ac_top_builddir=$ac_top_build_prefix
+
+case $srcdir in
+  .)  # We are building in place.
+    ac_srcdir=.
+    ac_top_srcdir=$ac_top_builddir_sub
+    ac_abs_top_srcdir=$ac_pwd ;;
+  [\\/]* | ?:[\\/]* )  # Absolute name.
+    ac_srcdir=$srcdir$ac_dir_suffix;
+    ac_top_srcdir=$srcdir
+    ac_abs_top_srcdir=$srcdir ;;
+  *) # Relative name.
+    ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix
+    ac_top_srcdir=$ac_top_build_prefix$srcdir
+    ac_abs_top_srcdir=$ac_pwd/$srcdir ;;
+esac
+ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix
+
+
+  case $ac_mode in
+  :F)
+  #
+  # CONFIG_FILE
+  #
+
+_ACEOF
+
+cat >>$CONFIG_STATUS <<\_ACEOF
+# If the template does not know about datarootdir, expand it.
+# FIXME: This hack should be removed a few years after 2.60.
+ac_datarootdir_hack=; ac_datarootdir_seen=
+
+case `sed -n '/datarootdir/ {
+  p
+  q
+}
+/@datadir@/p
+/@docdir@/p
+/@infodir@/p
+/@localedir@/p
+/@mandir@/p
+' $ac_file_inputs` in
+*datarootdir*) ac_datarootdir_seen=yes;;
+*@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*)
+  { echo "$as_me:$LINENO: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5
+echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;}
+_ACEOF
+cat >>$CONFIG_STATUS <<_ACEOF
+  ac_datarootdir_hack='
+  s&@datadir@&$datadir&g
+  s&@docdir@&$docdir&g
+  s&@infodir@&$infodir&g
+  s&@localedir@&$localedir&g
+  s&@mandir@&$mandir&g
+    s&\\\${datarootdir}&$datarootdir&g' ;;
+esac
+_ACEOF
+
+# Neutralize VPATH when `$srcdir' = `.'.
+# Shell code in configure.ac might set extrasub.
+# FIXME: do we really want to maintain this feature?
+cat >>$CONFIG_STATUS <<_ACEOF
+  sed "$ac_vpsub
+$extrasub
+_ACEOF
+cat >>$CONFIG_STATUS <<\_ACEOF
+:t
+/@[a-zA-Z_][a-zA-Z_0-9]*@/!b
+s&@configure_input@&$configure_input&;t t
+s&@top_builddir@&$ac_top_builddir_sub&;t t
+s&@srcdir@&$ac_srcdir&;t t
+s&@abs_srcdir@&$ac_abs_srcdir&;t t
+s&@top_srcdir@&$ac_top_srcdir&;t t
+s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t
+s&@builddir@&$ac_builddir&;t t
+s&@abs_builddir@&$ac_abs_builddir&;t t
+s&@abs_top_builddir@&$ac_abs_top_builddir&;t t
+$ac_datarootdir_hack
+" $ac_file_inputs | sed -f "$tmp/subs-1.sed" >$tmp/out
+
+test -z "$ac_datarootdir_hack$ac_datarootdir_seen" &&
+  { ac_out=`sed -n '/\${datarootdir}/p' "$tmp/out"`; test -n "$ac_out"; } &&
+  { ac_out=`sed -n '/^[	 ]*datarootdir[	 ]*:*=/p' "$tmp/out"`; test -z "$ac_out"; } &&
+  { echo "$as_me:$LINENO: WARNING: $ac_file contains a reference to the variable \`datarootdir'
+which seems to be undefined.  Please make sure it is defined." >&5
+echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir'
+which seems to be undefined.  Please make sure it is defined." >&2;}
+
+  rm -f "$tmp/stdin"
+  case $ac_file in
+  -) cat "$tmp/out"; rm -f "$tmp/out";;
+  *) rm -f "$ac_file"; mv "$tmp/out" $ac_file;;
+  esac
+ ;;
+
+
+
+  esac
+
+done # for ac_tag
+
+
+{ (exit 0); exit 0; }
+_ACEOF
 chmod +x $CONFIG_STATUS
-rm -fr confdefs* $ac_clean_files
-test "$no_create" = yes || ${CONFIG_SHELL-/bin/sh} $CONFIG_STATUS || exit 1
-
-
+ac_clean_files=$ac_clean_files_save
+
+
+# configure is writing to config.log, and then calls config.status.
+# config.status does its own redirection, appending to config.log.
+# Unfortunately, on DOS this fails, as config.log is still kept open
+# by configure, so config.status won't be able to write to it; its
+# output is simply discarded.  So we exec the FD to /dev/null,
+# effectively closing config.log, so it can be properly (re)opened and
+# appended to by config.status.  When coming back to configure, we
+# need to make the FD available again.
+if test "$no_create" != yes; then
+  ac_cs_success=:
+  ac_config_status_args=
+  test "$silent" = yes &&
+    ac_config_status_args="$ac_config_status_args --quiet"
+  exec 5>/dev/null
+  $SHELL $CONFIG_STATUS $ac_config_status_args || ac_cs_success=false
+  exec 5>>config.log
+  # Use ||, not &&, to avoid exiting from the if with $? = 1, which
+  # would make configure fail if this is the last instruction.
+  $ac_cs_success || { (exit 1); exit 1; }
+fi
+
+#
+# CONFIG_SUBDIRS section.
+#
 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
+  eval "set x $ac_configure_args"
+  shift
+  for ac_arg
+  do
     if test -n "$ac_prev"; then
       ac_prev=
       continue
     fi
-    case "$ac_arg" in
+    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=*)
+    | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* \
+    | --c=*)
+      ;;
+    --config-cache | -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" ;;
+    -prefix | --prefix | --prefi | --pref | --pre | --pr | --p)
+      ac_prev=prefix ;;
+    -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*)
+      ;;
+    *)
+      case $ac_arg in
+      *\'*) ac_arg=`echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;;
+      esac
+      ac_sub_configure_args="$ac_sub_configure_args '$ac_arg'" ;;
     esac
   done
 
-  for ac_config_dir in lib src tests doc; do
+  # Always prepend --prefix to ensure using the same prefix
+  # in subdir configurations.
+  ac_arg="--prefix=$prefix"
+  case $ac_arg in
+  *\'*) ac_arg=`echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;;
+  esac
+  ac_sub_configure_args="'$ac_arg' $ac_sub_configure_args"
+
+  # Pass --silent
+  if test "$silent" = yes; then
+    ac_sub_configure_args="--silent $ac_sub_configure_args"
+  fi
+
+  ac_popdir=`pwd`
+  for ac_dir in : $subdirs; do test "x$ac_dir" = x: && continue
 
     # 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
+    test -d "$srcdir/$ac_dir" || continue
+
+    ac_msg="=== configuring in $ac_dir (`pwd`/$ac_dir)"
+    echo "$as_me:$LINENO: $ac_msg" >&5
+    echo "$ac_msg" >&6
+    { as_dir="$ac_dir"
+  case $as_dir in #(
+  -*) as_dir=./$as_dir;;
+  esac
+  test -d "$as_dir" || { $as_mkdir_p && mkdir -p "$as_dir"; } || {
+    as_dirs=
+    while :; do
+      case $as_dir in #(
+      *\'*) as_qdir=`echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #(
+      *) as_qdir=$as_dir;;
+      esac
+      as_dirs="'$as_qdir' $as_dirs"
+      as_dir=`$as_dirname -- "$as_dir" ||
+$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+	 X"$as_dir" : 'X\(//\)[^/]' \| \
+	 X"$as_dir" : 'X\(//\)$' \| \
+	 X"$as_dir" : 'X\(/\)' \| . 2>/dev/null ||
+echo X"$as_dir" |
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)[^/].*/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+      test -d "$as_dir" && break
+    done
+    test -z "$as_dirs" || eval "mkdir $as_dirs"
+  } || test -d "$as_dir" || { { echo "$as_me:$LINENO: error: cannot create directory $as_dir" >&5
+echo "$as_me: error: cannot create directory $as_dir" >&2;}
+   { (exit 1); exit 1; }; }; }
+    ac_builddir=.
+
+case "$ac_dir" in
+.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;
+*)
+  ac_dir_suffix=/`echo "$ac_dir" | sed 's,^\.[\\/],,'`
+  # A ".." for each directory in $ac_dir_suffix.
+  ac_top_builddir_sub=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,/..,g;s,/,,'`
+  case $ac_top_builddir_sub in
+  "") ac_top_builddir_sub=. ac_top_build_prefix= ;;
+  *)  ac_top_build_prefix=$ac_top_builddir_sub/ ;;
+  esac ;;
+esac
+ac_abs_top_builddir=$ac_pwd
+ac_abs_builddir=$ac_pwd$ac_dir_suffix
+# for backward compatibility:
+ac_top_builddir=$ac_top_build_prefix
+
+case $srcdir in
+  .)  # We are building in place.
+    ac_srcdir=.
+    ac_top_srcdir=$ac_top_builddir_sub
+    ac_abs_top_srcdir=$ac_pwd ;;
+  [\\/]* | ?:[\\/]* )  # Absolute name.
+    ac_srcdir=$srcdir$ac_dir_suffix;
+    ac_top_srcdir=$srcdir
+    ac_abs_top_srcdir=$srcdir ;;
+  *) # Relative name.
+    ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix
+    ac_top_srcdir=$ac_top_build_prefix$srcdir
+    ac_abs_top_srcdir=$ac_pwd/$srcdir ;;
+esac
+ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix
+
+
+    cd "$ac_dir"
 
     # 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
+    if test -f "$ac_srcdir/configure.gnu"; then
+      ac_sub_configure=$ac_srcdir/configure.gnu
+    elif test -f "$ac_srcdir/configure"; then
+      ac_sub_configure=$ac_srcdir/configure
+    elif test -f "$ac_srcdir/configure.in"; then
+      # This should be Cygnus configure.
+      ac_sub_configure=$ac_aux_dir/configure
     else
-      echo "configure: warning: no configuration information is in $ac_config_dir" 1>&2
+      { echo "$as_me:$LINENO: WARNING: no configuration information is in $ac_dir" >&5
+echo "$as_me: WARNING: no configuration information is in $ac_dir" >&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" ;;
+      case $cache_file in
+      [\\/]* | ?:[\\/]* ) ac_sub_cache_file=$cache_file ;;
+      *) # Relative name.
+	ac_sub_cache_file=$ac_top_build_prefix$cache_file ;;
       esac
 
-      echo "running ${CONFIG_SHELL-/bin/sh} $ac_sub_configure $ac_sub_configure_args --cache-file=$ac_sub_cache_file --srcdir=$ac_sub_srcdir"
+      { echo "$as_me:$LINENO: running $SHELL $ac_sub_configure $ac_sub_configure_args --cache-file=$ac_sub_cache_file --srcdir=$ac_srcdir" >&5
+echo "$as_me: running $SHELL $ac_sub_configure $ac_sub_configure_args --cache-file=$ac_sub_cache_file --srcdir=$ac_srcdir" >&6;}
       # 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
+      eval "\$SHELL \"\$ac_sub_configure\" $ac_sub_configure_args \
+	   --cache-file=\"\$ac_sub_cache_file\" --srcdir=\"\$ac_srcdir\"" ||
+	{ { echo "$as_me:$LINENO: error: $ac_sub_configure failed for $ac_dir" >&5
+echo "$as_me: error: $ac_sub_configure failed for $ac_dir" >&2;}
+   { (exit 1); exit 1; }; }
     fi
 
-    cd $ac_popdir
+    cd "$ac_popdir"
   done
 fi
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/configure.ac
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/contrib/gperf/configure.ac	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,55 @@
+dnl autoconf configuration for gperf
+
+dnl Copyright (C) 1998, 2002, 2003, 2005-2007 Free Software Foundation, Inc.
+dnl Written by Douglas C. Schmidt <schmidt at ics.uci.edu>
+dnl and Bruno Haible <bruno at clisp.org>.
+dnl
+dnl This file is part of GNU GPERF.
+dnl
+dnl GNU GPERF is free software; you can redistribute it and/or modify
+dnl it under the terms of the GNU General Public License as published by
+dnl the Free Software Foundation; either version 2, or (at your option)
+dnl any later version.
+dnl
+dnl GNU GPERF is distributed in the hope that it will be useful,
+dnl but WITHOUT ANY WARRANTY; without even the implied warranty of
+dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+dnl GNU General Public License for more details.
+dnl
+dnl You should have received a copy of the GNU General Public License
+dnl along with this program; see the file COPYING.
+dnl If not, write to the Free Software Foundation, Inc.,
+dnl 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+
+AC_PREREQ([2.60])
+AC_INIT(doc/gperf.1)
+AC_PROG_MAKE_SET
+AC_OBJEXT
+AC_EXEEXT
+
+dnl An autoconf-2.52 bug: AC_CONFIG_SUBDIRS requires AC_CONFIG_AUX_DIR_DEFAULT.
+ac_aux_dir=$srcdir
+AC_PROVIDE([AC_CONFIG_AUX_DIR_DEFAULT])
+AC_CONFIG_SUBDIRS(lib src tests doc)
+
+dnl This piece of sed script replaces every line containing '@subdir@'
+dnl by several consecutive lines, each referencing one subdir.
+extrasub="$extrasub"'
+/@subdir@/{
+h
+g
+s/@subdir@/lib/
+p
+g
+s/@subdir@/src/
+p
+g
+s/@subdir@/tests/
+p
+g
+s/@subdir@/doc/
+p
+d
+}
+'
+AC_OUTPUT(Makefile)
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/configure.in
--- a/head/contrib/gperf/configure.in	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,46 +0,0 @@
-dnl autoconf configuration for gperf
-
-dnl Copyright (C) 1998 Free Software Foundation, Inc.
-dnl written by Douglas C. Schmidt (schmidt at ics.uci.edu)
-dnl
-dnl This file is part of GNU GPERF.
-dnl
-dnl GNU GPERF is free software; you can redistribute it and/or modify
-dnl it under the terms of the GNU General Public License as published by
-dnl the Free Software Foundation; either version 1, or (at your option)
-dnl any later version.
-dnl
-dnl GNU GPERF is distributed in the hope that it will be useful,
-dnl but WITHOUT ANY WARRANTY; without even the implied warranty of
-dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-dnl GNU General Public License for more details.
-dnl
-dnl You should have received a copy of the GNU General Public License
-dnl along with GNU GPERF; see the file COPYING.  If not, write to the
-dnl Free Software Foundation, 59 Temple Place - Suite 330, Boston,
-dnl MA 02111-1307, USA.
-
-AC_INIT(doc/gperf.1)
-AC_PROG_MAKE_SET
-dnl This piece of sed script replaces every line containing '@subdir@'
-dnl by several consecutive lines, each referencing one subdir.
-extrasub="$extrasub"'
-/@subdir@/{
-h
-g
-s/@subdir@/lib/
-p
-g
-s/@subdir@/src/
-p
-g
-s/@subdir@/tests/
-p
-g
-s/@subdir@/doc/
-p
-d
-}
-'
-AC_OUTPUT(Makefile)
-AC_OUTPUT_SUBDIRS(lib src tests doc)
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/doc/Makefile.in
--- a/head/contrib/gperf/doc/Makefile.in	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/contrib/gperf/doc/Makefile.in	Tue Dec 06 20:26:16 2011 +0200
@@ -1,12 +1,14 @@
 # Makefile for gperf/doc
 
-# Copyright (C) 1998, 2000 Free Software Foundation, Inc.
+# Copyright (C) 1998, 2000, 2002-2003, 2007 Free Software Foundation, Inc.
+# Written by Douglas C. Schmidt <schmidt at ics.uci.edu>
+# and Bruno Haible <bruno at clisp.org>.
 #
 # This file is part of GNU GPERF.
 #
 # GNU GPERF 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 1, or (at your option)
+# the Free Software Foundation; either version 2, or (at your option)
 # any later version.
 #
 # GNU GPERF is distributed in the hope that it will be useful,
@@ -15,8 +17,9 @@
 # GNU General Public License for more details.
 #
 # You should have received a copy of the GNU General Public License
-# along with GNU GPERF; see the file COPYING.  If not, write to the Free
-# Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111, USA.
+# along with this program; see the file COPYING.
+# If not, write to the Free Software Foundation, Inc.,
+# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
 
 #### Start of system configuration section. ####
 
@@ -27,14 +30,16 @@
 prefix = @prefix@
 local_prefix = /usr/local
 exec_prefix = @exec_prefix@
+datarootdir = @datarootdir@
 datadir = @datadir@
 infodir = @infodir@
 mandir = @mandir@
 man1dir = $(mandir)/man1
-docdir = $(prefix)/doc/@PACKAGE@
-dvidir = $(docdir)
-psdir = $(docdir)
-htmldir = $(docdir)
+docdir = @docdir@
+dvidir = @dvidir@
+psdir = @psdir@
+pdfdir = @pdfdir@
+htmldir = @htmldir@
 
 # Programs used by "make":
 RM = rm -f
@@ -44,7 +49,8 @@
 TEX = tex
 TEXI2DVI = texi2dvi
 DVIPS = dvips -D600
-MAKEINFO = LANG= LANGUAGE= makeinfo
+TEXI2PDF = texi2pdf
+MAKEINFO = LANG= LC_MESSAGES= LC_ALL= LANGUAGE= makeinfo
 TEXI2HTML = texi2html
 
 # Programs used by "make install":
@@ -59,7 +65,7 @@
 
 VPATH = $(srcdir)
 
-all : info dvi ps html
+all : info ps pdf html
 
 
 info : $(srcdir)/gperf.info
@@ -79,7 +85,15 @@
 ps : $(srcdir)/gperf.ps
 
 $(srcdir)/gperf.ps : $(srcdir)/gperf.dvi
-	$(DVIPS) -o $@ $<
+	$(DVIPS) -o $@ $(srcdir)/gperf.dvi
+
+
+pdf : $(srcdir)/gperf.pdf
+
+$(srcdir)/gperf.pdf : $(srcdir)/gperf.texi $(srcdir)/gpl.texinfo
+	cd $(srcdir) && $(RM) gperf.aux gperf.toc gperf.cp gperf.fn gperf.ky gperf.pg gperf.tp gperf.vr gperf.log gperf.cps
+	cd $(srcdir) && $(TEXI2PDF) gperf.texi
+	cd $(srcdir) && $(RM) gperf.aux gperf.toc gperf.cp gperf.fn gperf.ky gperf.pg gperf.tp gperf.vr gperf.log gperf.cps
 
 
 html : gperf.html gperf_toc.html
@@ -100,7 +114,9 @@
 #	$(MKINSTALLDIRS) $(DESTDIR)$(dvidir)
 #	$(INSTALL_DATA) $(srcdir)/gperf.dvi $(DESTDIR)$(dvidir)/gperf.dvi
 #	$(MKINSTALLDIRS) $(DESTDIR)$(psdir)
-#	$(INSTALL_DATA) $(srcdir)/gperf.ps $(DESTDIR)$(dvidir)/gperf.ps
+#	$(INSTALL_DATA) $(srcdir)/gperf.ps $(DESTDIR)$(psdir)/gperf.ps
+#	$(MKINSTALLDIRS) $(DESTDIR)$(pdfdir)
+#	$(INSTALL_DATA) $(srcdir)/gperf.pdf $(DESTDIR)$(pdfdir)/gperf.pdf
 	$(MKINSTALLDIRS) $(DESTDIR)$(htmldir)
 	$(INSTALL_DATA) $(srcdir)/gperf.html $(DESTDIR)$(htmldir)/gperf.html
 
@@ -109,6 +125,7 @@
 	$(MKINSTALLDIRS) $(DESTDIR)$(man1dir)
 #	$(MKINSTALLDIRS) $(DESTDIR)$(dvidir)
 #	$(MKINSTALLDIRS) $(DESTDIR)$(psdir)
+#	$(MKINSTALLDIRS) $(DESTDIR)$(pdfdir)
 	$(MKINSTALLDIRS) $(DESTDIR)$(htmldir)
 
 uninstall : force
@@ -116,6 +133,7 @@
 	$(RM) $(DESTDIR)$(man1dir)/gperf.1
 #	$(RM) $(DESTDIR)$(dvidir)/gperf.dvi
 #	$(RM) $(DESTDIR)$(psdir)/gperf.ps
+#	$(RM) $(DESTDIR)$(pdfdir)/gperf.pdf
 	$(RM) $(DESTDIR)$(htmldir)/gperf.html
 
 check : all
@@ -129,7 +147,7 @@
 	$(RM) config.status config.log config.cache Makefile
 
 maintainer-clean : distclean
-	$(RM) *.info *.dvi *.ps *.html
+	$(RM) *.info *.dvi *.ps *.pdf *.html
 
 force :
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/doc/configure
--- a/head/contrib/gperf/doc/configure	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/contrib/gperf/doc/configure	Tue Dec 06 20:26:16 2011 +0200
@@ -1,26 +1,640 @@
 #! /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.
+# Generated by GNU Autoconf 2.61.
 #
+# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001,
+# 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc.
 # This configure script is free software; the Free Software Foundation
 # gives unlimited permission to copy, distribute and modify it.
+## --------------------- ##
+## M4sh Initialization.  ##
+## --------------------- ##
 
-# Defaults:
-ac_help=
+# Be more Bourne compatible
+DUALCASE=1; export DUALCASE # for MKS sh
+if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
+  emulate sh
+  NULLCMD=:
+  # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
+  # is contrary to our usage.  Disable this feature.
+  alias -g '${1+"$@"}'='"$@"'
+  setopt NO_GLOB_SUBST
+else
+  case `(set -o) 2>/dev/null` in
+  *posix*) set -o posix ;;
+esac
+
+fi
+
+
+
+
+# PATH needs CR
+# Avoid depending upon Character Ranges.
+as_cr_letters='abcdefghijklmnopqrstuvwxyz'
+as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
+as_cr_Letters=$as_cr_letters$as_cr_LETTERS
+as_cr_digits='0123456789'
+as_cr_alnum=$as_cr_Letters$as_cr_digits
+
+# The user is always right.
+if test "${PATH_SEPARATOR+set}" != set; then
+  echo "#! /bin/sh" >conf$$.sh
+  echo  "exit 0"   >>conf$$.sh
+  chmod +x conf$$.sh
+  if (PATH="/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then
+    PATH_SEPARATOR=';'
+  else
+    PATH_SEPARATOR=:
+  fi
+  rm -f conf$$.sh
+fi
+
+# Support unset when possible.
+if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then
+  as_unset=unset
+else
+  as_unset=false
+fi
+
+
+# IFS
+# We need space, tab and new line, in precisely that order.  Quoting is
+# there to prevent editors from complaining about space-tab.
+# (If _AS_PATH_WALK were called with IFS unset, it would disable word
+# splitting by setting IFS to empty value.)
+as_nl='
+'
+IFS=" ""	$as_nl"
+
+# Find who we are.  Look in the path if we contain no directory separator.
+case $0 in
+  *[\\/]* ) as_myself=$0 ;;
+  *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+  test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break
+done
+IFS=$as_save_IFS
+
+     ;;
+esac
+# We did not find ourselves, most probably we were run as `sh COMMAND'
+# in which case we are not to be found in the path.
+if test "x$as_myself" = x; then
+  as_myself=$0
+fi
+if test ! -f "$as_myself"; then
+  echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2
+  { (exit 1); exit 1; }
+fi
+
+# Work around bugs in pre-3.0 UWIN ksh.
+for as_var in ENV MAIL MAILPATH
+do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var
+done
+PS1='$ '
+PS2='> '
+PS4='+ '
+
+# NLS nuisances.
+for as_var in \
+  LANG LANGUAGE LC_ADDRESS LC_ALL LC_COLLATE LC_CTYPE LC_IDENTIFICATION \
+  LC_MEASUREMENT LC_MESSAGES LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER \
+  LC_TELEPHONE LC_TIME
+do
+  if (set +x; test -z "`(eval $as_var=C; export $as_var) 2>&1`"); then
+    eval $as_var=C; export $as_var
+  else
+    ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var
+  fi
+done
+
+# Required to use basename.
+if expr a : '\(a\)' >/dev/null 2>&1 &&
+   test "X`expr 00001 : '.*\(...\)'`" = X001; then
+  as_expr=expr
+else
+  as_expr=false
+fi
+
+if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then
+  as_basename=basename
+else
+  as_basename=false
+fi
+
+
+# Name of the executable.
+as_me=`$as_basename -- "$0" ||
+$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
+	 X"$0" : 'X\(//\)$' \| \
+	 X"$0" : 'X\(/\)' \| . 2>/dev/null ||
+echo X/"$0" |
+    sed '/^.*\/\([^/][^/]*\)\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\/\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\/\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+
+# CDPATH.
+$as_unset CDPATH
+
+
+if test "x$CONFIG_SHELL" = x; then
+  if (eval ":") 2>/dev/null; then
+  as_have_required=yes
+else
+  as_have_required=no
+fi
+
+  if test $as_have_required = yes && 	 (eval ":
+(as_func_return () {
+  (exit \$1)
+}
+as_func_success () {
+  as_func_return 0
+}
+as_func_failure () {
+  as_func_return 1
+}
+as_func_ret_success () {
+  return 0
+}
+as_func_ret_failure () {
+  return 1
+}
+
+exitcode=0
+if as_func_success; then
+  :
+else
+  exitcode=1
+  echo as_func_success failed.
+fi
+
+if as_func_failure; then
+  exitcode=1
+  echo as_func_failure succeeded.
+fi
+
+if as_func_ret_success; then
+  :
+else
+  exitcode=1
+  echo as_func_ret_success failed.
+fi
+
+if as_func_ret_failure; then
+  exitcode=1
+  echo as_func_ret_failure succeeded.
+fi
+
+if ( set x; as_func_ret_success y && test x = \"\$1\" ); then
+  :
+else
+  exitcode=1
+  echo positional parameters were not saved.
+fi
+
+test \$exitcode = 0) || { (exit 1); exit 1; }
+
+(
+  as_lineno_1=\$LINENO
+  as_lineno_2=\$LINENO
+  test \"x\$as_lineno_1\" != \"x\$as_lineno_2\" &&
+  test \"x\`expr \$as_lineno_1 + 1\`\" = \"x\$as_lineno_2\") || { (exit 1); exit 1; }
+") 2> /dev/null; then
+  :
+else
+  as_candidate_shells=
+    as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+  case $as_dir in
+	 /*)
+	   for as_base in sh bash ksh sh5; do
+	     as_candidate_shells="$as_candidate_shells $as_dir/$as_base"
+	   done;;
+       esac
+done
+IFS=$as_save_IFS
+
+
+      for as_shell in $as_candidate_shells $SHELL; do
+	 # Try only shells that exist, to save several forks.
+	 if { test -f "$as_shell" || test -f "$as_shell.exe"; } &&
+		{ ("$as_shell") 2> /dev/null <<\_ASEOF
+if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
+  emulate sh
+  NULLCMD=:
+  # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
+  # is contrary to our usage.  Disable this feature.
+  alias -g '${1+"$@"}'='"$@"'
+  setopt NO_GLOB_SUBST
+else
+  case `(set -o) 2>/dev/null` in
+  *posix*) set -o posix ;;
+esac
+
+fi
+
+
+:
+_ASEOF
+}; then
+  CONFIG_SHELL=$as_shell
+	       as_have_required=yes
+	       if { "$as_shell" 2> /dev/null <<\_ASEOF
+if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
+  emulate sh
+  NULLCMD=:
+  # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
+  # is contrary to our usage.  Disable this feature.
+  alias -g '${1+"$@"}'='"$@"'
+  setopt NO_GLOB_SUBST
+else
+  case `(set -o) 2>/dev/null` in
+  *posix*) set -o posix ;;
+esac
+
+fi
+
+
+:
+(as_func_return () {
+  (exit $1)
+}
+as_func_success () {
+  as_func_return 0
+}
+as_func_failure () {
+  as_func_return 1
+}
+as_func_ret_success () {
+  return 0
+}
+as_func_ret_failure () {
+  return 1
+}
+
+exitcode=0
+if as_func_success; then
+  :
+else
+  exitcode=1
+  echo as_func_success failed.
+fi
+
+if as_func_failure; then
+  exitcode=1
+  echo as_func_failure succeeded.
+fi
+
+if as_func_ret_success; then
+  :
+else
+  exitcode=1
+  echo as_func_ret_success failed.
+fi
+
+if as_func_ret_failure; then
+  exitcode=1
+  echo as_func_ret_failure succeeded.
+fi
+
+if ( set x; as_func_ret_success y && test x = "$1" ); then
+  :
+else
+  exitcode=1
+  echo positional parameters were not saved.
+fi
+
+test $exitcode = 0) || { (exit 1); exit 1; }
+
+(
+  as_lineno_1=$LINENO
+  as_lineno_2=$LINENO
+  test "x$as_lineno_1" != "x$as_lineno_2" &&
+  test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2") || { (exit 1); exit 1; }
+
+_ASEOF
+}; then
+  break
+fi
+
+fi
+
+      done
+
+      if test "x$CONFIG_SHELL" != x; then
+  for as_var in BASH_ENV ENV
+        do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var
+        done
+        export CONFIG_SHELL
+        exec "$CONFIG_SHELL" "$as_myself" ${1+"$@"}
+fi
+
+
+    if test $as_have_required = no; then
+  echo This script requires a shell more modern than all the
+      echo shells that I found on your system.  Please install a
+      echo modern shell, or manually run the script under such a
+      echo shell if you do have one.
+      { (exit 1); exit 1; }
+fi
+
+
+fi
+
+fi
+
+
+
+(eval "as_func_return () {
+  (exit \$1)
+}
+as_func_success () {
+  as_func_return 0
+}
+as_func_failure () {
+  as_func_return 1
+}
+as_func_ret_success () {
+  return 0
+}
+as_func_ret_failure () {
+  return 1
+}
+
+exitcode=0
+if as_func_success; then
+  :
+else
+  exitcode=1
+  echo as_func_success failed.
+fi
+
+if as_func_failure; then
+  exitcode=1
+  echo as_func_failure succeeded.
+fi
+
+if as_func_ret_success; then
+  :
+else
+  exitcode=1
+  echo as_func_ret_success failed.
+fi
+
+if as_func_ret_failure; then
+  exitcode=1
+  echo as_func_ret_failure succeeded.
+fi
+
+if ( set x; as_func_ret_success y && test x = \"\$1\" ); then
+  :
+else
+  exitcode=1
+  echo positional parameters were not saved.
+fi
+
+test \$exitcode = 0") || {
+  echo No shell found that supports shell functions.
+  echo Please tell autoconf at gnu.org about your system,
+  echo including any error possibly output before this
+  echo message
+}
+
+
+
+  as_lineno_1=$LINENO
+  as_lineno_2=$LINENO
+  test "x$as_lineno_1" != "x$as_lineno_2" &&
+  test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2" || {
+
+  # Create $as_me.lineno as a copy of $as_myself, but with $LINENO
+  # uniformly replaced by the line number.  The first 'sed' inserts a
+  # line-number line after each line using $LINENO; the second 'sed'
+  # does the real work.  The second script uses 'N' to pair each
+  # line-number line with the line containing $LINENO, and appends
+  # trailing '-' during substitution so that $LINENO is not a special
+  # case at line end.
+  # (Raja R Harinath suggested sed '=', and Paul Eggert wrote the
+  # scripts with optimization help from Paolo Bonzini.  Blame Lee
+  # E. McMahon (1931-1989) for sed's syntax.  :-)
+  sed -n '
+    p
+    /[$]LINENO/=
+  ' <$as_myself |
+    sed '
+      s/[$]LINENO.*/&-/
+      t lineno
+      b
+      :lineno
+      N
+      :loop
+      s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/
+      t loop
+      s/-\n.*//
+    ' >$as_me.lineno &&
+  chmod +x "$as_me.lineno" ||
+    { echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2
+   { (exit 1); exit 1; }; }
+
+  # Don't try to exec as it changes $[0], causing all sort of problems
+  # (the dirname of $[0] is not the place where we might find the
+  # original and so on.  Autoconf is especially sensitive to this).
+  . "./$as_me.lineno"
+  # Exit status is that of the last command.
+  exit
+}
+
+
+if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then
+  as_dirname=dirname
+else
+  as_dirname=false
+fi
+
+ECHO_C= ECHO_N= ECHO_T=
+case `echo -n x` in
+-n*)
+  case `echo 'x\c'` in
+  *c*) ECHO_T='	';;	# ECHO_T is single tab character.
+  *)   ECHO_C='\c';;
+  esac;;
+*)
+  ECHO_N='-n';;
+esac
+
+if expr a : '\(a\)' >/dev/null 2>&1 &&
+   test "X`expr 00001 : '.*\(...\)'`" = X001; then
+  as_expr=expr
+else
+  as_expr=false
+fi
+
+rm -f conf$$ conf$$.exe conf$$.file
+if test -d conf$$.dir; then
+  rm -f conf$$.dir/conf$$.file
+else
+  rm -f conf$$.dir
+  mkdir conf$$.dir
+fi
+echo >conf$$.file
+if ln -s conf$$.file conf$$ 2>/dev/null; then
+  as_ln_s='ln -s'
+  # ... but there are two gotchas:
+  # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail.
+  # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable.
+  # In both cases, we have to default to `cp -p'.
+  ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe ||
+    as_ln_s='cp -p'
+elif ln conf$$.file conf$$ 2>/dev/null; then
+  as_ln_s=ln
+else
+  as_ln_s='cp -p'
+fi
+rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file
+rmdir conf$$.dir 2>/dev/null
+
+if mkdir -p . 2>/dev/null; then
+  as_mkdir_p=:
+else
+  test -d ./-p && rmdir ./-p
+  as_mkdir_p=false
+fi
+
+if test -x / >/dev/null 2>&1; then
+  as_test_x='test -x'
+else
+  if ls -dL / >/dev/null 2>&1; then
+    as_ls_L_option=L
+  else
+    as_ls_L_option=
+  fi
+  as_test_x='
+    eval sh -c '\''
+      if test -d "$1"; then
+        test -d "$1/.";
+      else
+	case $1 in
+        -*)set "./$1";;
+	esac;
+	case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in
+	???[sx]*):;;*)false;;esac;fi
+    '\'' sh
+  '
+fi
+as_executable_p=$as_test_x
+
+# Sed expression to map a string onto a valid CPP name.
+as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
+
+# Sed expression to map a string onto a valid variable name.
+as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'"
+
+
+
+exec 7<&0 </dev/null 6>&1
+
+# Name of the host.
+# hostname on some systems (SVR3.2, Linux) returns a bogus exit status,
+# so uname gets run too.
+ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q`
+
+#
+# Initializations.
+#
 ac_default_prefix=/usr/local
-# Any additions from configure.in:
+ac_clean_files=
+ac_config_libobj_dir=.
+LIBOBJS=
+cross_compiling=no
+subdirs=
+MFLAGS=
+MAKEFLAGS=
+SHELL=${CONFIG_SHELL-/bin/sh}
+
+# Identity of this package.
+PACKAGE_NAME=
+PACKAGE_TARNAME=
+PACKAGE_VERSION=
+PACKAGE_STRING=
+PACKAGE_BUGREPORT=
+
+ac_unique_file="gperf.1"
+ac_subst_vars='SHELL
+PATH_SEPARATOR
+PACKAGE_NAME
+PACKAGE_TARNAME
+PACKAGE_VERSION
+PACKAGE_STRING
+PACKAGE_BUGREPORT
+exec_prefix
+prefix
+program_transform_name
+bindir
+sbindir
+libexecdir
+datarootdir
+datadir
+sysconfdir
+sharedstatedir
+localstatedir
+includedir
+oldincludedir
+docdir
+infodir
+htmldir
+dvidir
+pdfdir
+psdir
+libdir
+localedir
+mandir
+DEFS
+ECHO_C
+ECHO_N
+ECHO_T
+LIBS
+build_alias
+host_alias
+target_alias
+PACKAGE
+SET_MAKE
+INSTALL
+INSTALL_PROGRAM
+INSTALL_DATA
+LIBOBJS
+LTLIBOBJS'
+ac_subst_files=''
+      ac_precious_vars='build_alias
+host_alias
+target_alias'
+
 
 # Initialize some variables set by options.
+ac_init_help=
+ac_init_version=false
 # The variables have the same names as the options, with
 # dashes changed to underlines.
-build=NONE
-cache_file=./config.cache
+cache_file=/dev/null
 exec_prefix=NONE
-host=NONE
 no_create=
-nonopt=NONE
 no_recursion=
 prefix=NONE
 program_prefix=NONE
@@ -29,94 +643,117 @@
 silent=
 site=
 srcdir=
-target=NONE
 verbose=
 x_includes=NONE
 x_libraries=NONE
+
+# Installation directory options.
+# These are left unexpanded so users can "make install exec_prefix=/foo"
+# and all the variables that are supposed to be based on exec_prefix
+# by default will actually change.
+# Use braces instead of parens because sh, perl, etc. also accept them.
+# (The list follows the same order as the GNU Coding Standards.)
 bindir='${exec_prefix}/bin'
 sbindir='${exec_prefix}/sbin'
 libexecdir='${exec_prefix}/libexec'
-datadir='${prefix}/share'
+datarootdir='${prefix}/share'
+datadir='${datarootdir}'
 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
+docdir='${datarootdir}/doc/${PACKAGE}'
+infodir='${datarootdir}/info'
+htmldir='${docdir}'
+dvidir='${docdir}'
+pdfdir='${docdir}'
+psdir='${docdir}'
+libdir='${exec_prefix}/lib'
+localedir='${datarootdir}/locale'
+mandir='${datarootdir}/man'
 
 ac_prev=
+ac_dashdash=
 for ac_option
 do
-
   # If the previous option needs an argument, assign it.
   if test -n "$ac_prev"; then
-    eval "$ac_prev=\$ac_option"
+    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= ;;
+  case $ac_option in
+  *=*)	ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;;
+  *)	ac_optarg=yes ;;
   esac
 
   # Accept the important Cygnus configure options, so we can diagnose typos.
 
-  case "$ac_option" in
+  case $ac_dashdash$ac_option in
+  --)
+    ac_dashdash=yes ;;
 
   -bindir | --bindir | --bindi | --bind | --bin | --bi)
     ac_prev=bindir ;;
   -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*)
-    bindir="$ac_optarg" ;;
+    bindir=$ac_optarg ;;
 
   -build | --build | --buil | --bui | --bu)
-    ac_prev=build ;;
+    ac_prev=build_alias ;;
   -build=* | --build=* | --buil=* | --bui=* | --bu=*)
-    build="$ac_optarg" ;;
+    build_alias=$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" ;;
+    cache_file=$ac_optarg ;;
 
-  -datadir | --datadir | --datadi | --datad | --data | --dat | --da)
+  --config-cache | -C)
+    cache_file=config.cache ;;
+
+  -datadir | --datadir | --datadi | --datad)
     ac_prev=datadir ;;
-  -datadir=* | --datadir=* | --datadi=* | --datad=* | --data=* | --dat=* \
-  | --da=*)
-    datadir="$ac_optarg" ;;
+  -datadir=* | --datadir=* | --datadi=* | --datad=*)
+    datadir=$ac_optarg ;;
+
+  -datarootdir | --datarootdir | --datarootdi | --datarootd | --dataroot \
+  | --dataroo | --dataro | --datar)
+    ac_prev=datarootdir ;;
+  -datarootdir=* | --datarootdir=* | --datarootdi=* | --datarootd=* \
+  | --dataroot=* | --dataroo=* | --dataro=* | --datar=*)
+    datarootdir=$ac_optarg ;;
 
   -disable-* | --disable-*)
-    ac_feature=`echo $ac_option|sed -e 's/-*disable-//'`
+    ac_feature=`expr "x$ac_option" : 'x-*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" ;;
+    expr "x$ac_feature" : ".*[^-._$as_cr_alnum]" >/dev/null &&
+      { echo "$as_me: error: invalid feature name: $ac_feature" >&2
+   { (exit 1); exit 1; }; }
+    ac_feature=`echo $ac_feature | sed 's/[-.]/_/g'`
+    eval enable_$ac_feature=no ;;
+
+  -docdir | --docdir | --docdi | --doc | --do)
+    ac_prev=docdir ;;
+  -docdir=* | --docdir=* | --docdi=* | --doc=* | --do=*)
+    docdir=$ac_optarg ;;
+
+  -dvidir | --dvidir | --dvidi | --dvid | --dvi | --dv)
+    ac_prev=dvidir ;;
+  -dvidir=* | --dvidir=* | --dvidi=* | --dvid=* | --dvi=* | --dv=*)
+    dvidir=$ac_optarg ;;
 
   -enable-* | --enable-*)
-    ac_feature=`echo $ac_option|sed -e 's/-*enable-//' -e 's/=.*//'`
+    ac_feature=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'`
     # 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'" ;;
+    expr "x$ac_feature" : ".*[^-._$as_cr_alnum]" >/dev/null &&
+      { echo "$as_me: error: invalid feature name: $ac_feature" >&2
+   { (exit 1); exit 1; }; }
+    ac_feature=`echo $ac_feature | sed 's/[-.]/_/g'`
+    eval enable_$ac_feature=\$ac_optarg ;;
 
   -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \
   | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \
@@ -125,116 +762,77 @@
   -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \
   | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \
   | --exec=* | --exe=* | --ex=*)
-    exec_prefix="$ac_optarg" ;;
+    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 ;;
+  -help | --help | --hel | --he | -h)
+    ac_init_help=long ;;
+  -help=r* | --help=r* | --hel=r* | --he=r* | -hr*)
+    ac_init_help=recursive ;;
+  -help=s* | --help=s* | --hel=s* | --he=s* | -hs*)
+    ac_init_help=short ;;
 
   -host | --host | --hos | --ho)
-    ac_prev=host ;;
+    ac_prev=host_alias ;;
   -host=* | --host=* | --hos=* | --ho=*)
-    host="$ac_optarg" ;;
+    host_alias=$ac_optarg ;;
+
+  -htmldir | --htmldir | --htmldi | --htmld | --html | --htm | --ht)
+    ac_prev=htmldir ;;
+  -htmldir=* | --htmldir=* | --htmldi=* | --htmld=* | --html=* | --htm=* \
+  | --ht=*)
+    htmldir=$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" ;;
+    includedir=$ac_optarg ;;
 
   -infodir | --infodir | --infodi | --infod | --info | --inf)
     ac_prev=infodir ;;
   -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*)
-    infodir="$ac_optarg" ;;
+    infodir=$ac_optarg ;;
 
   -libdir | --libdir | --libdi | --libd)
     ac_prev=libdir ;;
   -libdir=* | --libdir=* | --libdi=* | --libd=*)
-    libdir="$ac_optarg" ;;
+    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" ;;
+    libexecdir=$ac_optarg ;;
+
+  -localedir | --localedir | --localedi | --localed | --locale)
+    ac_prev=localedir ;;
+  -localedir=* | --localedir=* | --localedi=* | --localed=* | --locale=*)
+    localedir=$ac_optarg ;;
 
   -localstatedir | --localstatedir | --localstatedi | --localstated \
-  | --localstate | --localstat | --localsta | --localst \
-  | --locals | --local | --loca | --loc | --lo)
+  | --localstate | --localstat | --localsta | --localst | --locals)
     ac_prev=localstatedir ;;
   -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \
-  | --localstate=* | --localstat=* | --localsta=* | --localst=* \
-  | --locals=* | --local=* | --loca=* | --loc=* | --lo=*)
-    localstatedir="$ac_optarg" ;;
+  | --localstate=* | --localstat=* | --localsta=* | --localst=* | --locals=*)
+    localstatedir=$ac_optarg ;;
 
   -mandir | --mandir | --mandi | --mand | --man | --ma | --m)
     ac_prev=mandir ;;
   -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*)
-    mandir="$ac_optarg" ;;
+    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-cr | --no-c | -n)
     no_create=yes ;;
 
   -no-recursion | --no-recursion | --no-recursio | --no-recursi \
@@ -248,26 +846,26 @@
   -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \
   | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \
   | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*)
-    oldincludedir="$ac_optarg" ;;
+    oldincludedir=$ac_optarg ;;
 
   -prefix | --prefix | --prefi | --pref | --pre | --pr | --p)
     ac_prev=prefix ;;
   -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*)
-    prefix="$ac_optarg" ;;
+    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_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_suffix=$ac_optarg ;;
 
   -program-transform-name | --program-transform-name \
   | --program-transform-nam | --program-transform-na \
@@ -284,7 +882,17 @@
   | --program-transfo=* | --program-transf=* \
   | --program-trans=* | --program-tran=* \
   | --progr-tra=* | --program-tr=* | --program-t=*)
-    program_transform_name="$ac_optarg" ;;
+    program_transform_name=$ac_optarg ;;
+
+  -pdfdir | --pdfdir | --pdfdi | --pdfd | --pdf | --pd)
+    ac_prev=pdfdir ;;
+  -pdfdir=* | --pdfdir=* | --pdfdi=* | --pdfd=* | --pdf=* | --pd=*)
+    pdfdir=$ac_optarg ;;
+
+  -psdir | --psdir | --psdi | --psd | --ps)
+    ac_prev=psdir ;;
+  -psdir=* | --psdir=* | --psdi=* | --psd=* | --ps=*)
+    psdir=$ac_optarg ;;
 
   -q | -quiet | --quiet | --quie | --qui | --qu | --q \
   | -silent | --silent | --silen | --sile | --sil)
@@ -294,7 +902,7 @@
     ac_prev=sbindir ;;
   -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \
   | --sbi=* | --sb=*)
-    sbindir="$ac_optarg" ;;
+    sbindir=$ac_optarg ;;
 
   -sharedstatedir | --sharedstatedir | --sharedstatedi \
   | --sharedstated | --sharedstate | --sharedstat | --sharedsta \
@@ -305,58 +913,53 @@
   | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \
   | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \
   | --sha=* | --sh=*)
-    sharedstatedir="$ac_optarg" ;;
+    sharedstatedir=$ac_optarg ;;
 
   -site | --site | --sit)
     ac_prev=site ;;
   -site=* | --site=* | --sit=*)
-    site="$ac_optarg" ;;
+    site=$ac_optarg ;;
 
   -srcdir | --srcdir | --srcdi | --srcd | --src | --sr)
     ac_prev=srcdir ;;
   -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*)
-    srcdir="$ac_optarg" ;;
+    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" ;;
+    sysconfdir=$ac_optarg ;;
 
   -target | --target | --targe | --targ | --tar | --ta | --t)
-    ac_prev=target ;;
+    ac_prev=target_alias ;;
   -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*)
-    target="$ac_optarg" ;;
+    target_alias=$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 ;;
+  -version | --version | --versio | --versi | --vers | -V)
+    ac_init_version=: ;;
 
   -with-* | --with-*)
-    ac_package=`echo $ac_option|sed -e 's/-*with-//' -e 's/=.*//'`
+    ac_package=`expr "x$ac_option" : 'x-*with-\([^=]*\)'`
     # 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'" ;;
+    expr "x$ac_package" : ".*[^-._$as_cr_alnum]" >/dev/null &&
+      { echo "$as_me: error: invalid package name: $ac_package" >&2
+   { (exit 1); exit 1; }; }
+    ac_package=`echo $ac_package | sed 's/[-.]/_/g'`
+    eval with_$ac_package=\$ac_optarg ;;
 
   -without-* | --without-*)
-    ac_package=`echo $ac_option|sed -e 's/-*without-//'`
+    ac_package=`expr "x$ac_option" : 'x-*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" ;;
+    expr "x$ac_package" : ".*[^-._$as_cr_alnum]" >/dev/null &&
+      { echo "$as_me: error: invalid package name: $ac_package" >&2
+   { (exit 1); exit 1; }; }
+    ac_package=`echo $ac_package | sed 's/[-.]/_/g'`
+    eval with_$ac_package=no ;;
 
   --x)
     # Obsolete; use --with-x.
@@ -367,186 +970,674 @@
     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_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" ;;
+    x_libraries=$ac_optarg ;;
 
-  -*) { echo "configure: error: $ac_option: invalid option; use --help to show usage" 1>&2; exit 1; }
+  -*) { echo "$as_me: error: unrecognized option: $ac_option
+Try \`$0 --help' for more information." >&2
+   { (exit 1); exit 1; }; }
     ;;
 
+  *=*)
+    ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='`
+    # Reject names that are not valid shell variable names.
+    expr "x$ac_envvar" : ".*[^_$as_cr_alnum]" >/dev/null &&
+      { echo "$as_me: error: invalid variable name: $ac_envvar" >&2
+   { (exit 1); exit 1; }; }
+    eval $ac_envvar=\$ac_optarg
+    export $ac_envvar ;;
+
   *)
-    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"
+    # FIXME: should be removed in autoconf 3.0.
+    echo "$as_me: WARNING: you should use --build, --host, --target" >&2
+    expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null &&
+      echo "$as_me: WARNING: invalid host type: $ac_option" >&2
+    : ${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$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; }
+  ac_option=--`echo $ac_prev | sed 's/_/-/g'`
+  { echo "$as_me: error: missing argument to $ac_option" >&2
+   { (exit 1); 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
+# Be sure to have absolute directory names.
+for ac_var in	exec_prefix prefix bindir sbindir libexecdir datarootdir \
+		datadir sysconfdir sharedstatedir localstatedir includedir \
+		oldincludedir docdir infodir htmldir dvidir pdfdir psdir \
+		libdir localedir mandir
 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" ;;
+  eval ac_val=\$$ac_var
+  case $ac_val in
+    [\\/$]* | ?:[\\/]* )  continue;;
+    NONE | '' ) case $ac_var in *prefix ) continue;; esac;;
   esac
+  { echo "$as_me: error: expected an absolute directory name for --$ac_var: $ac_val" >&2
+   { (exit 1); exit 1; }; }
 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
+# There might be people who depend on the old broken behavior: `$host'
+# used to hold the argument of --host etc.
+# FIXME: To remove some day.
+build=$build_alias
+host=$host_alias
+target=$target_alias
 
-# 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
+# FIXME: To remove some day.
+if test "x$host_alias" != x; then
+  if test "x$build_alias" = x; then
+    cross_compiling=maybe
+    echo "$as_me: WARNING: If you wanted to set the --build type, don't use --host.
+    If a cross compiler is detected then cross compile mode will be used." >&2
+  elif test "x$build_alias" != "x$host_alias"; then
+    cross_compiling=yes
+  fi
+fi
 
-# 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=gperf.1
+ac_tool_prefix=
+test -n "$host_alias" && ac_tool_prefix=$host_alias-
+
+test "$silent" = yes && exec 6>/dev/null
+
+
+ac_pwd=`pwd` && test -n "$ac_pwd" &&
+ac_ls_di=`ls -di .` &&
+ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` ||
+  { echo "$as_me: error: Working directory cannot be determined" >&2
+   { (exit 1); exit 1; }; }
+test "X$ac_ls_di" = "X$ac_pwd_ls_di" ||
+  { echo "$as_me: error: pwd does not report name of working directory" >&2
+   { (exit 1); exit 1; }; }
+
 
 # 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=.
+  # Try the directory containing this script, then the parent directory.
+  ac_confdir=`$as_dirname -- "$0" ||
+$as_expr X"$0" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+	 X"$0" : 'X\(//\)[^/]' \| \
+	 X"$0" : 'X\(//\)$' \| \
+	 X"$0" : 'X\(/\)' \| . 2>/dev/null ||
+echo X"$0" |
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)[^/].*/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
   srcdir=$ac_confdir
-  if test ! -r $srcdir/$ac_unique_file; then
+  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
+if test ! -r "$srcdir/$ac_unique_file"; then
+  test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .."
+  { echo "$as_me: error: cannot find sources ($ac_unique_file) in $srcdir" >&2
+   { (exit 1); exit 1; }; }
 fi
-srcdir=`echo "${srcdir}" | sed 's%\([^/]\)/*$%\1%'`
+ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work"
+ac_abs_confdir=`(
+	cd "$srcdir" && test -r "./$ac_unique_file" || { echo "$as_me: error: $ac_msg" >&2
+   { (exit 1); exit 1; }; }
+	pwd)`
+# When building in place, set srcdir=.
+if test "$ac_abs_confdir" = "$ac_pwd"; then
+  srcdir=.
+fi
+# Remove unnecessary trailing slashes from srcdir.
+# Double slashes in file names in object file debugging info
+# mess up M-x gdb in Emacs.
+case $srcdir in
+*/) srcdir=`expr "X$srcdir" : 'X\(.*[^/]\)' \| "X$srcdir" : 'X\(.*\)'`;;
+esac
+for ac_var in $ac_precious_vars; do
+  eval ac_env_${ac_var}_set=\${${ac_var}+set}
+  eval ac_env_${ac_var}_value=\$${ac_var}
+  eval ac_cv_env_${ac_var}_set=\${${ac_var}+set}
+  eval ac_cv_env_${ac_var}_value=\$${ac_var}
+done
 
+#
+# Report the --help message.
+#
+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 this package to adapt to many kinds of systems.
+
+Usage: $0 [OPTION]... [VAR=VALUE]...
+
+To assign environment variables (e.g., CC, CFLAGS...), specify them as
+VAR=VALUE.  See below for descriptions of some of the useful variables.
+
+Defaults for the options are specified in brackets.
+
+Configuration:
+  -h, --help              display this help and exit
+      --help=short        display options specific to this package
+      --help=recursive    display the short help of all the included packages
+  -V, --version           display version information and exit
+  -q, --quiet, --silent   do not print \`checking...' messages
+      --cache-file=FILE   cache test results in FILE [disabled]
+  -C, --config-cache      alias for \`--cache-file=config.cache'
+  -n, --no-create         do not create output files
+      --srcdir=DIR        find the sources in DIR [configure dir or \`..']
+
+Installation directories:
+  --prefix=PREFIX         install architecture-independent files in PREFIX
+			  [$ac_default_prefix]
+  --exec-prefix=EPREFIX   install architecture-dependent files in EPREFIX
+			  [PREFIX]
+
+By default, \`make install' will install all the files in
+\`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc.  You can specify
+an installation prefix other than \`$ac_default_prefix' using \`--prefix',
+for instance \`--prefix=\$HOME'.
+
+For better control, use the options below.
+
+Fine tuning of the installation directories:
+  --bindir=DIR           user executables [EPREFIX/bin]
+  --sbindir=DIR          system admin executables [EPREFIX/sbin]
+  --libexecdir=DIR       program executables [EPREFIX/libexec]
+  --sysconfdir=DIR       read-only single-machine data [PREFIX/etc]
+  --sharedstatedir=DIR   modifiable architecture-independent data [PREFIX/com]
+  --localstatedir=DIR    modifiable single-machine data [PREFIX/var]
+  --libdir=DIR           object code libraries [EPREFIX/lib]
+  --includedir=DIR       C header files [PREFIX/include]
+  --oldincludedir=DIR    C header files for non-gcc [/usr/include]
+  --datarootdir=DIR      read-only arch.-independent data root [PREFIX/share]
+  --datadir=DIR          read-only architecture-independent data [DATAROOTDIR]
+  --infodir=DIR          info documentation [DATAROOTDIR/info]
+  --localedir=DIR        locale-dependent data [DATAROOTDIR/locale]
+  --mandir=DIR           man documentation [DATAROOTDIR/man]
+  --docdir=DIR           documentation root [DATAROOTDIR/doc/PACKAGE]
+  --htmldir=DIR          html documentation [DOCDIR]
+  --dvidir=DIR           dvi documentation [DOCDIR]
+  --pdfdir=DIR           pdf documentation [DOCDIR]
+  --psdir=DIR            ps documentation [DOCDIR]
+_ACEOF
+
+  cat <<\_ACEOF
+_ACEOF
+fi
+
+if test -n "$ac_init_help"; then
+
+  cat <<\_ACEOF
+
+_ACEOF
+ac_status=$?
+fi
+
+if test "$ac_init_help" = "recursive"; then
+  # If there are subdirs, report their specific --help.
+  for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue
+    test -d "$ac_dir" || continue
+    ac_builddir=.
+
+case "$ac_dir" in
+.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;
+*)
+  ac_dir_suffix=/`echo "$ac_dir" | sed 's,^\.[\\/],,'`
+  # A ".." for each directory in $ac_dir_suffix.
+  ac_top_builddir_sub=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,/..,g;s,/,,'`
+  case $ac_top_builddir_sub in
+  "") ac_top_builddir_sub=. ac_top_build_prefix= ;;
+  *)  ac_top_build_prefix=$ac_top_builddir_sub/ ;;
+  esac ;;
+esac
+ac_abs_top_builddir=$ac_pwd
+ac_abs_builddir=$ac_pwd$ac_dir_suffix
+# for backward compatibility:
+ac_top_builddir=$ac_top_build_prefix
+
+case $srcdir in
+  .)  # We are building in place.
+    ac_srcdir=.
+    ac_top_srcdir=$ac_top_builddir_sub
+    ac_abs_top_srcdir=$ac_pwd ;;
+  [\\/]* | ?:[\\/]* )  # Absolute name.
+    ac_srcdir=$srcdir$ac_dir_suffix;
+    ac_top_srcdir=$srcdir
+    ac_abs_top_srcdir=$srcdir ;;
+  *) # Relative name.
+    ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix
+    ac_top_srcdir=$ac_top_build_prefix$srcdir
+    ac_abs_top_srcdir=$ac_pwd/$srcdir ;;
+esac
+ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix
+
+    cd "$ac_dir" || { ac_status=$?; continue; }
+    # Check for guested configure.
+    if test -f "$ac_srcdir/configure.gnu"; then
+      echo &&
+      $SHELL "$ac_srcdir/configure.gnu" --help=recursive
+    elif test -f "$ac_srcdir/configure"; then
+      echo &&
+      $SHELL "$ac_srcdir/configure" --help=recursive
+    else
+      echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2
+    fi || ac_status=$?
+    cd "$ac_pwd" || { ac_status=$?; break; }
+  done
+fi
+
+test -n "$ac_init_help" && exit $ac_status
+if $ac_init_version; then
+  cat <<\_ACEOF
+configure
+generated by GNU Autoconf 2.61
+
+Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001,
+2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc.
+This configure script is free software; the Free Software Foundation
+gives unlimited permission to copy, distribute and modify it.
+_ACEOF
+  exit
+fi
+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 $as_me, which was
+generated by GNU Autoconf 2.61.  Invocation command line was
+
+  $ $0 $@
+
+_ACEOF
+exec 5>>config.log
+{
+cat <<_ASUNAME
+## --------- ##
+## Platform. ##
+## --------- ##
+
+hostname = `(hostname || uname -n) 2>/dev/null | sed 1q`
+uname -m = `(uname -m) 2>/dev/null || echo unknown`
+uname -r = `(uname -r) 2>/dev/null || echo unknown`
+uname -s = `(uname -s) 2>/dev/null || echo unknown`
+uname -v = `(uname -v) 2>/dev/null || echo unknown`
+
+/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown`
+/bin/uname -X     = `(/bin/uname -X) 2>/dev/null     || echo unknown`
+
+/bin/arch              = `(/bin/arch) 2>/dev/null              || echo unknown`
+/usr/bin/arch -k       = `(/usr/bin/arch -k) 2>/dev/null       || echo unknown`
+/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown`
+/usr/bin/hostinfo      = `(/usr/bin/hostinfo) 2>/dev/null      || echo unknown`
+/bin/machine           = `(/bin/machine) 2>/dev/null           || echo unknown`
+/usr/bin/oslevel       = `(/usr/bin/oslevel) 2>/dev/null       || echo unknown`
+/bin/universe          = `(/bin/universe) 2>/dev/null          || echo unknown`
+
+_ASUNAME
+
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+  echo "PATH: $as_dir"
+done
+IFS=$as_save_IFS
+
+} >&5
+
+cat >&5 <<_ACEOF
+
+
+## ----------- ##
+## Core tests. ##
+## ----------- ##
+
+_ACEOF
+
+
+# Keep a trace of the command line.
+# Strip out --no-create and --no-recursion so they do not pile up.
+# Strip out --silent because we don't want to record it for future runs.
+# Also quote any args containing shell meta-characters.
+# Make two passes to allow for proper duplicate-argument suppression.
+ac_configure_args=
+ac_configure_args0=
+ac_configure_args1=
+ac_must_keep_next=false
+for ac_pass in 1 2
+do
+  for ac_arg
+  do
+    case $ac_arg in
+    -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;;
+    -q | -quiet | --quiet | --quie | --qui | --qu | --q \
+    | -silent | --silent | --silen | --sile | --sil)
+      continue ;;
+    *\'*)
+      ac_arg=`echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;;
+    esac
+    case $ac_pass in
+    1) ac_configure_args0="$ac_configure_args0 '$ac_arg'" ;;
+    2)
+      ac_configure_args1="$ac_configure_args1 '$ac_arg'"
+      if test $ac_must_keep_next = true; then
+	ac_must_keep_next=false # Got value, back to normal.
+      else
+	case $ac_arg in
+	  *=* | --config-cache | -C | -disable-* | --disable-* \
+	  | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \
+	  | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \
+	  | -with-* | --with-* | -without-* | --without-* | --x)
+	    case "$ac_configure_args0 " in
+	      "$ac_configure_args1"*" '$ac_arg' "* ) continue ;;
+	    esac
+	    ;;
+	  -* ) ac_must_keep_next=true ;;
+	esac
+      fi
+      ac_configure_args="$ac_configure_args '$ac_arg'"
+      ;;
+    esac
+  done
+done
+$as_unset ac_configure_args0 || test "${ac_configure_args0+set}" != set || { ac_configure_args0=; export ac_configure_args0; }
+$as_unset ac_configure_args1 || test "${ac_configure_args1+set}" != set || { ac_configure_args1=; export ac_configure_args1; }
+
+# When interrupted or exit'd, cleanup temporary files, and complete
+# config.log.  We remove comments because anyway the quotes in there
+# would cause problems or look ugly.
+# WARNING: Use '\'' to represent an apostrophe within the trap.
+# WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug.
+trap 'exit_status=$?
+  # Save into config.log some information that might help in debugging.
+  {
+    echo
+
+    cat <<\_ASBOX
+## ---------------- ##
+## Cache variables. ##
+## ---------------- ##
+_ASBOX
+    echo
+    # The following way of writing the cache mishandles newlines in values,
+(
+  for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do
+    eval ac_val=\$$ac_var
+    case $ac_val in #(
+    *${as_nl}*)
+      case $ac_var in #(
+      *_cv_*) { echo "$as_me:$LINENO: WARNING: Cache variable $ac_var contains a newline." >&5
+echo "$as_me: WARNING: Cache variable $ac_var contains a newline." >&2;} ;;
+      esac
+      case $ac_var in #(
+      _ | IFS | as_nl) ;; #(
+      *) $as_unset $ac_var ;;
+      esac ;;
+    esac
+  done
+  (set) 2>&1 |
+    case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #(
+    *${as_nl}ac_space=\ *)
+      sed -n \
+	"s/'\''/'\''\\\\'\'''\''/g;
+	  s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p"
+      ;; #(
+    *)
+      sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p"
+      ;;
+    esac |
+    sort
+)
+    echo
+
+    cat <<\_ASBOX
+## ----------------- ##
+## Output variables. ##
+## ----------------- ##
+_ASBOX
+    echo
+    for ac_var in $ac_subst_vars
+    do
+      eval ac_val=\$$ac_var
+      case $ac_val in
+      *\'\''*) ac_val=`echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;;
+      esac
+      echo "$ac_var='\''$ac_val'\''"
+    done | sort
+    echo
+
+    if test -n "$ac_subst_files"; then
+      cat <<\_ASBOX
+## ------------------- ##
+## File substitutions. ##
+## ------------------- ##
+_ASBOX
+      echo
+      for ac_var in $ac_subst_files
+      do
+	eval ac_val=\$$ac_var
+	case $ac_val in
+	*\'\''*) ac_val=`echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;;
+	esac
+	echo "$ac_var='\''$ac_val'\''"
+      done | sort
+      echo
+    fi
+
+    if test -s confdefs.h; then
+      cat <<\_ASBOX
+## ----------- ##
+## confdefs.h. ##
+## ----------- ##
+_ASBOX
+      echo
+      cat confdefs.h
+      echo
+    fi
+    test "$ac_signal" != 0 &&
+      echo "$as_me: caught signal $ac_signal"
+    echo "$as_me: exit $exit_status"
+  } >&5
+  rm -f core *.core core.conftest.* &&
+    rm -f -r conftest* confdefs* conf$$* $ac_clean_files &&
+    exit $exit_status
+' 0
+for ac_signal in 1 2 13 15; do
+  trap 'ac_signal='$ac_signal'; { (exit 1); exit 1; }' $ac_signal
+done
+ac_signal=0
+
+# confdefs.h avoids OS command line length limits that DEFS can exceed.
+rm -f -r conftest* confdefs.h
+
+# Predefined preprocessor variables.
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_NAME "$PACKAGE_NAME"
+_ACEOF
+
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_TARNAME "$PACKAGE_TARNAME"
+_ACEOF
+
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_VERSION "$PACKAGE_VERSION"
+_ACEOF
+
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_STRING "$PACKAGE_STRING"
+_ACEOF
+
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT"
+_ACEOF
+
+
+# Let the site file select an alternate cache file if it wants to.
 # 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
+if test -n "$CONFIG_SITE"; then
+  set x "$CONFIG_SITE"
+elif test "x$prefix" != xNONE; then
+  set x "$prefix/share/config.site" "$prefix/etc/config.site"
+else
+  set x "$ac_default_prefix/share/config.site" \
+	"$ac_default_prefix/etc/config.site"
 fi
-for ac_site_file in $CONFIG_SITE; do
+shift
+for ac_site_file
+do
   if test -r "$ac_site_file"; then
-    echo "loading site script $ac_site_file"
+    { echo "$as_me:$LINENO: loading site script $ac_site_file" >&5
+echo "$as_me: loading site script $ac_site_file" >&6;}
+    sed 's/^/| /' "$ac_site_file" >&5
     . "$ac_site_file"
   fi
 done
 
 if test -r "$cache_file"; then
-  echo "loading cache $cache_file"
-  . $cache_file
+  # Some versions of bash will fail to source /dev/null (special
+  # files actually), so we avoid doing that.
+  if test -f "$cache_file"; then
+    { echo "$as_me:$LINENO: loading cache $cache_file" >&5
+echo "$as_me: loading cache $cache_file" >&6;}
+    case $cache_file in
+      [\\/]* | ?:[\\/]* ) . "$cache_file";;
+      *)                      . "./$cache_file";;
+    esac
+  fi
 else
-  echo "creating cache $cache_file"
-  > $cache_file
+  { echo "$as_me:$LINENO: creating cache $cache_file" >&5
+echo "$as_me: creating cache $cache_file" >&6;}
+  >$cache_file
 fi
 
+# Check that the precious variables saved in the cache have kept the same
+# value.
+ac_cache_corrupted=false
+for ac_var in $ac_precious_vars; do
+  eval ac_old_set=\$ac_cv_env_${ac_var}_set
+  eval ac_new_set=\$ac_env_${ac_var}_set
+  eval ac_old_val=\$ac_cv_env_${ac_var}_value
+  eval ac_new_val=\$ac_env_${ac_var}_value
+  case $ac_old_set,$ac_new_set in
+    set,)
+      { echo "$as_me:$LINENO: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5
+echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;}
+      ac_cache_corrupted=: ;;
+    ,set)
+      { echo "$as_me:$LINENO: error: \`$ac_var' was not set in the previous run" >&5
+echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;}
+      ac_cache_corrupted=: ;;
+    ,);;
+    *)
+      if test "x$ac_old_val" != "x$ac_new_val"; then
+	{ echo "$as_me:$LINENO: error: \`$ac_var' has changed since the previous run:" >&5
+echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;}
+	{ echo "$as_me:$LINENO:   former value:  $ac_old_val" >&5
+echo "$as_me:   former value:  $ac_old_val" >&2;}
+	{ echo "$as_me:$LINENO:   current value: $ac_new_val" >&5
+echo "$as_me:   current value: $ac_new_val" >&2;}
+	ac_cache_corrupted=:
+      fi;;
+  esac
+  # Pass precious variables to config.status.
+  if test "$ac_new_set" = set; then
+    case $ac_new_val in
+    *\'*) ac_arg=$ac_var=`echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;;
+    *) ac_arg=$ac_var=$ac_new_val ;;
+    esac
+    case " $ac_configure_args " in
+      *" '$ac_arg' "*) ;; # Avoid dups.  Use of quotes ensures accuracy.
+      *) ac_configure_args="$ac_configure_args '$ac_arg'" ;;
+    esac
+  fi
+done
+if $ac_cache_corrupted; then
+  { echo "$as_me:$LINENO: error: changes in the environment can compromise the build" >&5
+echo "$as_me: error: changes in the environment can compromise the build" >&2;}
+  { { echo "$as_me:$LINENO: error: run \`make distclean' and/or \`rm $cache_file' and start over" >&5
+echo "$as_me: error: run \`make distclean' and/or \`rm $cache_file' and start over" >&2;}
+   { (exit 1); exit 1; }; }
+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 at 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
+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
 
 
 PACKAGE=gperf
 
-echo $ac_n "checking whether ${MAKE-make} sets \${MAKE}""... $ac_c" 1>&6
-echo "configure:528: 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
+{ echo "$as_me:$LINENO: checking whether ${MAKE-make} sets \$(MAKE)" >&5
+echo $ECHO_N "checking whether ${MAKE-make} sets \$(MAKE)... $ECHO_C" >&6; }
+set x ${MAKE-make}; ac_make=`echo "$2" | sed 's/+/p/g; s/[^a-zA-Z0-9_]/_/g'`
+if { as_var=ac_cv_prog_make_${ac_make}_set; eval "test \"\${$as_var+set}\" = set"; }; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
 else
-  cat > conftestmake <<\EOF
+  cat >conftest.make <<\_ACEOF
+SHELL = /bin/sh
 all:
-	@echo 'ac_maketemp="${MAKE}"'
-EOF
+	@echo '@@@%%%=$(MAKE)=@@@%%%'
+_ACEOF
 # 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
+case `${MAKE-make} -f conftest.make 2>/dev/null` in
+  *@@@%%%=?*=@@@%%%*)
+    eval ac_cv_prog_make_${ac_make}_set=yes;;
+  *)
+    eval ac_cv_prog_make_${ac_make}_set=no;;
+esac
+rm -f conftest.make
 fi
-rm -f conftestmake
-fi
-if eval "test \"`echo '$ac_cv_prog_make_'${ac_make}_set`\" = yes"; then
-  echo "$ac_t""yes" 1>&6
+if eval test \$ac_cv_prog_make_${ac_make}_set = yes; then
+  { echo "$as_me:$LINENO: result: yes" >&5
+echo "${ECHO_T}yes" >&6; }
   SET_MAKE=
 else
-  echo "$ac_t""no" 1>&6
+  { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
   SET_MAKE="MAKE=${MAKE-make}"
 fi
 
@@ -560,11 +1651,11 @@
 # 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:565: checking for a BSD compatible install" >&5
+{ echo "$as_me:$LINENO: checking for a BSD compatible install" >&5
+echo $ECHO_N "checking for a BSD compatible install... $ECHO_C" >&6; }
 if test -z "$INSTALL"; then
-if eval "test \"`echo '$''{'cl_cv_path_install'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
+if test "${cl_cv_path_install+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
 else
     IFS="${IFS= 	}"; ac_save_ifs="$IFS"; IFS="${IFS}:"
   for ac_dir in $PATH; do
@@ -602,7 +1693,8 @@
 fi
   INSTALL="$cl_cv_path_install"
 fi
-echo "$ac_t""$INSTALL" 1>&6
+{ echo "$as_me:$LINENO: result: $INSTALL" >&5
+echo "${ECHO_T}$INSTALL" >&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)'
@@ -613,259 +1705,1006 @@
   esac
 fi
 
-                      trap '' 1 2 15
-cat > confcache <<\EOF
+                      ac_config_files="$ac_config_files Makefile"
+
+cat >confcache <<\_ACEOF
 # 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.
+# scripts and configure runs, see configure's option --config-cache.
+# 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.
+# config.status only pays attention to the cache file if you give it
+# the --recheck option to rerun configure.
 #
-EOF
+# `ac_cv_env_foo' variables (set or unset) will be overridden when
+# loading this file, other *unset* `ac_cv_foo' will be assigned the
+# following values.
+
+_ACEOF
+
 # 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.
+# So, we kill variables containing newlines.
 # 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
+(
+  for ac_var in `(set) 2>&1 | sed -n 's/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'`; do
+    eval ac_val=\$$ac_var
+    case $ac_val in #(
+    *${as_nl}*)
+      case $ac_var in #(
+      *_cv_*) { echo "$as_me:$LINENO: WARNING: Cache variable $ac_var contains a newline." >&5
+echo "$as_me: WARNING: Cache variable $ac_var contains a newline." >&2;} ;;
+      esac
+      case $ac_var in #(
+      _ | IFS | as_nl) ;; #(
+      *) $as_unset $ac_var ;;
+      esac ;;
+    esac
+  done
+
+  (set) 2>&1 |
+    case $as_nl`(ac_space=' '; set) 2>&1` in #(
+    *${as_nl}ac_space=\ *)
+      # `set' does not quote correctly, so add quotes (double-quote
+      # substitution turns \\\\ into \\, and sed turns \\ into \).
+      sed -n \
+	"s/'/'\\\\''/g;
+	  s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p"
+      ;; #(
+    *)
+      # `set' quotes correctly as required by POSIX, so do not add quotes.
+      sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p"
+      ;;
+    esac |
+    sort
+) |
+  sed '
+     /^ac_cv_env_/b end
+     t clear
+     :clear
+     s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/
+     t end
+     s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/
+     :end' >>confcache
+if diff "$cache_file" confcache >/dev/null 2>&1; then :; else
+  if test -w "$cache_file"; then
+    test "x$cache_file" != "x/dev/null" &&
+      { echo "$as_me:$LINENO: updating cache $cache_file" >&5
+echo "$as_me: updating cache $cache_file" >&6;}
+    cat confcache >$cache_file
   else
-    echo "not updating unwritable cache $cache_file"
+    { echo "$as_me:$LINENO: not updating unwritable cache $cache_file" >&5
+echo "$as_me: not updating unwritable cache $cache_file" >&6;}
   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
+#
+# If the first sed substitution is executed (which looks for macros that
+# take arguments), then branch to the quote section.  Otherwise,
+# look for a macro that doesn't take arguments.
+ac_script='
+t clear
+:clear
+s/^[	 ]*#[	 ]*define[	 ][	 ]*\([^	 (][^	 (]*([^)]*)\)[	 ]*\(.*\)/-D\1=\2/g
+t quote
+s/^[	 ]*#[	 ]*define[	 ][	 ]*\([^	 ][^	 ]*\)[	 ]*\(.*\)/-D\1=\2/g
+t quote
+b any
+:quote
+s/[	 `~#$^&*(){}\\|;'\''"<>?]/\\&/g
+s/\[/\\&/g
+s/\]/\\&/g
+s/\$/$$/g
+H
+:any
+${
+	g
+	s/^\n//
+	s/\n/ /g
+	p
+}
+'
+DEFS=`sed -n "$ac_script" confdefs.h`
 
 
-# Without the "./", some shells look in PATH for config.status.
+ac_libobjs=
+ac_ltlibobjs=
+for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue
+  # 1. Remove the extension, and $U if already installed.
+  ac_script='s/\$U\././;s/\.o$//;s/\.obj$//'
+  ac_i=`echo "$ac_i" | sed "$ac_script"`
+  # 2. Prepend LIBOBJDIR.  When used with automake>=1.10 LIBOBJDIR
+  #    will be set to the directory where LIBOBJS objects are built.
+  ac_libobjs="$ac_libobjs \${LIBOBJDIR}$ac_i\$U.$ac_objext"
+  ac_ltlibobjs="$ac_ltlibobjs \${LIBOBJDIR}$ac_i"'$U.lo'
+done
+LIBOBJS=$ac_libobjs
+
+LTLIBOBJS=$ac_ltlibobjs
+
+
+
 : ${CONFIG_STATUS=./config.status}
+ac_clean_files_save=$ac_clean_files
+ac_clean_files="$ac_clean_files $CONFIG_STATUS"
+{ echo "$as_me:$LINENO: creating $CONFIG_STATUS" >&5
+echo "$as_me: creating $CONFIG_STATUS" >&6;}
+cat >$CONFIG_STATUS <<_ACEOF
+#! $SHELL
+# Generated by $as_me.
+# Run this file to recreate the current configuration.
+# Compiler output produced by configure, useful for debugging
+# configure, is in config.log if it exists.
 
-echo creating $CONFIG_STATUS
-rm -f $CONFIG_STATUS
-cat > $CONFIG_STATUS <<EOF
-#! /bin/sh
-# Generated automatically by configure.
-# Run this file to recreate the current configuration.
-# This directory was configured as follows,
-# on host `(hostname || uname -n) 2>/dev/null | sed 1q`:
-#
-# $0 $ac_configure_args
-#
-# Compiler output produced by configure, useful for debugging
-# configure, is in ./config.log if it exists.
+debug=false
+ac_cs_recheck=false
+ac_cs_silent=false
+SHELL=\${CONFIG_SHELL-$SHELL}
+_ACEOF
 
-ac_cs_usage="Usage: $CONFIG_STATUS [--recheck] [--version] [--help]"
-for ac_option
+cat >>$CONFIG_STATUS <<\_ACEOF
+## --------------------- ##
+## M4sh Initialization.  ##
+## --------------------- ##
+
+# Be more Bourne compatible
+DUALCASE=1; export DUALCASE # for MKS sh
+if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
+  emulate sh
+  NULLCMD=:
+  # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
+  # is contrary to our usage.  Disable this feature.
+  alias -g '${1+"$@"}'='"$@"'
+  setopt NO_GLOB_SUBST
+else
+  case `(set -o) 2>/dev/null` in
+  *posix*) set -o posix ;;
+esac
+
+fi
+
+
+
+
+# PATH needs CR
+# Avoid depending upon Character Ranges.
+as_cr_letters='abcdefghijklmnopqrstuvwxyz'
+as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
+as_cr_Letters=$as_cr_letters$as_cr_LETTERS
+as_cr_digits='0123456789'
+as_cr_alnum=$as_cr_Letters$as_cr_digits
+
+# The user is always right.
+if test "${PATH_SEPARATOR+set}" != set; then
+  echo "#! /bin/sh" >conf$$.sh
+  echo  "exit 0"   >>conf$$.sh
+  chmod +x conf$$.sh
+  if (PATH="/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then
+    PATH_SEPARATOR=';'
+  else
+    PATH_SEPARATOR=:
+  fi
+  rm -f conf$$.sh
+fi
+
+# Support unset when possible.
+if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then
+  as_unset=unset
+else
+  as_unset=false
+fi
+
+
+# IFS
+# We need space, tab and new line, in precisely that order.  Quoting is
+# there to prevent editors from complaining about space-tab.
+# (If _AS_PATH_WALK were called with IFS unset, it would disable word
+# splitting by setting IFS to empty value.)
+as_nl='
+'
+IFS=" ""	$as_nl"
+
+# Find who we are.  Look in the path if we contain no directory separator.
+case $0 in
+  *[\\/]* ) as_myself=$0 ;;
+  *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
 do
-  case "\$ac_option" in
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+  test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break
+done
+IFS=$as_save_IFS
+
+     ;;
+esac
+# We did not find ourselves, most probably we were run as `sh COMMAND'
+# in which case we are not to be found in the path.
+if test "x$as_myself" = x; then
+  as_myself=$0
+fi
+if test ! -f "$as_myself"; then
+  echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2
+  { (exit 1); exit 1; }
+fi
+
+# Work around bugs in pre-3.0 UWIN ksh.
+for as_var in ENV MAIL MAILPATH
+do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var
+done
+PS1='$ '
+PS2='> '
+PS4='+ '
+
+# NLS nuisances.
+for as_var in \
+  LANG LANGUAGE LC_ADDRESS LC_ALL LC_COLLATE LC_CTYPE LC_IDENTIFICATION \
+  LC_MEASUREMENT LC_MESSAGES LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER \
+  LC_TELEPHONE LC_TIME
+do
+  if (set +x; test -z "`(eval $as_var=C; export $as_var) 2>&1`"); then
+    eval $as_var=C; export $as_var
+  else
+    ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var
+  fi
+done
+
+# Required to use basename.
+if expr a : '\(a\)' >/dev/null 2>&1 &&
+   test "X`expr 00001 : '.*\(...\)'`" = X001; then
+  as_expr=expr
+else
+  as_expr=false
+fi
+
+if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then
+  as_basename=basename
+else
+  as_basename=false
+fi
+
+
+# Name of the executable.
+as_me=`$as_basename -- "$0" ||
+$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
+	 X"$0" : 'X\(//\)$' \| \
+	 X"$0" : 'X\(/\)' \| . 2>/dev/null ||
+echo X/"$0" |
+    sed '/^.*\/\([^/][^/]*\)\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\/\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\/\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+
+# CDPATH.
+$as_unset CDPATH
+
+
+
+  as_lineno_1=$LINENO
+  as_lineno_2=$LINENO
+  test "x$as_lineno_1" != "x$as_lineno_2" &&
+  test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2" || {
+
+  # Create $as_me.lineno as a copy of $as_myself, but with $LINENO
+  # uniformly replaced by the line number.  The first 'sed' inserts a
+  # line-number line after each line using $LINENO; the second 'sed'
+  # does the real work.  The second script uses 'N' to pair each
+  # line-number line with the line containing $LINENO, and appends
+  # trailing '-' during substitution so that $LINENO is not a special
+  # case at line end.
+  # (Raja R Harinath suggested sed '=', and Paul Eggert wrote the
+  # scripts with optimization help from Paolo Bonzini.  Blame Lee
+  # E. McMahon (1931-1989) for sed's syntax.  :-)
+  sed -n '
+    p
+    /[$]LINENO/=
+  ' <$as_myself |
+    sed '
+      s/[$]LINENO.*/&-/
+      t lineno
+      b
+      :lineno
+      N
+      :loop
+      s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/
+      t loop
+      s/-\n.*//
+    ' >$as_me.lineno &&
+  chmod +x "$as_me.lineno" ||
+    { echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2
+   { (exit 1); exit 1; }; }
+
+  # Don't try to exec as it changes $[0], causing all sort of problems
+  # (the dirname of $[0] is not the place where we might find the
+  # original and so on.  Autoconf is especially sensitive to this).
+  . "./$as_me.lineno"
+  # Exit status is that of the last command.
+  exit
+}
+
+
+if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then
+  as_dirname=dirname
+else
+  as_dirname=false
+fi
+
+ECHO_C= ECHO_N= ECHO_T=
+case `echo -n x` in
+-n*)
+  case `echo 'x\c'` in
+  *c*) ECHO_T='	';;	# ECHO_T is single tab character.
+  *)   ECHO_C='\c';;
+  esac;;
+*)
+  ECHO_N='-n';;
+esac
+
+if expr a : '\(a\)' >/dev/null 2>&1 &&
+   test "X`expr 00001 : '.*\(...\)'`" = X001; then
+  as_expr=expr
+else
+  as_expr=false
+fi
+
+rm -f conf$$ conf$$.exe conf$$.file
+if test -d conf$$.dir; then
+  rm -f conf$$.dir/conf$$.file
+else
+  rm -f conf$$.dir
+  mkdir conf$$.dir
+fi
+echo >conf$$.file
+if ln -s conf$$.file conf$$ 2>/dev/null; then
+  as_ln_s='ln -s'
+  # ... but there are two gotchas:
+  # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail.
+  # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable.
+  # In both cases, we have to default to `cp -p'.
+  ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe ||
+    as_ln_s='cp -p'
+elif ln conf$$.file conf$$ 2>/dev/null; then
+  as_ln_s=ln
+else
+  as_ln_s='cp -p'
+fi
+rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file
+rmdir conf$$.dir 2>/dev/null
+
+if mkdir -p . 2>/dev/null; then
+  as_mkdir_p=:
+else
+  test -d ./-p && rmdir ./-p
+  as_mkdir_p=false
+fi
+
+if test -x / >/dev/null 2>&1; then
+  as_test_x='test -x'
+else
+  if ls -dL / >/dev/null 2>&1; then
+    as_ls_L_option=L
+  else
+    as_ls_L_option=
+  fi
+  as_test_x='
+    eval sh -c '\''
+      if test -d "$1"; then
+        test -d "$1/.";
+      else
+	case $1 in
+        -*)set "./$1";;
+	esac;
+	case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in
+	???[sx]*):;;*)false;;esac;fi
+    '\'' sh
+  '
+fi
+as_executable_p=$as_test_x
+
+# Sed expression to map a string onto a valid CPP name.
+as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
+
+# Sed expression to map a string onto a valid variable name.
+as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'"
+
+
+exec 6>&1
+
+# Save the log message, to keep $[0] and so on meaningful, and to
+# report actual input values of CONFIG_FILES etc. instead of their
+# values after options handling.
+ac_log="
+This file was extended by $as_me, which was
+generated by GNU Autoconf 2.61.  Invocation command line was
+
+  CONFIG_FILES    = $CONFIG_FILES
+  CONFIG_HEADERS  = $CONFIG_HEADERS
+  CONFIG_LINKS    = $CONFIG_LINKS
+  CONFIG_COMMANDS = $CONFIG_COMMANDS
+  $ $0 $@
+
+on `(hostname || uname -n) 2>/dev/null | sed 1q`
+"
+
+_ACEOF
+
+cat >>$CONFIG_STATUS <<_ACEOF
+# Files that config.status was made for.
+config_files="$ac_config_files"
+
+_ACEOF
+
+cat >>$CONFIG_STATUS <<\_ACEOF
+ac_cs_usage="\
+\`$as_me' instantiates files from templates according to the
+current configuration.
+
+Usage: $0 [OPTIONS] [FILE]...
+
+  -h, --help       print this help, then exit
+  -V, --version    print version number and configuration settings, then exit
+  -q, --quiet      do not print progress messages
+  -d, --debug      don't remove temporary files
+      --recheck    update $as_me by reconfiguring in the same conditions
+  --file=FILE[:TEMPLATE]
+		   instantiate the configuration file FILE
+
+Configuration files:
+$config_files
+
+Report bugs to <bug-autoconf at gnu.org>."
+
+_ACEOF
+cat >>$CONFIG_STATUS <<_ACEOF
+ac_cs_version="\\
+config.status
+configured by $0, generated by GNU Autoconf 2.61,
+  with options \\"`echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`\\"
+
+Copyright (C) 2006 Free Software Foundation, Inc.
+This config.status script is free software; the Free Software Foundation
+gives unlimited permission to copy, distribute and modify it."
+
+ac_pwd='$ac_pwd'
+srcdir='$srcdir'
+_ACEOF
+
+cat >>$CONFIG_STATUS <<\_ACEOF
+# If no file are specified by the user, then we need to provide default
+# value.  By we need to know if files were specified by the user.
+ac_need_defaults=:
+while test $# != 0
+do
+  case $1 in
+  --*=*)
+    ac_option=`expr "X$1" : 'X\([^=]*\)='`
+    ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'`
+    ac_shift=:
+    ;;
+  *)
+    ac_option=$1
+    ac_optarg=$2
+    ac_shift=shift
+    ;;
+  esac
+
+  case $ac_option in
+  # Handling of the options.
   -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 ;;
+    ac_cs_recheck=: ;;
+  --version | --versio | --versi | --vers | --ver | --ve | --v | -V )
+    echo "$ac_cs_version"; exit ;;
+  --debug | --debu | --deb | --de | --d | -d )
+    debug=: ;;
+  --file | --fil | --fi | --f )
+    $ac_shift
+    CONFIG_FILES="$CONFIG_FILES $ac_optarg"
+    ac_need_defaults=false;;
+  --he | --h |  --help | --hel | -h )
+    echo "$ac_cs_usage"; exit ;;
+  -q | -quiet | --quiet | --quie | --qui | --qu | --q \
+  | -silent | --silent | --silen | --sile | --sil | --si | --s)
+    ac_cs_silent=: ;;
+
+  # This is an error.
+  -*) { echo "$as_me: error: unrecognized option: $1
+Try \`$0 --help' for more information." >&2
+   { (exit 1); exit 1; }; } ;;
+
+  *) ac_config_targets="$ac_config_targets $1"
+     ac_need_defaults=false ;;
+
+  esac
+  shift
+done
+
+ac_configure_extra_args=
+
+if $ac_cs_silent; then
+  exec 6>/dev/null
+  ac_configure_extra_args="$ac_configure_extra_args --silent"
+fi
+
+_ACEOF
+cat >>$CONFIG_STATUS <<_ACEOF
+if \$ac_cs_recheck; then
+  echo "running CONFIG_SHELL=$SHELL $SHELL $0 "$ac_configure_args \$ac_configure_extra_args " --no-create --no-recursion" >&6
+  CONFIG_SHELL=$SHELL
+  export CONFIG_SHELL
+  exec $SHELL "$0"$ac_configure_args \$ac_configure_extra_args --no-create --no-recursion
+fi
+
+_ACEOF
+cat >>$CONFIG_STATUS <<\_ACEOF
+exec 5>>config.log
+{
+  echo
+  sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX
+## Running $as_me. ##
+_ASBOX
+  echo "$ac_log"
+} >&5
+
+_ACEOF
+cat >>$CONFIG_STATUS <<_ACEOF
+_ACEOF
+
+cat >>$CONFIG_STATUS <<\_ACEOF
+
+# Handling of arguments.
+for ac_config_target in $ac_config_targets
+do
+  case $ac_config_target in
+    "Makefile") CONFIG_FILES="$CONFIG_FILES Makefile" ;;
+
+  *) { { echo "$as_me:$LINENO: error: invalid argument: $ac_config_target" >&5
+echo "$as_me: error: invalid argument: $ac_config_target" >&2;}
+   { (exit 1); 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 <<EOF
+# If the user did not use the arguments to specify the items to instantiate,
+# then the envvar interface is used.  Set only those that are not.
+# We use the long form for the default assignment because of an extremely
+# bizarre bug on SunOS 4.1.3.
+if $ac_need_defaults; then
+  test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files
+fi
 
-# Protect against being on the right side of a sed subst in config.status.
-sed 's/%@/@@/; s/@%/@@/; s/%g\$/@g/; /@g\$/s/[\\\\&%]/\\\\&/g;
- s/@@/%@/; s/@@/@%/; s/@g\$/%g/' > 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%@PACKAGE@%$PACKAGE%g
-s%@SET_MAKE@%$SET_MAKE%g
-s%@INSTALL@%$INSTALL%g
-s%@INSTALL_PROGRAM@%$INSTALL_PROGRAM%g
-s%@INSTALL_DATA@%$INSTALL_DATA%g
+# Have a temporary directory for convenience.  Make it in the build tree
+# simply because there is no reason against having it here, and in addition,
+# creating and moving files from /tmp can sometimes cause problems.
+# Hook for its removal unless debugging.
+# Note that there is a small window in which the directory will not be cleaned:
+# after its creation but before its name has been assigned to `$tmp'.
+$debug ||
+{
+  tmp=
+  trap 'exit_status=$?
+  { test -z "$tmp" || test ! -d "$tmp" || rm -fr "$tmp"; } && exit $exit_status
+' 0
+  trap '{ (exit 1); exit 1; }' 1 2 13 15
+}
+# Create a (secure) tmp directory for tmp files.
 
-CEOF
-EOF
+{
+  tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` &&
+  test -n "$tmp" && test -d "$tmp"
+}  ||
+{
+  tmp=./conf$$-$RANDOM
+  (umask 077 && mkdir "$tmp")
+} ||
+{
+   echo "$me: cannot create a temporary directory in ." >&2
+   { (exit 1); exit 1; }
+}
 
-cat >> $CONFIG_STATUS <<\EOF
+#
+# Set up the sed scripts for CONFIG_FILES section.
+#
 
-# 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
+# No need to generate the scripts if there are no CONFIG_FILES.
+# This happens for instance when ./config.status config.h
+if test -n "$CONFIG_FILES"; then
+
+_ACEOF
+
+
+
+ac_delim='%!_!# '
+for ac_last_try in false false false false false :; do
+  cat >conf$$subs.sed <<_ACEOF
+SHELL!$SHELL$ac_delim
+PATH_SEPARATOR!$PATH_SEPARATOR$ac_delim
+PACKAGE_NAME!$PACKAGE_NAME$ac_delim
+PACKAGE_TARNAME!$PACKAGE_TARNAME$ac_delim
+PACKAGE_VERSION!$PACKAGE_VERSION$ac_delim
+PACKAGE_STRING!$PACKAGE_STRING$ac_delim
+PACKAGE_BUGREPORT!$PACKAGE_BUGREPORT$ac_delim
+exec_prefix!$exec_prefix$ac_delim
+prefix!$prefix$ac_delim
+program_transform_name!$program_transform_name$ac_delim
+bindir!$bindir$ac_delim
+sbindir!$sbindir$ac_delim
+libexecdir!$libexecdir$ac_delim
+datarootdir!$datarootdir$ac_delim
+datadir!$datadir$ac_delim
+sysconfdir!$sysconfdir$ac_delim
+sharedstatedir!$sharedstatedir$ac_delim
+localstatedir!$localstatedir$ac_delim
+includedir!$includedir$ac_delim
+oldincludedir!$oldincludedir$ac_delim
+docdir!$docdir$ac_delim
+infodir!$infodir$ac_delim
+htmldir!$htmldir$ac_delim
+dvidir!$dvidir$ac_delim
+pdfdir!$pdfdir$ac_delim
+psdir!$psdir$ac_delim
+libdir!$libdir$ac_delim
+localedir!$localedir$ac_delim
+mandir!$mandir$ac_delim
+DEFS!$DEFS$ac_delim
+ECHO_C!$ECHO_C$ac_delim
+ECHO_N!$ECHO_N$ac_delim
+ECHO_T!$ECHO_T$ac_delim
+LIBS!$LIBS$ac_delim
+build_alias!$build_alias$ac_delim
+host_alias!$host_alias$ac_delim
+target_alias!$target_alias$ac_delim
+PACKAGE!$PACKAGE$ac_delim
+SET_MAKE!$SET_MAKE$ac_delim
+INSTALL!$INSTALL$ac_delim
+INSTALL_PROGRAM!$INSTALL_PROGRAM$ac_delim
+INSTALL_DATA!$INSTALL_DATA$ac_delim
+LIBOBJS!$LIBOBJS$ac_delim
+LTLIBOBJS!$LTLIBOBJS$ac_delim
+_ACEOF
+
+  if test `sed -n "s/.*$ac_delim\$/X/p" conf$$subs.sed | grep -c X` = 44; then
+    break
+  elif $ac_last_try; then
+    { { echo "$as_me:$LINENO: error: could not make $CONFIG_STATUS" >&5
+echo "$as_me: error: could not make $CONFIG_STATUS" >&2;}
+   { (exit 1); exit 1; }; }
   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`
+    ac_delim="$ac_delim!$ac_delim _$ac_delim!! "
   fi
 done
-if test -z "$ac_sed_cmds"; then
-  ac_sed_cmds=cat
+
+ac_eof=`sed -n '/^CEOF[0-9]*$/s/CEOF/0/p' conf$$subs.sed`
+if test -n "$ac_eof"; then
+  ac_eof=`echo "$ac_eof" | sort -nru | sed 1q`
+  ac_eof=`expr $ac_eof + 1`
 fi
-EOF
 
-cat >> $CONFIG_STATUS <<EOF
+cat >>$CONFIG_STATUS <<_ACEOF
+cat >"\$tmp/subs-1.sed" <<\CEOF$ac_eof
+/@[a-zA-Z_][a-zA-Z_0-9]*@/!b end
+_ACEOF
+sed '
+s/[,\\&]/\\&/g; s/@/@|#_!!_#|/g
+s/^/s,@/; s/!/@,|#_!!_#|/
+:n
+t n
+s/'"$ac_delim"'$/,g/; t
+s/$/\\/; p
+N; s/^.*\n//; s/[,\\&]/\\&/g; s/@/@|#_!!_#|/g; b n
+' >>$CONFIG_STATUS <conf$$subs.sed
+rm -f conf$$subs.sed
+cat >>$CONFIG_STATUS <<_ACEOF
+:end
+s/|#_!!_#|//g
+CEOF$ac_eof
+_ACEOF
 
-CONFIG_FILES=\${CONFIG_FILES-"Makefile"}
-EOF
-cat >> $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" ;;
+
+# VPATH may cause trouble with some makes, so we remove $(srcdir),
+# ${srcdir} and @srcdir@ from VPATH if srcdir is ".", strip leading and
+# trailing colons and then remove the whole line if VPATH becomes empty
+# (actually we leave an empty line to preserve line numbers).
+if test "x$srcdir" = x.; then
+  ac_vpsub='/^[	 ]*VPATH[	 ]*=/{
+s/:*\$(srcdir):*/:/
+s/:*\${srcdir}:*/:/
+s/:*@srcdir@:*/:/
+s/^\([^=]*=[	 ]*\):*/\1/
+s/:*$//
+s/^[^=]*=[	 ]*$//
+}'
+fi
+
+cat >>$CONFIG_STATUS <<\_ACEOF
+fi # test -n "$CONFIG_FILES"
+
+
+for ac_tag in  :F $CONFIG_FILES
+do
+  case $ac_tag in
+  :[FHLC]) ac_mode=$ac_tag; continue;;
+  esac
+  case $ac_mode$ac_tag in
+  :[FHL]*:*);;
+  :L* | :C*:*) { { echo "$as_me:$LINENO: error: Invalid tag $ac_tag." >&5
+echo "$as_me: error: Invalid tag $ac_tag." >&2;}
+   { (exit 1); exit 1; }; };;
+  :[FH]-) ac_tag=-:-;;
+  :[FH]*) ac_tag=$ac_tag:$ac_tag.in;;
+  esac
+  ac_save_IFS=$IFS
+  IFS=:
+  set x $ac_tag
+  IFS=$ac_save_IFS
+  shift
+  ac_file=$1
+  shift
+
+  case $ac_mode in
+  :L) ac_source=$1;;
+  :[FH])
+    ac_file_inputs=
+    for ac_f
+    do
+      case $ac_f in
+      -) ac_f="$tmp/stdin";;
+      *) # Look for the file first in the build tree, then in the source tree
+	 # (if the path is not absolute).  The absolute path cannot be DOS-style,
+	 # because $ac_f cannot contain `:'.
+	 test -f "$ac_f" ||
+	   case $ac_f in
+	   [\\/$]*) false;;
+	   *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";;
+	   esac ||
+	   { { echo "$as_me:$LINENO: error: cannot find input file: $ac_f" >&5
+echo "$as_me: error: cannot find input file: $ac_f" >&2;}
+   { (exit 1); exit 1; }; };;
+      esac
+      ac_file_inputs="$ac_file_inputs $ac_f"
+    done
+
+    # Let's still pretend it is `configure' which instantiates (i.e., don't
+    # use $as_me), people would be surprised to read:
+    #    /* config.h.  Generated by config.status.  */
+    configure_input="Generated from "`IFS=:
+	  echo $* | sed 's|^[^:]*/||;s|:[^:]*/|, |g'`" by configure."
+    if test x"$ac_file" != x-; then
+      configure_input="$ac_file.  $configure_input"
+      { echo "$as_me:$LINENO: creating $ac_file" >&5
+echo "$as_me: creating $ac_file" >&6;}
+    fi
+
+    case $ac_tag in
+    *:-:* | *:-) cat >"$tmp/stdin";;
+    esac
+    ;;
   esac
 
-  # Adjust a relative srcdir, top_srcdir, and INSTALL for subdirectories.
+  ac_dir=`$as_dirname -- "$ac_file" ||
+$as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+	 X"$ac_file" : 'X\(//\)[^/]' \| \
+	 X"$ac_file" : 'X\(//\)$' \| \
+	 X"$ac_file" : 'X\(/\)' \| . 2>/dev/null ||
+echo X"$ac_file" |
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)[^/].*/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+  { as_dir="$ac_dir"
+  case $as_dir in #(
+  -*) as_dir=./$as_dir;;
+  esac
+  test -d "$as_dir" || { $as_mkdir_p && mkdir -p "$as_dir"; } || {
+    as_dirs=
+    while :; do
+      case $as_dir in #(
+      *\'*) as_qdir=`echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #(
+      *) as_qdir=$as_dir;;
+      esac
+      as_dirs="'$as_qdir' $as_dirs"
+      as_dir=`$as_dirname -- "$as_dir" ||
+$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+	 X"$as_dir" : 'X\(//\)[^/]' \| \
+	 X"$as_dir" : 'X\(//\)$' \| \
+	 X"$as_dir" : 'X\(/\)' \| . 2>/dev/null ||
+echo X"$as_dir" |
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)[^/].*/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+      test -d "$as_dir" && break
+    done
+    test -z "$as_dirs" || eval "mkdir $as_dirs"
+  } || test -d "$as_dir" || { { echo "$as_me:$LINENO: error: cannot create directory $as_dir" >&5
+echo "$as_me: error: cannot create directory $as_dir" >&2;}
+   { (exit 1); exit 1; }; }; }
+  ac_builddir=.
 
-  # 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_dir" in
+.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;
+*)
+  ac_dir_suffix=/`echo "$ac_dir" | sed 's,^\.[\\/],,'`
+  # A ".." for each directory in $ac_dir_suffix.
+  ac_top_builddir_sub=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,/..,g;s,/,,'`
+  case $ac_top_builddir_sub in
+  "") ac_top_builddir_sub=. ac_top_build_prefix= ;;
+  *)  ac_top_build_prefix=$ac_top_builddir_sub/ ;;
+  esac ;;
+esac
+ac_abs_top_builddir=$ac_pwd
+ac_abs_builddir=$ac_pwd$ac_dir_suffix
+# for backward compatibility:
+ac_top_builddir=$ac_top_build_prefix
 
-  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" ;;
+case $srcdir in
+  .)  # We are building in place.
+    ac_srcdir=.
+    ac_top_srcdir=$ac_top_builddir_sub
+    ac_abs_top_srcdir=$ac_pwd ;;
+  [\\/]* | ?:[\\/]* )  # Absolute name.
+    ac_srcdir=$srcdir$ac_dir_suffix;
+    ac_top_srcdir=$srcdir
+    ac_abs_top_srcdir=$srcdir ;;
+  *) # Relative name.
+    ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix
+    ac_top_srcdir=$ac_top_build_prefix$srcdir
+    ac_abs_top_srcdir=$ac_pwd/$srcdir ;;
+esac
+ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix
+
+
+  case $ac_mode in
+  :F)
+  #
+  # CONFIG_FILE
+  #
+
+_ACEOF
+
+cat >>$CONFIG_STATUS <<\_ACEOF
+# If the template does not know about datarootdir, expand it.
+# FIXME: This hack should be removed a few years after 2.60.
+ac_datarootdir_hack=; ac_datarootdir_seen=
+
+case `sed -n '/datarootdir/ {
+  p
+  q
+}
+/@datadir@/p
+/@docdir@/p
+/@infodir@/p
+/@localedir@/p
+/@mandir@/p
+' $ac_file_inputs` in
+*datarootdir*) ac_datarootdir_seen=yes;;
+*@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*)
+  { echo "$as_me:$LINENO: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5
+echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;}
+_ACEOF
+cat >>$CONFIG_STATUS <<_ACEOF
+  ac_datarootdir_hack='
+  s&@datadir@&$datadir&g
+  s&@docdir@&$docdir&g
+  s&@infodir@&$infodir&g
+  s&@localedir@&$localedir&g
+  s&@mandir@&$mandir&g
+    s&\\\${datarootdir}&$datarootdir&g' ;;
+esac
+_ACEOF
+
+# Neutralize VPATH when `$srcdir' = `.'.
+# Shell code in configure.ac might set extrasub.
+# FIXME: do we really want to maintain this feature?
+cat >>$CONFIG_STATUS <<_ACEOF
+  sed "$ac_vpsub
+$extrasub
+_ACEOF
+cat >>$CONFIG_STATUS <<\_ACEOF
+:t
+/@[a-zA-Z_][a-zA-Z_0-9]*@/!b
+s&@configure_input@&$configure_input&;t t
+s&@top_builddir@&$ac_top_builddir_sub&;t t
+s&@srcdir@&$ac_srcdir&;t t
+s&@abs_srcdir@&$ac_abs_srcdir&;t t
+s&@top_srcdir@&$ac_top_srcdir&;t t
+s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t
+s&@builddir@&$ac_builddir&;t t
+s&@abs_builddir@&$ac_abs_builddir&;t t
+s&@abs_top_builddir@&$ac_abs_top_builddir&;t t
+$ac_datarootdir_hack
+" $ac_file_inputs | sed -f "$tmp/subs-1.sed" >$tmp/out
+
+test -z "$ac_datarootdir_hack$ac_datarootdir_seen" &&
+  { ac_out=`sed -n '/\${datarootdir}/p' "$tmp/out"`; test -n "$ac_out"; } &&
+  { ac_out=`sed -n '/^[	 ]*datarootdir[	 ]*:*=/p' "$tmp/out"`; test -z "$ac_out"; } &&
+  { echo "$as_me:$LINENO: WARNING: $ac_file contains a reference to the variable \`datarootdir'
+which seems to be undefined.  Please make sure it is defined." >&5
+echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir'
+which seems to be undefined.  Please make sure it is defined." >&2;}
+
+  rm -f "$tmp/stdin"
+  case $ac_file in
+  -) cat "$tmp/out"; rm -f "$tmp/out";;
+  *) rm -f "$ac_file"; mv "$tmp/out" $ac_file;;
+  esac
+ ;;
+
+
+
   esac
 
+done # for ac_tag
 
-  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*
+{ (exit 0); exit 0; }
+_ACEOF
+chmod +x $CONFIG_STATUS
+ac_clean_files=$ac_clean_files_save
 
-EOF
-cat >> $CONFIG_STATUS <<EOF
 
-EOF
-cat >> $CONFIG_STATUS <<\EOF
+# configure is writing to config.log, and then calls config.status.
+# config.status does its own redirection, appending to config.log.
+# Unfortunately, on DOS this fails, as config.log is still kept open
+# by configure, so config.status won't be able to write to it; its
+# output is simply discarded.  So we exec the FD to /dev/null,
+# effectively closing config.log, so it can be properly (re)opened and
+# appended to by config.status.  When coming back to configure, we
+# need to make the FD available again.
+if test "$no_create" != yes; then
+  ac_cs_success=:
+  ac_config_status_args=
+  test "$silent" = yes &&
+    ac_config_status_args="$ac_config_status_args --quiet"
+  exec 5>/dev/null
+  $SHELL $CONFIG_STATUS $ac_config_status_args || ac_cs_success=false
+  exec 5>>config.log
+  # Use ||, not &&, to avoid exiting from the if with $? = 1, which
+  # would make configure fail if this is the last instruction.
+  $ac_cs_success || { (exit 1); exit 1; }
+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
-
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/doc/configure.ac
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/contrib/gperf/doc/configure.ac	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,37 @@
+dnl autoconf configuration for gperf/doc
+
+dnl Copyright (C) 1998, 2000, 2002-2003, 2007 Free Software Foundation, Inc.
+dnl Written by Douglas C. Schmidt <schmidt at ics.uci.edu>
+dnl and Bruno Haible <bruno at clisp.org>.
+dnl
+dnl This file is part of GNU GPERF.
+dnl
+dnl GNU GPERF is free software; you can redistribute it and/or modify
+dnl it under the terms of the GNU General Public License as published by
+dnl the Free Software Foundation; either version 2, or (at your option)
+dnl any later version.
+dnl
+dnl GNU GPERF is distributed in the hope that it will be useful,
+dnl but WITHOUT ANY WARRANTY; without even the implied warranty of
+dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+dnl GNU General Public License for more details.
+dnl
+dnl You should have received a copy of the GNU General Public License
+dnl along with this program; see the file COPYING.
+dnl If not, write to the Free Software Foundation, Inc.,
+dnl 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
+
+AC_PREREQ([2.60])
+AC_INIT(gperf.1)
+PACKAGE=gperf
+AC_SUBST(PACKAGE)
+AC_PROG_MAKE_SET
+dnl
+dnl           checks for programs
+dnl
+CL_PROG_INSTALL
+                      dnl sets variables INSTALL, INSTALL_DATA, INSTALL_PROGRAM
+dnl
+dnl           That's it.
+dnl
+AC_OUTPUT(Makefile)
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/doc/configure.in
--- a/head/contrib/gperf/doc/configure.in	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,35 +0,0 @@
-dnl autoconf configuration for gperf/doc
-
-dnl Copyright (C) 1998, 2000 Free Software Foundation, Inc.
-dnl written by Douglas C. Schmidt (schmidt at ics.uci.edu)
-dnl
-dnl This file is part of GNU GPERF.
-dnl
-dnl GNU GPERF is free software; you can redistribute it and/or modify
-dnl it under the terms of the GNU General Public License as published by
-dnl the Free Software Foundation; either version 1, or (at your option)
-dnl any later version.
-dnl
-dnl GNU GPERF is distributed in the hope that it will be useful,
-dnl but WITHOUT ANY WARRANTY; without even the implied warranty of
-dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-dnl GNU General Public License for more details.
-dnl
-dnl You should have received a copy of the GNU General Public License
-dnl along with GNU GPERF; see the file COPYING.  If not, write to the
-dnl Free Software Foundation, 59 Temple Place - Suite 330, Boston,
-dnl MA 02111-1307, USA.
-
-AC_INIT(gperf.1)
-PACKAGE=gperf
-AC_SUBST(PACKAGE)
-AC_PROG_MAKE_SET
-dnl
-dnl           checks for programs
-dnl
-CL_PROG_INSTALL
-                      dnl sets variables INSTALL, INSTALL_DATA, INSTALL_PROGRAM
-dnl
-dnl           That's it.
-dnl
-AC_OUTPUT(Makefile)
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/doc/gperf.1
--- a/head/contrib/gperf/doc/gperf.1	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/contrib/gperf/doc/gperf.1	Tue Dec 06 20:26:16 2011 +0200
@@ -1,21 +1,27 @@
-.\" DO NOT MODIFY THIS FILE!  It was generated by help2man 1.022.
-.TH GPERF "1" "September 2000" "GNU gperf 2.7.2" FSF
+.\" DO NOT MODIFY THIS FILE!  It was generated by help2man 1.23.
+.TH GPERF "1" "May 2007" "GNU gperf 3.0.3" FSF
 .SH NAME
 gperf \- generate a perfect hash function from a key set
 .SH SYNOPSIS
 .B gperf
 [\fIOPTION\fR]... [\fIINPUT-FILE\fR]
 .SH DESCRIPTION
-GNU `gperf' generates perfect hash functions.
+GNU 'gperf' generates perfect hash functions.
 .PP
 If a long option shows an argument as mandatory, then it is mandatory
 for the equivalent short option also.
+.SS "Output file location:"
+.HP
+\fB\-\-output\-file\fR=\fIFILE\fR Write output to specified file.
+.PP
+The results are written to standard output if no output file is specified
+or if it is -.
 .SS "Input file interpretation:"
 .TP
 \fB\-e\fR, \fB\-\-delimiters\fR=\fIDELIMITER\-LIST\fR
 Allow user to provide a string containing delimiters
 used to separate keywords from their attributes.
-Default is ",\en".
+Default is ",".
 .TP
 \fB\-t\fR, \fB\-\-struct\-type\fR
 Allows the user to include a structured type
@@ -23,6 +29,11 @@
 is considered part of the type declaration. Key
 words and additional fields may follow this, one
 group of fields per line.
+.TP
+\fB\-\-ignore\-case\fR
+Consider upper and lower case ASCII characters as
+equivalent. Note that locale dependent case mappings
+are ignored.
 .SS "Language for the output code:"
 .TP
 \fB\-L\fR, \fB\-\-language\fR=\fILANGUAGE\-NAME\fR
@@ -39,21 +50,27 @@
 Initializers for additional components in the keyword
 structure.
 .TP
-\fB\-H\fR, \fB\-\-hash\-fn\-name\fR=\fINAME\fR
+\fB\-H\fR, \fB\-\-hash\-function\-name\fR=\fINAME\fR
 Specify name of generated hash function. Default is
-`hash'.
+\&'hash'.
 .TP
-\fB\-N\fR, \fB\-\-lookup\-fn\-name\fR=\fINAME\fR
+\fB\-N\fR, \fB\-\-lookup\-function\-name\fR=\fINAME\fR
 Specify name of generated lookup function. Default
-name is `in_word_set'.
+name is 'in_word_set'.
 .TP
 \fB\-Z\fR, \fB\-\-class\-name\fR=\fINAME\fR
 Specify name of generated C++ class. Default name is
-`Perfect_Hash'.
+\&'Perfect_Hash'.
 .TP
 \fB\-7\fR, \fB\-\-seven\-bit\fR
 Assume 7-bit characters.
 .TP
+\fB\-l\fR, \fB\-\-compare\-lengths\fR
+Compare key lengths before trying a string
+comparison. This is necessary if the keywords
+contain NUL bytes. It also helps cut down on the
+number of string comparisons made during the lookup.
+.TP
 \fB\-c\fR, \fB\-\-compare\-strncmp\fR
 Generate comparison code using strncmp rather than
 strcmp.
@@ -70,14 +87,31 @@
 Include the necessary system include file <string.h>
 at the beginning of the code.
 .TP
-\fB\-G\fR, \fB\-\-global\fR
+\fB\-G\fR, \fB\-\-global\-table\fR
 Generate the static table of keywords as a static
 global variable, rather than hiding it inside of the
 lookup function (which is the default behavior).
 .TP
+\fB\-P\fR, \fB\-\-pic\fR
+Optimize the generated table for inclusion in shared
+libraries.  This reduces the startup time of programs
+using a shared library containing the generated code.
+.TP
+\fB\-Q\fR, \fB\-\-string\-pool\-name\fR=\fINAME\fR
+Specify name of string pool generated by option \fB\-\-pic\fR.
+Default name is 'stringpool'.
+.TP
+\fB\-\-null\-strings\fR
+Use NULL strings instead of empty strings for empty
+keyword table entries.
+.TP
 \fB\-W\fR, \fB\-\-word\-array\-name\fR=\fINAME\fR
 Specify name of word list array. Default name is
-`wordlist'.
+\&'wordlist'.
+.TP
+\fB\-\-length\-table\-name\fR=\fINAME\fR
+Specify name of length table array. Default name is
+\&'lengthtable'.
 .TP
 \fB\-S\fR, \fB\-\-switch\fR=\fICOUNT\fR
 Causes the generated C code to use a switch
@@ -99,30 +133,23 @@
 .TP
 \fB\-k\fR, \fB\-\-key\-positions\fR=\fIKEYS\fR
 Select the key positions used in the hash function.
-The allowable choices range between 1-126, inclusive.
+The allowable choices range between 1-255, inclusive.
 The positions are separated by commas, ranges may be
 used, and key positions may occur in any order.
 Also, the meta-character '*' causes the generated
 hash function to consider ALL key positions, and $
-indicates the ``final character'' of a key, e.g.,
+indicates the "final character" of a key, e.g.,
 $,1,2,4,6-10.
 .TP
-\fB\-l\fR, \fB\-\-compare\-strlen\fR
-Compare key lengths before trying a string
-comparison. This helps cut down on the number of
-string comparisons made during the lookup.
-.TP
 \fB\-D\fR, \fB\-\-duplicates\fR
 Handle keywords that hash to duplicate values. This
 is useful for certain highly redundant keyword sets.
 .TP
-\fB\-f\fR, \fB\-\-fast\fR=\fIITERATIONS\fR
-Generate the gen-perf.hash function ``fast''. This
-decreases gperf's running time at the cost of
-minimizing generated table size. The numeric
-argument represents the number of times to iterate
-when resolving a collision. `0' means ``iterate by
-the number of keywords''.
+\fB\-m\fR, \fB\-\-multiple\-iterations\fR=\fIITERATIONS\fR
+Perform multiple choices of the \fB\-i\fR and \fB\-j\fR values,
+and choose the best results. This increases the
+running time by a factor of ITERATIONS but does a
+good job minimizing the generated table size.
 .TP
 \fB\-i\fR, \fB\-\-initial\-asso\fR=\fIN\fR
 Provide an initial value for the associate values
@@ -130,7 +157,7 @@
 inflate the size of the final table.
 .TP
 \fB\-j\fR, \fB\-\-jump\fR=\fIJUMP\-VALUE\fR
-Affects the ``jump value'', i.e., how far to advance
+Affects the "jump value", i.e., how far to advance
 the associated character value upon collisions. Must
 be an odd number, default is 5.
 .TP
@@ -138,25 +165,20 @@
 Do not include the length of the keyword when
 computing the hash function.
 .TP
-\fB\-o\fR, \fB\-\-occurrence\-sort\fR
-Reorders input keys by frequency of occurrence of
-the key sets. This should decrease the search time
-dramatically.
-.TP
 \fB\-r\fR, \fB\-\-random\fR
 Utilizes randomness to initialize the associated
 values table.
 .TP
 \fB\-s\fR, \fB\-\-size\-multiple\fR=\fIN\fR
 Affects the size of the generated hash table. The
-numeric argument N indicates ``how many times larger
-or smaller'' the associated value range should be,
+numeric argument N indicates "how many times larger
+or smaller" the associated value range should be,
 in relationship to the number of keys, e.g. a value
-of 3 means ``allow the maximum associated value to
+of 3 means "allow the maximum associated value to
 be about 3 times larger than the number of input
-keys.'' Conversely, a value of \fB\-3\fR means ``make the
+keys". Conversely, a value of 1/3 means "make the
 maximum associated value about 3 times smaller than
-the number of input keys. A larger table should
+the number of input keys". A larger table should
 decrease the time required for an unsuccessful
 search, at the expense of extra table space. Default
 value is 1.
@@ -171,8 +193,15 @@
 \fB\-d\fR, \fB\-\-debug\fR
 Enables the debugging option (produces verbose
 output to the standard error).
+.SH AUTHOR
+Written by Douglas C. Schmidt and Bruno Haible.
 .SH "REPORTING BUGS"
-Report bugs to <bug-gnu-utils at gnu.org>.
+Report bugs to <bug-gnu-gperf at gnu.org>.
+.SH COPYRIGHT
+Copyright \(co 1989-1998, 2000-2004, 2006-2007 Free Software Foundation, Inc.
+.br
+This is free software; see the source for copying conditions.  There is NO
+warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 .SH "SEE ALSO"
 The full documentation for
 .B gperf
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/doc/gperf.texi
--- a/head/contrib/gperf/doc/gperf.texi	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/contrib/gperf/doc/gperf.texi	Tue Dec 06 20:26:16 2011 +0200
@@ -7,9 +7,9 @@
 
 @c some day we should @include version.texi instead of defining
 @c these values at hand.
- at set UPDATED 26 September 2000
- at set EDITION 2.7.2
- at set VERSION 2.7.2
+ at set UPDATED 31 March 2007
+ at set EDITION 3.0.3
+ at set VERSION 3.0.3
 @c ---------------------
 
 @c remove the black boxes generated in the GPL appendix.
@@ -28,7 +28,7 @@
 This file documents the features of the GNU Perfect Hash Function
 Generator @value{VERSION}.
 
-Copyright @copyright{} 1989-2000 Free Software Foundation, Inc.
+Copyright @copyright{} 1989-2006 Free Software Foundation, Inc.
 
 Permission is granted to make and distribute verbatim copies of this
 manual provided the copyright notice and this permission notice are
@@ -62,10 +62,11 @@
 @subtitle The GNU Perfect Hash Function Generator
 @subtitle Edition @value{EDITION}, @value{UPDATED}
 @author Douglas C. Schmidt
+ at author Bruno Haible
 
 @page
 @vskip 0pt plus 1filll
-Copyright @copyright{} 1989-2000 Free Software Foundation, Inc.
+Copyright @copyright{} 1989-2007 Free Software Foundation, Inc.
 
 
 Permission is granted to make and distribute verbatim copies of
@@ -98,13 +99,12 @@
 * Copying::                     GNU @code{gperf} General Public License says
                                 how you can copy and share @code{gperf}.
 * Contributors::                People who have contributed to @code{gperf}.
-* Motivation::                  Static search structures and GNU GPERF.
+* Motivation::                  The purpose of @code{gperf}.
 * Search Structures::           Static search structures and GNU @code{gperf}
 * Description::                 High-level discussion of how GPERF functions.
 * Options::                     A description of options to the program.
 * Bugs::                        Known bugs and limitations with GPERF.
 * Projects::                    Things still left to do.
-* Implementation::              Implementation Details for GNU GPERF.
 * Bibliography::                Material Referenced in this Report.
 
 * Concept Index::               
@@ -115,13 +115,20 @@
 
 * Input Format::                Input Format to @code{gperf}
 * Output Format::               Output Format for Generated C Code with @code{gperf}
-* Binary Strings::              Use of NUL characters
+* Binary Strings::              Use of NUL bytes
 
 Input Format to @code{gperf}
 
-* Declarations::                @code{struct} Declarations and C Code Inclusion.
+* Declarations::                Declarations.
 * Keywords::                    Format for Keyword Entries.
 * Functions::                   Including Additional C Functions.
+* Controls for GNU indent::     Where to place directives for GNU @code{indent}.
+
+Declarations
+
+* User-supplied Struct::        Specifying keywords with attributes.
+* Gperf Declarations::          Embedding command line options in the input.
+* C Code Inclusion::            Including C declarations and definitions.
 
 Invoking @code{gperf}
 
@@ -147,15 +154,13 @@
 @item
 @cindex Bugs 
 The GNU @code{gperf} perfect hash function generator utility was
-originally written in GNU C++ by Douglas C. Schmidt.  It is now also
-available in a highly-portable ``old-style'' C version.  The general
+written in GNU C++ by Douglas C. Schmidt.  The general
 idea for the perfect hash function generator was inspired by Keith
 Bostic's algorithm written in C, and distributed to net.sources around
 1984.  The current program is a heavily modified, enhanced, and extended
 implementation of Keith's basic idea, created at the University of
 California, Irvine.  Bugs, patches, and suggestions should be reported
-to both @code{<bug-gnu-utils@@gnu.org>} and
- at code{<gperf-bugs@@lists.sourceforge.net>}.
+to @code{<bug-gnu-gperf@@gnu.org>}.
 
 @item
 Special thanks is extended to Michael Tiemann and Doug Lea, for
@@ -166,8 +171,9 @@
 that greatly helped improve the quality and functionality of @code{gperf}.
 
 @item
-A testsuite was added by Bruno Haible. He also rewrote the output
-routines for better reliability.
+Bruno Haible enhanced and optimized the search algorithm.  He also rewrote
+the input routines and the output routines for better reliability, and
+added a testsuite.
 @end itemize
 
 @node Motivation, Search Structures, Contributors, Top
@@ -176,8 +182,8 @@
 @code{gperf} is a perfect hash function generator written in C++.  It
 transforms an @var{n} element user-specified keyword set @var{W} into a
 perfect hash function @var{F}.  @var{F} uniquely maps keywords in
- at var{W} onto the range 0.. at var{k}, where @var{k} >= @var{n}.  If @var{k}
-= @var{n} then @var{F} is a @emph{minimal} perfect hash function.
+ at var{W} onto the range 0.. at var{k}, where @var{k} >= @var{n-1}.  If @var{k}
+= @var{n-1} then @var{F} is a @emph{minimal} perfect hash function.
 @code{gperf} generates a 0.. at var{k} element static lookup table and a
 pair of C functions.  These functions determine whether a given
 character string @var{s} occurs in @var{W}, using at most one probe into
@@ -185,11 +191,12 @@
 
 @code{gperf} currently generates the reserved keyword recognizer for
 lexical analyzers in several production and research compilers and
-language processing tools, including GNU C, GNU C++, GNU Pascal, GNU
-Modula 3, and GNU indent.  Complete C++ source code for @code{gperf} is
-available via anonymous ftp from @code{ftp://ftp.gnu.org/pub/gnu/gperf/}.
+language processing tools, including GNU C, GNU C++, GNU Java, GNU Pascal,
+GNU Modula 3, and GNU indent.  Complete C++ source code for @code{gperf} is
+available from @code{http://ftp.gnu.org/pub/gnu/gperf/}.
 A paper describing @code{gperf}'s design and implementation in greater
-detail is available in the Second USENIX C++ Conference proceedings.
+detail is available in the Second USENIX C++ Conference proceedings
+or from @code{http://www.cs.wustl.edu/~schmidt/resume.html}.
 
 @node Search Structures, Description, Motivation, Top
 @chapter Static search structures and GNU @code{gperf}
@@ -198,7 +205,7 @@
 A @dfn{static search structure} is an Abstract Data Type with certain
 fundamental operations, e.g., @emph{initialize}, @emph{insert},
 and @emph{retrieve}.  Conceptually, all insertions occur before any
-retrievals.  In practice, @code{gperf} generates a @code{static} array
+retrievals.  In practice, @code{gperf} generates a @emph{static} array
 containing search set keywords and any associated attributes specified
 by the user.  Thus, there is essentially no execution-time cost for the
 insertions.  It is a useful data structure for representing @emph{static
@@ -254,8 +261,8 @@
 search structures by hand.  It has proven a useful and practical tool
 for serious programming projects.  Output from @code{gperf} is currently
 used in several production and research compilers, including GNU C, GNU
-C++, GNU Pascal, and GNU Modula 3.  The latter two compilers are not yet
-part of the official GNU distribution.  Each compiler utilizes
+C++, GNU Java, GNU Pascal, and GNU Modula 3.  The latter two compilers are
+not yet part of the official GNU distribution.  Each compiler utilizes
 @code{gperf} to automatically generate static search structures that
 efficiently identify their respective reserved keywords.
 
@@ -265,11 +272,11 @@
 @menu
 * Input Format::                Input Format to @code{gperf}
 * Output Format::               Output Format for Generated C Code with @code{gperf}
-* Binary Strings::              Use of NUL characters
+* Binary Strings::              Use of NUL bytes
 @end menu
 
 The perfect hash function generator @code{gperf} reads a set of
-``keywords'' from a @dfn{keyfile} (or from the standard input by
+``keywords'' from an input file (or from the standard input by
 default).  It attempts to derive a perfect hashing function that
 recognizes a member of the @dfn{static keyword set} with at most a
 single probe into the lookup table.  If @code{gperf} succeeds in
@@ -288,7 +295,7 @@
 using a C @code{switch} may actually speed up the keyword retrieval time
 somewhat.  Actual results depend on your C compiler, of course.
 
-In general, @code{gperf} assigns values to the characters it is using
+In general, @code{gperf} assigns values to the bytes it is using
 for hashing until some set of values gives each keyword a unique value.
 A helpful heuristic is that the larger the hash value range, the easier
 it is for @code{gperf} to find and generate a perfect hash function.
@@ -300,7 +307,7 @@
 @cindex Declaration section
 @cindex Keywords section
 @cindex Functions section
-You can control the input keyfile format by varying certain command-line
+You can control the input file format by varying certain command-line
 arguments, in particular the @samp{-t} option.  The input's appearance
 is similar to GNU utilities @code{flex} and @code{bison} (or UNIX
 utilities @code{lex} and @code{yacc}).  Here's an outline of the general
@@ -316,34 +323,64 @@
 @end group
 @end example
 
- at emph{Unlike} @code{flex} or @code{bison}, all sections of
- at code{gperf}'s input are optional.  The following sections describe the
+ at emph{Unlike} @code{flex} or @code{bison}, the declarations section and
+the functions section are optional.  The following sections describe the
 input format for each section.
 
 @menu
-* Declarations::                @code{struct} Declarations and C Code Inclusion.
+* Declarations::                Declarations.
 * Keywords::                    Format for Keyword Entries.
 * Functions::                   Including Additional C Functions.
+* Controls for GNU indent::     Where to place directives for GNU @code{indent}.
 @end menu
 
+It is possible to omit the declaration section entirely, if the @samp{-t}
+option is not given.  In this case the input file begins directly with the
+first keyword line, e.g.:
+
+ at example
+ at group
+january
+february
+march
+april
+...
+ at end group
+ at end example
+
 @node Declarations, Keywords, Input Format, Input Format
- at subsection @code{struct} Declarations and C Code Inclusion
+ at subsection Declarations
 
 The keyword input file optionally contains a section for including
-arbitrary C declarations and definitions, as well as provisions for
-providing a user-supplied @code{struct}.  If the @samp{-t} option
+arbitrary C declarations and definitions, @code{gperf} declarations that
+act like command-line options, as well as for providing a user-supplied
+ at code{struct}.
+
+ at menu
+* User-supplied Struct::        Specifying keywords with attributes.
+* Gperf Declarations::          Embedding command line options in the input.
+* C Code Inclusion::            Including C declarations and definitions.
+ at end menu
+
+ at node User-supplied Struct, Gperf Declarations, Declarations, Declarations
+ at subsubsection User-supplied @code{struct}
+
+If the @samp{-t} option (or, equivalently, the @samp{%struct-type} declaration)
 @emph{is} enabled, you @emph{must} provide a C @code{struct} as the last
-component in the declaration section from the keyfile file.  The first
-field in this struct must be a @code{char *} or @code{const char *}
-identifier called @samp{name}, although it is possible to modify this
-field's name with the @samp{-K} option described below.
+component in the declaration section from the input file.  The first
+field in this struct must be of type @code{char *} or @code{const char *}
+if the @samp{-P} option is not given, or of type @code{int} if the option
+ at samp{-P} (or, equivalently, the @samp{%pic} declaration) is enabled.
+This first field must be called @samp{name}, although it is possible to modify
+its name with the @samp{-K} option (or, equivalently, the
+ at samp{%define slot-name} declaration) described below.
 
 Here is a simple example, using months of the year and their attributes as
 input:
 
 @example
 @group
-struct months @{ char *name; int number; int days; int leap_days; @};
+struct month @{ char *name; int number; int days; int leap_days; @};
 %%
 january,   1, 31, 31
 february,  2, 28, 29
@@ -366,6 +403,236 @@
 appearing left justified in the first column, as in the UNIX utility
 @code{lex}.
 
+If the @code{struct} has already been declared in an include file, it can
+be mentioned in an abbreviated form, like this:
+
+ at example
+ at group
+struct month;
+%%
+january,   1, 31, 31
+...
+ at end group
+ at end example
+
+ at node Gperf Declarations, C Code Inclusion, User-supplied Struct, Declarations
+ at subsubsection Gperf Declarations
+
+The declaration section can contain @code{gperf} declarations.  They
+influence the way @code{gperf} works, like command line options do.
+In fact, every such declaration is equivalent to a command line option.
+There are three forms of declarations:
+
+ at enumerate
+ at item
+Declarations without argument, like @samp{%compare-lengths}.
+
+ at item
+Declarations with an argument, like @samp{%switch=@var{count}}.
+
+ at item
+Declarations of names of entities in the output file, like
+ at samp{%define lookup-function-name @var{name}}.
+ at end enumerate
+
+When a declaration is given both in the input file and as a command line
+option, the command-line option's value prevails.
+
+The following @code{gperf} declarations are available.
+
+ at table @samp
+ at item %delimiters=@var{delimiter-list}
+ at cindex @samp{%delimiters}
+Allows you to provide a string containing delimiters used to
+separate keywords from their attributes.  The default is ",".  This
+option is essential if you want to use keywords that have embedded
+commas or newlines.
+
+ at item %struct-type
+ at cindex @samp{%struct-type}
+Allows you to include a @code{struct} type declaration for generated
+code; see above for an example.
+
+ at item %ignore-case
+ at cindex @samp{%ignore-case}
+Consider upper and lower case ASCII characters as equivalent.  The string
+comparison will use a case insignificant character comparison.  Note that
+locale dependent case mappings are ignored.
+
+ at item %language=@var{language-name}
+ at cindex @samp{%language}
+Instructs @code{gperf} to generate code in the language specified by the
+option's argument.  Languages handled are currently:
+
+ at table @samp
+ at item KR-C
+Old-style K&R C.  This language is understood by old-style C compilers and
+ANSI C compilers, but ANSI C compilers may flag warnings (or even errors)
+because of lacking @samp{const}.
+
+ at item C
+Common C.  This language is understood by ANSI C compilers, and also by
+old-style C compilers, provided that you @code{#define const} to empty
+for compilers which don't know about this keyword.
+
+ at item ANSI-C
+ANSI C.  This language is understood by ANSI C compilers and C++ compilers.
+
+ at item C++
+C++.  This language is understood by C++ compilers.
+ at end table
+
+The default is C.
+
+ at item %define slot-name @var{name}
+ at cindex @samp{%define slot-name}
+This declaration is only useful when option @samp{-t} (or, equivalently, the
+ at samp{%struct-type} declaration) has been given.
+By default, the program assumes the structure component identifier for
+the keyword is @samp{name}.  This option allows an arbitrary choice of
+identifier for this component, although it still must occur as the first
+field in your supplied @code{struct}.
+
+ at item %define initializer-suffix @var{initializers}
+ at cindex @samp{%define initializer-suffix}
+This declaration is only useful when option @samp{-t} (or, equivalently, the
+ at samp{%struct-type} declaration) has been given.
+It permits to specify initializers for the structure members following
+ at var{slot-name} in empty hash table entries.  The list of initializers
+should start with a comma.  By default, the emitted code will
+zero-initialize structure members following @var{slot-name}.
+
+ at item %define hash-function-name @var{name}
+ at cindex @samp{%define hash-function-name}
+Allows you to specify the name for the generated hash function.  Default
+name is @samp{hash}.  This option permits the use of two hash tables in
+the same file.
+
+ at item %define lookup-function-name @var{name}
+ at cindex @samp{%define lookup-function-name}
+Allows you to specify the name for the generated lookup function.
+Default name is @samp{in_word_set}.  This option permits multiple
+generated hash functions to be used in the same application.
+
+ at item %define class-name @var{name}
+ at cindex @samp{%define class-name}
+This option is only useful when option @samp{-L C++} (or, equivalently,
+the @samp{%language=C++} declaration) has been given.  It
+allows you to specify the name of generated C++ class.  Default name is
+ at code{Perfect_Hash}.
+
+ at item %7bit
+ at cindex @samp{%7bit}
+This option specifies that all strings that will be passed as arguments
+to the generated hash function and the generated lookup function will
+solely consist of 7-bit ASCII characters (bytes in the range 0..127).
+(Note that the ANSI C functions @code{isalnum} and @code{isgraph} do
+ at emph{not} guarantee that a byte is in this range.  Only an explicit
+test like @samp{c >= 'A' && c <= 'Z'} guarantees this.)
+
+ at item %compare-lengths
+ at cindex @samp{%compare-lengths}
+Compare keyword lengths before trying a string comparison.  This option
+is mandatory for binary comparisons (@pxref{Binary Strings}).  It also might
+cut down on the number of string comparisons made during the lookup, since
+keywords with different lengths are never compared via @code{strcmp}.
+However, using @samp{%compare-lengths} might greatly increase the size of the
+generated C code if the lookup table range is large (which implies that
+the switch option @samp{-S} or @samp{%switch} is not enabled), since the length
+table contains as many elements as there are entries in the lookup table.
+
+ at item %compare-strncmp
+ at cindex @samp{%compare-strncmp}
+Generates C code that uses the @code{strncmp} function to perform
+string comparisons.  The default action is to use @code{strcmp}.
+
+ at item %readonly-tables
+ at cindex @samp{%readonly-tables}
+Makes the contents of all generated lookup tables constant, i.e.,
+``readonly''.  Many compilers can generate more efficient code for this
+by putting the tables in readonly memory.
+
+ at item %enum
+ at cindex @samp{%enum}
+Define constant values using an enum local to the lookup function rather
+than with #defines.  This also means that different lookup functions can
+reside in the same file.  Thanks to James Clark @code{<jjc@@ai.mit.edu>}.
+
+ at item %includes
+ at cindex @samp{%includes}
+Include the necessary system include file, @code{<string.h>}, at the
+beginning of the code.  By default, this is not done; the user must
+include this header file himself to allow compilation of the code.
+
+ at item %global-table
+ at cindex @samp{%global-table}
+Generate the static table of keywords as a static global variable,
+rather than hiding it inside of the lookup function (which is the
+default behavior).
+
+ at item %pic
+ at cindex @samp{%pic}
+Optimize the generated table for inclusion in shared libraries.  This
+reduces the startup time of programs using a shared library containing
+the generated code.  If the @samp{%struct-type} declaration (or,
+equivalently, the option @samp{-t}) is also given, the first field of the
+user-defined struct must be of type @samp{int}, not @samp{char *}, because
+it will contain offsets into the string pool instead of actual strings.
+To convert such an offset to a string, you can use the expression
+ at samp{stringpool + @var{o}}, where @var{o} is the offset.  The string pool
+name can be changed through the @samp{%define string-pool-name} declaration.
+
+ at item %define string-pool-name @var{name}
+ at cindex @samp{%define string-pool-name}
+Allows you to specify the name of the generated string pool created by
+the declaration @samp{%pic} (or, equivalently, the option @samp{-P}).
+The default name is @samp{stringpool}.  This declaration permits the use of
+two hash tables in the same file, with @samp{%pic} and even when the
+ at samp{%global-table} declaration (or, equivalently, the option @samp{-G})
+is given.
+
+ at item %null-strings
+ at cindex @samp{%null-strings}
+Use NULL strings instead of empty strings for empty keyword table entries.
+This reduces the startup time of programs using a shared library containing
+the generated code (but not as much as the declaration @samp{%pic}), at the
+expense of one more test-and-branch instruction at run time.
+
+ at item %define word-array-name @var{name}
+ at cindex @samp{%define word-array-name}
+Allows you to specify the name for the generated array containing the
+hash table.  Default name is @samp{wordlist}.  This option permits the
+use of two hash tables in the same file, even when the option @samp{-G}
+(or, equivalently, the @samp{%global-table} declaration) is given.
+
+ at item %define length-table-name @var{name}
+ at cindex @samp{%define length-table-name}
+Allows you to specify the name for the generated array containing the
+length table.  Default name is @samp{lengthtable}.  This option permits the
+use of two length tables in the same file, even when the option @samp{-G}
+(or, equivalently, the @samp{%global-table} declaration) is given.
+
+ at item %switch=@var{count}
+ at cindex @samp{%switch}
+Causes the generated C code to use a @code{switch} statement scheme,
+rather than an array lookup table.  This can lead to a reduction in both
+time and space requirements for some input files.  The argument to this
+option determines how many @code{switch} statements are generated.  A
+value of 1 generates 1 @code{switch} containing all the elements, a
+value of 2 generates 2 tables with 1/2 the elements in each
+ at code{switch}, etc.  This is useful since many C compilers cannot
+correctly generate code for large @code{switch} statements.  This option
+was inspired in part by Keith Bostic's original C program.
+
+ at item %omit-struct-type
+ at cindex @samp{%omit-struct-type}
+Prevents the transfer of the type declaration to the output file.  Use
+this option if the type is already defined elsewhere.
+ at end table
+
+ at node C Code Inclusion,  , Gperf Declarations, Declarations
+ at subsubsection C Code Inclusion
+
 @cindex @samp{%@{}
 @cindex @samp{%@}}
 Using a syntax similar to GNU utilities @code{flex} and @code{bison}, it
@@ -380,9 +647,9 @@
 %@{
 #include <assert.h>
 /* This section of code is inserted directly into the output. */
-int return_month_days (struct months *months, int is_leap_year);
+int return_month_days (struct month *months, int is_leap_year);
 %@}
-struct months @{ char *name; int number; int days; int leap_days; @};
+struct month @{ char *name; int number; int days; int leap_days; @};
 %%
 january,   1, 31, 31
 february,  2, 28, 29
@@ -391,32 +658,21 @@
 @end group
 @end example
 
-It is possible to omit the declaration section entirely.  In this case
-the keyfile begins directly with the first keyword line, e.g.:
-
- at example
- at group
-january,   1, 31, 31
-february,  2, 28, 29
-march,     3, 31, 31
-april,     4, 30, 30
-...
- at end group
- at end example
-
 @node Keywords, Functions, Declarations, Input Format
 @subsection Format for Keyword Entries
 
-The second keyfile format section contains lines of keywords and any
+The second input file format section contains lines of keywords and any
 associated attributes you might supply.  A line beginning with @samp{#}
 in the first column is considered a comment.  Everything following the
- at samp{#} is ignored, up to and including the following newline.
+ at samp{#} is ignored, up to and including the following newline.  A line
+beginning with @samp{%} in the first column is an option declaration and
+must not occur within the keywords section.
 
-The first field of each non-comment line is always the key itself.  It
+The first field of each non-comment line is always the keyword itself.  It
 can be given in two ways: as a simple name, i.e., without surrounding
 string quotation marks, or as a string enclosed in double-quotes, in
 C syntax, possibly with backslash escapes like @code{\"} or @code{\234}
-or @code{\xa8}. In either case, it must start right at the beginning
+or @code{\xa8}.  In either case, it must start right at the beginning
 of the line, without leading whitespace.
 In this context, a ``field'' is considered to extend up to, but
 not include, the first blank, comma, or newline.  Here is a simple
@@ -445,11 +701,12 @@
 should be separated by commas, and terminate at the end of line.  What
 these fields mean is entirely up to you; they are used to initialize the
 elements of the user-defined @code{struct} provided by you in the
-declaration section.  If the @samp{-t} option is @emph{not} enabled
+declaration section.  If the @samp{-t} option (or, equivalently, the
+ at samp{%struct-type} declaration) is @emph{not} enabled
 these fields are simply ignored.  All previous examples except the last
 one contain keyword attributes.
 
- at node Functions,  , Keywords, Input Format
+ at node Functions, Controls for GNU indent, Keywords, Input Format
 @subsection Including Additional C Functions
 
 The optional third section also corresponds closely with conventions
@@ -459,12 +716,58 @@
 it is your responsibility to ensure that the code contained in this
 section is valid C.
 
+ at node Controls for GNU indent,  , Functions, Input Format
+ at subsection Where to place directives for GNU @code{indent}.
+
+If you want to invoke GNU @code{indent} on a @code{gperf} input file,
+you will see that GNU @code{indent} doesn't understand the @samp{%%},
+ at samp{%@{} and @samp{%@}} directives that control @code{gperf}'s
+interpretation of the input file.  Therefore you have to insert some
+directives for GNU @code{indent}.  More precisely, assuming the most
+general input file structure
+
+ at example
+ at group
+declarations part 1
+%@{
+verbatim code
+%@}
+declarations part 2
+%%
+keywords
+%%
+functions
+ at end group
+ at end example
+
+ at noindent
+you would insert @samp{*INDENT-OFF*} and @samp{*INDENT-ON*} comments
+as follows:
+
+ at example
+ at group
+/* *INDENT-OFF* */
+declarations part 1
+%@{
+/* *INDENT-ON* */
+verbatim code
+/* *INDENT-OFF* */
+%@}
+declarations part 2
+%%
+keywords
+%%
+/* *INDENT-ON* */
+functions
+ at end group
+ at end example
+
 @node Output Format, Binary Strings, Input Format, Description
 @section Output Format for Generated C Code with @code{gperf}
 @cindex hash table
 
 Several options control how the generated C code appears on the standard 
-output.  Two C function are generated.  They are called @code{hash} and 
+output.  Two C functions are generated.  They are called @code{hash} and 
 @code{in_word_set}, although you may modify their names with a command-line 
 option.  Both functions require two arguments, a string, @code{char *} 
 @var{str}, and a length parameter, @code{int} @var{len}.  Their default 
@@ -472,26 +775,28 @@
 
 @deftypefun {unsigned int} hash (const char * @var{str}, unsigned int @var{len})
 By default, the generated @code{hash} function returns an integer value
-created by adding @var{len} to several user-specified @var{str} key
+created by adding @var{len} to several user-specified @var{str} byte
 positions indexed into an @dfn{associated values} table stored in a
 local static array.  The associated values table is constructed
 internally by @code{gperf} and later output as a static local C array
-called @samp{hash_table}; its meaning and properties are described below
-(@pxref{Implementation}). The relevant key positions are specified via
-the @samp{-k} option when running @code{gperf}, as detailed in the
- at emph{Options} section below(@pxref{Options}).
+called @samp{hash_table}.  The relevant selected positions (i.e. indices
+into @var{str}) are specified via the @samp{-k} option when running
+ at code{gperf}, as detailed in the @emph{Options} section below (@pxref{Options}).
 @end deftypefun
 
 @deftypefun {} in_word_set (const char * @var{str}, unsigned int @var{len})
 If @var{str} is in the keyword set, returns a pointer to that
-keyword. More exactly, if the option @samp{-t} was given, it returns
-a pointer to the matching keyword's structure. Otherwise it returns
+keyword.  More exactly, if the option @samp{-t} (or, equivalently, the
+ at samp{%struct-type} declaration) was given, it returns
+a pointer to the matching keyword's structure.  Otherwise it returns
 @code{NULL}.
 @end deftypefun
 
-If the option @samp{-c} is not used, @var{str} must be a NUL terminated
-string of exactly length @var{len}. If @samp{-c} is used, @var{str} must
-simply be an array of @var{len} characters and does not need to be NUL
+If the option @samp{-c} (or, equivalently, the @samp{%compare-strncmp}
+declaration) is not used, @var{str} must be a NUL terminated
+string of exactly length @var{len}.  If @samp{-c} (or, equivalently, the
+ at samp{%compare-strncmp} declaration) is used, @var{str} must
+simply be an array of @var{len} bytes and does not need to be NUL
 terminated.
 
 The code generated for these two functions is affected by the following
@@ -512,44 +817,50 @@
 code.
 @end table
 
-If the @samp{-t} and @samp{-S} options are omitted, the default action
-is to generate a @code{char *} array containing the keys, together with
-additional null strings used for padding the array.  By experimenting
+If the @samp{-t} and @samp{-S} options (or, equivalently, the
+ at samp{%struct-type} and @samp{%switch} declarations) are omitted, the default
+action
+is to generate a @code{char *} array containing the keywords, together with
+additional empty strings used for padding the array.  By experimenting
 with the various input and output options, and timing the resulting C
 code, you can determine the best option choices for different keyword
 set characteristics.
 
 @node Binary Strings,  , Output Format, Description
- at section Use of NUL characters
+ at section Use of NUL bytes
 @cindex NUL
 
 By default, the code generated by @code{gperf} operates on zero
-terminated strings, the usual representation of strings in C. This means
-that the keywords in the input file must not contain NUL characters,
+terminated strings, the usual representation of strings in C.  This means
+that the keywords in the input file must not contain NUL bytes,
 and the @var{str} argument passed to @code{hash} or @code{in_word_set}
 must be NUL terminated and have exactly length @var{len}.
 
-If option @samp{-c} is used, then the @var{str} argument does not need
-to be NUL terminated. The code generated by @code{gperf} will only
+If option @samp{-c} (or, equivalently, the @samp{%compare-strncmp}
+declaration) is used, then the @var{str} argument does not need
+to be NUL terminated.  The code generated by @code{gperf} will only
 access the first @var{len}, not @var{len+1}, bytes starting at @var{str}.
 However, the keywords in the input file still must not contain NUL
-characters.
+bytes.
 
-If option @samp{-l} is used, then the hash table performs binary
-comparison. The keywords in the input file may contain NUL characters,
+If option @samp{-l} (or, equivalently, the @samp{%compare-lengths}
+declaration) is used, then the hash table performs binary
+comparison.  The keywords in the input file may contain NUL bytes,
 written in string syntax as @code{\000} or @code{\x00}, and the code
-generated by @code{gperf} will treat NUL like any other character.
-Also, in this case the @samp{-c} option is ignored.
+generated by @code{gperf} will treat NUL like any other byte.
+Also, in this case the @samp{-c} option (or, equivalently, the
+ at samp{%compare-strncmp} declaration) is ignored.
 
 @node Options, Bugs, Description, Top
 @chapter Invoking @code{gperf}
 
 There are @emph{many} options to @code{gperf}.  They were added to make
 the program more convenient for use with real applications.  ``On-line''
-help is readily available via the @samp{-h} option.  Here is the
+help is readily available via the @samp{--help} option.  Here is the
 complete list of options.
 
 @menu
+* Output File::                 Specifying the Location of the Output File
 * Input Details::               Options that affect Interpretation of the Input File
 * Output Language::             Specifying the Language for the Output Code
 * Output Details::              Fine tuning Details in the Output Code
@@ -557,15 +868,29 @@
 * Verbosity::                   Informative Output
 @end menu
 
- at node Input Details, Output Language, Options, Options
+ at node Output File, Input Details, Options, Options
+ at section Specifying the Location of the Output File
+
+ at table @samp
+ at item --output-file=@var{file}
+Allows you to specify the name of the file to which the output is written to.
+ at end table
+
+The results are written to standard output if no output file is specified
+or if it is @samp{-}.
+
+ at node Input Details, Output Language, Output File, Options
 @section Options that affect Interpretation of the Input File
 
+These options are also available as declarations in the input file
+(@pxref{Gperf Declarations}).
+
 @table @samp
 @item -e @var{keyword-delimiter-list}
 @itemx --delimiters=@var{keyword-delimiter-list}
 @cindex Delimiters
-Allows the user to provide a string containing delimiters used to
-separate keywords from their attributes.  The default is ",\n".  This
+Allows you to provide a string containing delimiters used to
+separate keywords from their attributes.  The default is ",".  This
 option is essential if you want to use keywords that have embedded
 commas or newlines.  One useful trick is to use -e'TAB', where TAB is
 the literal tab character.
@@ -578,11 +903,25 @@
 this, one group of fields per line.  A set of examples for generating
 perfect hash tables and functions for Ada, C, C++, Pascal, Modula 2,
 Modula 3 and JavaScript reserved words are distributed with this release.
+
+ at item --ignore-case
+Consider upper and lower case ASCII characters as equivalent.  The string
+comparison will use a case insignificant character comparison.  Note that
+locale dependent case mappings are ignored.  This option is therefore not
+suitable if a properly internationalized or locale aware case mapping
+should be used.  (For example, in a Turkish locale, the upper case equivalent
+of the lowercase ASCII letter @samp{i} is the non-ASCII character
+ at samp{capital i with dot above}.)  For this case, it is better to apply
+an uppercase or lowercase conversion on the string before passing it to
+the @code{gperf} generated function.
 @end table
 
 @node Output Language, Output Details, Input Details, Options
 @section Options to specify the Language for the Output Code
 
+These options are also available as declarations in the input file
+(@pxref{Gperf Declarations}).
+
 @table @samp
 @item -L @var{generated-language-name}
 @itemx --language=@var{generated-language-name}
@@ -591,41 +930,45 @@
 
 @table @samp
 @item KR-C
-Old-style K&R C. This language is understood by old-style C compilers and
+Old-style K&R C.  This language is understood by old-style C compilers and
 ANSI C compilers, but ANSI C compilers may flag warnings (or even errors)
 because of lacking @samp{const}.
 
 @item C
-Common C. This language is understood by ANSI C compilers, and also by
+Common C.  This language is understood by ANSI C compilers, and also by
 old-style C compilers, provided that you @code{#define const} to empty
 for compilers which don't know about this keyword.
 
 @item ANSI-C
-ANSI C. This language is understood by ANSI C compilers and C++ compilers.
+ANSI C.  This language is understood by ANSI C compilers and C++ compilers.
 
 @item C++
-C++. This language is understood by C++ compilers.
+C++.  This language is understood by C++ compilers.
 @end table
 
 The default is C.
 
 @item -a
 This option is supported for compatibility with previous releases of
- at code{gperf}. It does not do anything.
+ at code{gperf}.  It does not do anything.
 
 @item -g
 This option is supported for compatibility with previous releases of
- at code{gperf}. It does not do anything.
+ at code{gperf}.  It does not do anything.
 @end table
 
 @node Output Details, Algorithmic Details, Output Language, Options
 @section Options for fine tuning Details in the Output Code
 
+Most of these options are also available as declarations in the input file
+(@pxref{Gperf Declarations}).
+
 @table @samp
- at item -K @var{key-name}
- at itemx --slot-name=@var{key-name}
+ at item -K @var{slot-name}
+ at itemx --slot-name=@var{slot-name}
 @cindex Slot name
-This option is only useful when option @samp{-t} has been given.
+This option is only useful when option @samp{-t} (or, equivalently, the
+ at samp{%struct-type} declaration) has been given.
 By default, the program assumes the structure component identifier for
 the keyword is @samp{name}.  This option allows an arbitrary choice of
 identifier for this component, although it still must occur as the first
@@ -634,29 +977,30 @@
 @item -F @var{initializers}
 @itemx --initializer-suffix=@var{initializers}
 @cindex Initializers
-This option is only useful when option @samp{-t} has been given.
+This option is only useful when option @samp{-t} (or, equivalently, the
+ at samp{%struct-type} declaration) has been given.
 It permits to specify initializers for the structure members following
- at var{key name} in empty hash table entries.  The list of initializers
+ at var{slot-name} in empty hash table entries.  The list of initializers
 should start with a comma.  By default, the emitted code will
-zero-initialize structure members following @var{key name}.
+zero-initialize structure members following @var{slot-name}.
 
 @item -H @var{hash-function-name}
- at itemx --hash-fn-name=@var{hash-function-name}
+ at itemx --hash-function-name=@var{hash-function-name}
 Allows you to specify the name for the generated hash function.  Default
 name is @samp{hash}.  This option permits the use of two hash tables in
 the same file.
 
 @item -N @var{lookup-function-name}
- at itemx --lookup-fn-name=@var{lookup-function-name}
+ at itemx --lookup-function-name=@var{lookup-function-name}
 Allows you to specify the name for the generated lookup function.
-Default name is @samp{in_word_set}.  This option permits completely
-automatic generation of perfect hash functions, especially when multiple
-generated hash functions are used in the same application.
+Default name is @samp{in_word_set}.  This option permits multiple
+generated hash functions to be used in the same application.
 
 @item -Z @var{class-name}
 @itemx --class-name=@var{class-name}
 @cindex Class name
-This option is only useful when option @samp{-L C++} has been given.  It
+This option is only useful when option @samp{-L C++} (or, equivalently,
+the @samp{%language=C++} declaration) has been given.  It
 allows you to specify the name of generated C++ class.  Default name is
 @code{Perfect_Hash}.
 
@@ -664,12 +1008,23 @@
 @itemx --seven-bit
 This option specifies that all strings that will be passed as arguments
 to the generated hash function and the generated lookup function will
-solely consist of 7-bit ASCII characters (characters in the range 0..127).
+solely consist of 7-bit ASCII characters (bytes in the range 0..127).
 (Note that the ANSI C functions @code{isalnum} and @code{isgraph} do
- at emph{not} guarantee that a character is in this range. Only an explicit
+ at emph{not} guarantee that a byte is in this range.  Only an explicit
 test like @samp{c >= 'A' && c <= 'Z'} guarantees this.) This was the
 default in versions of @code{gperf} earlier than 2.7; now the default is
-to assume 8-bit characters.
+to support 8-bit and multibyte characters.
+
+ at item -l
+ at itemx --compare-lengths
+Compare keyword lengths before trying a string comparison.  This option
+is mandatory for binary comparisons (@pxref{Binary Strings}).  It also might
+cut down on the number of string comparisons made during the lookup, since
+keywords with different lengths are never compared via @code{strcmp}.
+However, using @samp{-l} might greatly increase the size of the
+generated C code if the lookup table range is large (which implies that
+the switch option @samp{-S} or @samp{%switch} is not enabled), since the length
+table contains as many elements as there are entries in the lookup table.
 
 @item -c
 @itemx --compare-strncmp
@@ -695,30 +1050,63 @@
 include this header file himself to allow compilation of the code.
 
 @item -G
- at itemx --global
+ at itemx --global-table
 Generate the static table of keywords as a static global variable,
 rather than hiding it inside of the lookup function (which is the
 default behavior).
 
+ at item -P
+ at itemx --pic
+Optimize the generated table for inclusion in shared libraries.  This
+reduces the startup time of programs using a shared library containing
+the generated code.  If the option @samp{-t} (or, equivalently, the
+ at samp{%struct-type} declaration) is also given, the first field of the
+user-defined struct must be of type @samp{int}, not @samp{char *}, because
+it will contain offsets into the string pool instead of actual strings.
+To convert such an offset to a string, you can use the expression
+ at samp{stringpool + @var{o}}, where @var{o} is the offset.  The string pool
+name can be changed through the option @samp{--string-pool-name}.
+
+ at item -Q @var{string-pool-name}
+ at itemx --string-pool-name=@var{string-pool-name}
+Allows you to specify the name of the generated string pool created by
+option @samp{-P}.  The default name is @samp{stringpool}.  This option
+permits the use of two hash tables in the same file, with @samp{-P} and
+even when the option @samp{-G} (or, equivalently, the @samp{%global-table}
+declaration) is given.
+
+ at item --null-strings
+Use NULL strings instead of empty strings for empty keyword table entries.
+This reduces the startup time of programs using a shared library containing
+the generated code (but not as much as option @samp{-P}), at the expense
+of one more test-and-branch instruction at run time.
+
 @item -W @var{hash-table-array-name}
 @itemx --word-array-name=@var{hash-table-array-name}
 @cindex Array name
 Allows you to specify the name for the generated array containing the
 hash table.  Default name is @samp{wordlist}.  This option permits the
 use of two hash tables in the same file, even when the option @samp{-G}
-is given.
+(or, equivalently, the @samp{%global-table} declaration) is given.
+
+ at itemx --length-table-name=@var{length-table-array-name}
+ at cindex Array name
+Allows you to specify the name for the generated array containing the
+length table.  Default name is @samp{lengthtable}.  This option permits the
+use of two length tables in the same file, even when the option @samp{-G}
+(or, equivalently, the @samp{%global-table} declaration) is given.
 
 @item -S @var{total-switch-statements}
 @itemx --switch=@var{total-switch-statements}
 @cindex @code{switch}
 Causes the generated C code to use a @code{switch} statement scheme,
 rather than an array lookup table.  This can lead to a reduction in both
-time and space requirements for some keyfiles.  The argument to this
-option determines how many @code{switch} statements are generated. A
+time and space requirements for some input files.  The argument to this
+option determines how many @code{switch} statements are generated.  A
 value of 1 generates 1 @code{switch} containing all the elements, a
 value of 2 generates 2 tables with 1/2 the elements in each
 @code{switch}, etc.  This is useful since many C compilers cannot
-correctly generate code for large @code{switch} statements. This option
+correctly generate code for large @code{switch} statements.  This option
 was inspired in part by Keith Bostic's original C program.
 
 @item -T
@@ -728,93 +1116,73 @@
 
 @item -p
 This option is supported for compatibility with previous releases of
- at code{gperf}. It does not do anything.
+ at code{gperf}.  It does not do anything.
 @end table
 
 @node Algorithmic Details, Verbosity, Output Details, Options
 @section Options for changing the Algorithms employed by @code{gperf}
 
 @table @samp
- at item -k @var{keys}
- at itemx --key-positions=@var{keys}
-Allows selection of the character key positions used in the keywords'
-hash function. The allowable choices range between 1-126, inclusive.
+ at item -k @var{selected-byte-positions}
+ at itemx --key-positions=@var{selected-byte-positions}
+Allows selection of the byte positions used in the keywords'
+hash function.  The allowable choices range between 1-255, inclusive.
 The positions are separated by commas, e.g., @samp{-k 9,4,13,14};
 ranges may be used, e.g., @samp{-k 2-7}; and positions may occur
-in any order.  Furthermore, the meta-character '*' causes the generated
-hash function to consider @strong{all} character positions in each key,
-whereas '$' instructs the hash function to use the ``final character''
-of a key (this is the only way to use a character position greater than
-126, incidentally).
+in any order.  Furthermore, the wildcard '*' causes the generated
+hash function to consider @strong{all} byte positions in each keyword,
+whereas '$' instructs the hash function to use the ``final byte''
+of a keyword (this is the only way to use a byte position greater than
+255, incidentally).
 
 For instance, the option @samp{-k 1,2,4,6-10,'$'} generates a hash
 function that considers positions 1,2,4,6,7,8,9,10, plus the last
-character in each key (which may differ for each key, obviously).  Keys
-with length less than the indicated key positions work properly, since
-selected key positions exceeding the key length are simply not
+byte in each keyword (which may be at a different position for each
+keyword, obviously).  Keywords
+with length less than the indicated byte positions work properly, since
+selected byte positions exceeding the keyword length are simply not
 referenced in the hash function.
 
- at item -l
- at itemx --compare-strlen
-Compare key lengths before trying a string comparison.  This might cut
-down on the number of string comparisons made during the lookup, since
-keys with different lengths are never compared via @code{strcmp}.
-However, using @samp{-l} might greatly increase the size of the
-generated C code if the lookup table range is large (which implies that
-the switch option @samp{-S} is not enabled), since the length table
-contains as many elements as there are entries in the lookup table.
-This option is mandatory for binary comparisons (@pxref{Binary Strings}).
+This option is not normally needed since version 2.8 of @code{gperf};
+the default byte positions are computed depending on the keyword set,
+through a search that minimizes the number of byte positions.
 
 @item -D
 @itemx --duplicates
 @cindex Duplicates
-Handle keywords whose key position sets hash to duplicate values.
-Duplicate hash values occur for two reasons:
-
- at itemize @bullet
- at item
-Since @code{gperf} does not backtrack it is possible for it to process
-all your input keywords without finding a unique mapping for each word.
-However, frequently only a very small number of duplicates occur, and 
-the majority of keys still require one probe into the table.
-
- at item
-Sometimes a set of keys may have the same names, but possess different
-attributes.  With the -D option @code{gperf} treats all these keys as
+Handle keywords whose selected byte sets hash to duplicate values.
+Duplicate hash values can occur if a set of keywords has the same names, but
+possesses different attributes, or if the selected byte positions are not well
+chosen.  With the -D option @code{gperf} treats all these keywords as
 part of an equivalence class and generates a perfect hash function with
-multiple comparisons for duplicate keys.  It is up to you to completely
+multiple comparisons for duplicate keywords.  It is up to you to completely
 disambiguate the keywords by modifying the generated C code.  However,
 @code{gperf} helps you out by organizing the output.
- at end itemize
 
-Option @samp{-D} is extremely useful for certain large or highly
-redundant keyword sets, e.g., assembler instruction opcodes.
 Using this option usually means that the generated hash function is no
 longer perfect.  On the other hand, it permits @code{gperf} to work on
 keyword sets that it otherwise could not handle.
 
- at item -f @var{iteration-amount}
- at itemx --fast=@var{iteration-amount}
-Generate the perfect hash function ``fast''.  This decreases
- at code{gperf}'s running time at the cost of minimizing generated
-table-size.  The iteration amount represents the number of times to
-iterate when resolving a collision.  `0' means iterate by the number of
-keywords.  This option is probably most useful when used in conjunction
-with options @samp{-D} and/or @samp{-S} for @emph{large} keyword sets.
+ at item -m @var{iterations}
+ at itemx --multiple-iterations=@var{iterations}
+Perform multiple choices of the @samp{-i} and @samp{-j} values, and
+choose the best results.  This increases the running time by a factor of
+ at var{iterations} but does a good job minimizing the generated table size.
 
 @item -i @var{initial-value}
 @itemx --initial-asso=@var{initial-value}
 Provides an initial @var{value} for the associate values array.  Default
 is 0.  Increasing the initial value helps inflate the final table size,
 possibly leading to more time efficient keyword lookups.  Note that this
-option is not particularly useful when @samp{-S} is used.  Also,
+option is not particularly useful when @samp{-S} (or, equivalently,
+ at samp{%switch}) is used.  Also,
 @samp{-i} is overridden when the @samp{-r} option is used.
 
 @item -j @var{jump-value}
 @itemx --jump=@var{jump-value}
 @cindex Jump value
 Affects the ``jump value'', i.e., how far to advance the associated
-character value upon collisions.  @var{Jump-value} is rounded up to an
+byte value upon collisions.  @var{Jump-value} is rounded up to an
 odd number, the default is 5.  If the @var{jump-value} is 0 @code{gperf}
 jumps by random amounts.
 
@@ -824,60 +1192,38 @@
 computing its hash value.  This may save a few assembly instructions in
 the generated lookup table.
 
- at item -o
- at itemx --occurrence-sort
-Reorders the keywords by sorting the keywords so that frequently
-occuring key position set components appear first.  A second reordering
-pass follows so that keys with ``already determined values'' are placed
-towards the front of the keylist.  This may decrease the time required
-to generate a perfect hash function for many keyword sets, and also
-produce more minimal perfect hash functions.  The reason for this is
-that the reordering helps prune the search time by handling inevitable
-collisions early in the search process.  On the other hand, if the
-number of keywords is @emph{very} large using @samp{-o} may
- at emph{increase} @code{gperf}'s execution time, since collisions will
-begin earlier and continue throughout the remainder of keyword
-processing.  See Cichelli's paper from the January 1980 Communications
-of the ACM for details.
-
 @item -r
 @itemx --random
 Utilizes randomness to initialize the associated values table.  This
 frequently generates solutions faster than using deterministic
 initialization (which starts all associated values at 0).  Furthermore,
 using the randomization option generally increases the size of the
-table.  If @code{gperf} has difficultly with a certain keyword set try using
- at samp{-r} or @samp{-D}.
+table.
 
 @item -s @var{size-multiple}
 @itemx --size-multiple=@var{size-multiple}
 Affects the size of the generated hash table.  The numeric argument for
 this option indicates ``how many times larger or smaller'' the maximum
-associated value range should be, in relationship to the number of keys.
-If the @var{size-multiple} is negative the maximum associated value is
-calculated by @emph{dividing} it into the total number of keys.  For
-example, a value of 3 means ``allow the maximum associated value to be
-about 3 times larger than the number of input keys''.  
+associated value range should be, in relationship to the number of keywords.
+It can be written as an integer, a floating-point number or a fraction.
+For example, a value of 3 means ``allow the maximum associated value to be
+about 3 times larger than the number of input keywords''.
+Conversely, a value of 1/3 means ``allow the maximum associated value to
+be about 3 times smaller than the number of input keywords''.  Values
+smaller than 1 are useful for limiting the overall size of the generated hash
+table, though the option @samp{-m} is better at this purpose.
 
-Conversely, a value of -3 means ``allow the maximum associated value to
-be about 3 times smaller than the number of input keys''.  Negative
-values are useful for limiting the overall size of the generated hash
-table, though this usually increases the number of duplicate hash
-values.
-
-If `generate switch' option @samp{-S} is @emph{not} enabled, the maximum
+If `generate switch' option @samp{-S} (or, equivalently, @samp{%switch}) is
+ at emph{not} enabled, the maximum
 associated value influences the static array table size, and a larger
 table should decrease the time required for an unsuccessful search, at
 the expense of extra table space.
 
 The default value is 1, thus the default maximum associated value about
-the same size as the number of keys (for efficiency, the maximum
+the same size as the number of keywords (for efficiency, the maximum
 associated value is always rounded up to a power of 2).  The actual
 table size may vary somewhat, since this technique is essentially a
-heuristic.  In particular, setting this value too high slows down
- at code{gperf}'s runtime, since it must search through a much larger range
-of values.  Judicious use of the @samp{-f} option helps alleviate this
-overhead, however.
+heuristic.
 @end table
 
 @node Verbosity,  , Algorithmic Details, Options
@@ -919,16 +1265,6 @@
 When processing large keyword sets it helps greatly to have over 8 megs
 of RAM.
 
-However, since @code{gperf} does not backtrack no guaranteed solution
-occurs on every run.  On the other hand, it is usually easy to obtain a
-solution by varying the option parameters.  In particular, try the
- at samp{-r} option, and also try changing the default arguments to the
- at samp{-s} and @samp{-j} options.  To @emph{guarantee} a solution, use
-the @samp{-D} and @samp{-S} options, although the final results are not
-likely to be a @emph{perfect} hash function anymore!  Finally, use the
- at samp{-f} option if you want @code{gperf} to generate the perfect hash
-function @emph{fast}, with less emphasis on making it minimal.
-
 @item 
 The size of the generate static keyword array can get @emph{extremely}
 large if the input keyword file is large or if the keywords are quite
@@ -936,19 +1272,19 @@
 code, and @emph{greatly} inflates the object code size.  If this
 situation occurs, consider using the @samp{-S} option to reduce data
 size, potentially increasing keyword recognition time a negligible
-amount.  Since many C compilers cannot correctly generated code for
+amount.  Since many C compilers cannot correctly generate code for
 large switch statements it is important to qualify the @var{-S} option
 with an appropriate numerical argument that controls the number of
 switch statements generated.
 
 @item 
-The maximum number of key positions selected for a given key has an
-arbitrary limit of 126.  This restriction should be removed, and if
+The maximum number of selected byte positions has an
+arbitrary limit of 255.  This restriction should be removed, and if
 anyone considers this a problem write me and let me know so I can remove
 the constraint.
 @end itemize
 
- at node Projects, Implementation, Bugs, Top
+ at node Projects, Bibliography, Bugs, Top
 @chapter Things Still Left to Do
 
 It should be ``relatively'' easy to replace the current perfect hash
@@ -958,18 +1294,10 @@
 
 @itemize @bullet
 @item 
-Make the algorithm more robust.  At present, the program halts with an
-error diagnostic if it can't find a direct solution and the @samp{-D}
-option is not enabled.  A more comprehensive, albeit computationally
-expensive, approach would employ backtracking or enable alternative
-options and retry.  It's not clear how helpful this would be, in
-general, since most search sets are rather small in practice.
-
- at item 
 Another useful extension involves modifying the program to generate
 ``minimal'' perfect hash functions (under certain circumstances, the
 current version can be rather extravagant in the generated table size).
-Again, this is mostly of theoretical interest, since a sparse table
+This is mostly of theoretical interest, since a sparse table
 often produces faster lookups, and use of the @samp{-S} @code{switch}
 option can minimize the data size, at the expense of slightly longer
 lookups (note that the gcc compiler generally produces good code for
@@ -977,42 +1305,30 @@
 
 @item
 In addition to improving the algorithm, it would also be useful to
-generate a C++ class or Ada package as the code output, in addition to
-the current C routines.
+generate an Ada package as the code output, in addition to the current
+C and C++ routines.
 @end itemize
 
- at node Implementation, Bibliography, Projects, Top
- at chapter Implementation Details of GNU @code{gperf}
-
-A paper describing the high-level description of the data structures and
-algorithms used to implement @code{gperf} will soon be available.  This
-paper is useful not only from a maintenance and enhancement perspective,
-but also because they demonstrate several clever and useful programming
-techniques, e.g., `Iteration Number' boolean arrays, double
-hashing, a ``safe'' and efficient method for reading arbitrarily long
-input from a file, and a provably optimal algorithm for simultaneously
-determining both the minimum and maximum elements in a list.
-
 @page
 
- at node Bibliography, Concept Index, Implementation, Top
+ at node Bibliography, Concept Index, Projects, Top
 @chapter Bibliography
 
 [1] Chang, C.C.: @i{A Scheme for Constructing Ordered Minimal Perfect
 Hashing Functions} Information Sciences 39(1986), 187-195.
-       
+
 [2] Cichelli, Richard J. @i{Author's Response to ``On Cichelli's Minimal Perfect Hash
 Functions Method''} Communications of the ACM, 23, 12(December 1980), 729.
-    
+
 [3] Cichelli, Richard J. @i{Minimal Perfect Hash Functions Made Simple}
 Communications of the ACM, 23, 1(January 1980), 17-19.
-           
+
 [4] Cook, C. R. and Oldehoeft, R.R. @i{A Letter Oriented Minimal
 Perfect Hashing Function} SIGPLAN Notices, 17, 9(September 1982), 18-27.
 
 [5] Cormack, G. V. and Horspool, R. N. S. and Kaiserwerth, M.
 @i{Practical Perfect Hashing} Computer Journal, 28, 1(January 1985), 54-58.
-    
+
 [6] Jaeschke, G. @i{Reciprocal Hashing: A Method for Generating Minimal
 Perfect Hashing Functions} Communications of the ACM, 24, 12(December
 1981), 829-833.
@@ -1027,19 +1343,22 @@
 [9] Schmidt, Douglas C. @i{GPERF: A Perfect Hash Function Generator}
 Second USENIX C++ Conference Proceedings, April 1990.
 
-[10] Sebesta, R.W. and Taylor, M.A. @i{Minimal Perfect Hash Functions
+[10] Schmidt, Douglas C. @i{GPERF: A Perfect Hash Function Generator}
+C++ Report, SIGS 10 10 (November/December 1998).
+
+[11] Sebesta, R.W. and Taylor, M.A. @i{Minimal Perfect Hash Functions
 for Reserved Word Lists}  SIGPLAN Notices, 20, 12(September 1985), 47-53.
 
-[11] Sprugnoli, R. @i{Perfect Hashing Functions: A Single Probe
+[12] Sprugnoli, R. @i{Perfect Hashing Functions: A Single Probe
 Retrieving Method for Static Sets} Communications of the ACM, 20
 11(November 1977), 841-850.
 
-[12] Stallman, Richard M. @i{Using and Porting GNU CC} Free Software Foundation,
+[13] Stallman, Richard M. @i{Using and Porting GNU CC} Free Software Foundation,
 1988.
 
-[13] Stroustrup, Bjarne @i{The C++ Programming Language.} Addison-Wesley, 1986.
+[14] Stroustrup, Bjarne @i{The C++ Programming Language.} Addison-Wesley, 1986.
 
-[14] Tiemann, Michael D. @i{User's Guide to GNU C++} Free Software
+[15] Tiemann, Michael D. @i{User's Guide to GNU C++} Free Software
 Foundation, 1989.
 
 @node Concept Index,  , Bibliography, Top
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/doc/help2man
--- a/head/contrib/gperf/doc/help2man	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/contrib/gperf/doc/help2man	Tue Dec 06 20:26:16 2011 +0200
@@ -15,7 +15,7 @@
 
 # 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 
 # Written by Brendan O'Dea <bod at compusol.com.au>
 # Available from ftp://ftp.gnu.org/gnu/help2man/
@@ -27,7 +27,7 @@
 use POSIX qw(strftime setlocale LC_TIME);
 
 my $this_program = 'help2man';
-my $this_version = '1.022';
+my $this_version = '1.23';
 my $version_info = <<EOT;
 GNU $this_program $this_version
 
@@ -269,9 +269,11 @@
 s/\n*$/\n/;
 s/\n\n+/\n\n/g;
 
-# Temporarily exchange leading dots and backslashes for tokens.
+# Temporarily exchange leading dots, apostrophes and backslashes for
+# tokens.
 s/^\./\x80/mg;
-s/\\/\x81/g;
+s/^'/\x81/mg;
+s/\\/\x82/g;
 
 # Start a new paragraph (if required) for these.
 s/([^\n])\n(Report +bugs|Email +bug +reports +to|Written +by)/$1\n\n$2/g;
@@ -366,7 +368,7 @@
     {
 	$matched .= $& if %append;
 	$indent = length ($4 || "$1$3");
-	$content = ".TP\n\x82$2\n\x82$5\n";
+	$content = ".TP\n\x83$2\n\x83$5\n";
 	unless ($4)
 	{
 	    # Indent may be different on second line.
@@ -378,7 +380,7 @@
     elsif (s/^ {1,10}([+-]\S.*)\n//)
     {
 	$matched .= $& if %append;
-	$content = ".HP\n\x82$1\n";
+	$content = ".HP\n\x83$1\n";
 	$indent = 80; # not continued
     }
 
@@ -387,7 +389,7 @@
     {
 	$matched .= $& if %append;
 	$indent = length $1;
-	$content = ".TP\n\x82$2\n\x82$3\n";
+	$content = ".TP\n\x83$2\n\x83$3\n";
     }
 
     # Indented paragraph.
@@ -395,7 +397,7 @@
     {
 	$matched .= $& if %append;
 	$indent = length $1;
-	$content = ".IP\n\x82$2\n";
+	$content = ".IP\n\x83$2\n";
     }
 
     # Left justified paragraph.
@@ -411,7 +413,7 @@
     while (s/^ {$indent}(\S.*)\n//)
     {
 	$matched .= $& if %append;
-	$content .= "\x82$1\n"
+	$content .= "\x83$1\n"
     }
 
     # Move to next paragraph.
@@ -419,9 +421,10 @@
 
     for ($content)
     {
-	# Leading dot protection.
-	s/\x82\./\x80/g;
-	s/\x82//g;
+	# Leading dot and apostrophe protection.
+	s/\x83\./\x80/g;
+	s/\x83'/\x81/g;
+	s/\x83//g;
 
 	# Convert options.
 	s/(^| )(-[][\w=-]+)/$1 . convert_option $2/mge;
@@ -482,12 +485,13 @@
     {
 	my $quote = /\W/ ? '"' : '';
 	print ".SH $quote$_$quote\n";
-
+	
 	for ($include{$_})
 	{
-	    # Replace leading dot an backslash tokens.
+	    # Replace leading dot, apostrophe and backslash tokens.
 	    s/\x80/\\&./g;
-	    s/\x81/\\e/g;
+	    s/\x81/\\&'/g;
+	    s/\x82/\\e/g;
 	    print;
 	}
     }
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/doc/texinfo.tex
--- a/head/contrib/gperf/doc/texinfo.tex	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,5999 +0,0 @@
-% texinfo.tex -- TeX macros to handle Texinfo files.
-%
-% Load plain if necessary, i.e., if running under initex.
-\expandafter\ifx\csname fmtname\endcsname\relax\input plain\fi
-%
-\def\texinfoversion{2000-05-28.15}
-%
-% Copyright (C) 1985, 86, 88, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99
-% Free Software Foundation, Inc.
-%
-% This texinfo.tex file 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.
-%
-% This texinfo.tex file 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 texinfo.tex file; see the file COPYING.  If not, write
-% to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-% Boston, MA 02111-1307, USA.
-%
-% In other words, you are welcome to use, share and improve this program.
-% You are forbidden to forbid anyone else to use, share and improve
-% what you give them.   Help stamp out software-hoarding!
-%
-% Please try the latest version of texinfo.tex before submitting bug
-% reports; you can get the latest version from:
-%   ftp://ftp.gnu.org/gnu/texinfo.tex
-%   (and all GNU mirrors, see http://www.gnu.org/order/ftp.html)
-%   ftp://texinfo.org/tex/texinfo.tex
-%   ftp://us.ctan.org/macros/texinfo/texinfo.tex
-%   (and all CTAN mirrors, finger ctan at us.ctan.org for a list).
-%   /home/gd/gnu/doc/texinfo.tex on the GNU machines.
-% The texinfo.tex in any given Texinfo distribution could well be out
-% of date, so if that's what you're using, please check.
-% Texinfo has a small home page at http://texinfo.org/.
-%
-% Send bug reports to bug-texinfo at gnu.org.  Please include including a
-% complete document in each bug report with which we can reproduce the
-% problem.  Patches are, of course, greatly appreciated.
-%
-% To process a Texinfo manual with TeX, it's most reliable to use the
-% texi2dvi shell script that comes with the distribution.  For a simple
-% manual foo.texi, however, you can get away with this:
-%   tex foo.texi
-%   texindex foo.??
-%   tex foo.texi
-%   tex foo.texi
-%   dvips foo.dvi -o # or whatever, to process the dvi file; this makes foo.ps.
-% The extra runs of TeX get the cross-reference information correct.
-% Sometimes one run after texindex suffices, and sometimes you need more
-% than two; texi2dvi does it as many times as necessary.
-%
-% It is possible to adapt texinfo.tex for other languages.  You can get
-% the existing language-specific files from ftp://ftp.gnu.org/gnu/texinfo/.
-
-\message{Loading texinfo [version \texinfoversion]:}
-
-% If in a .fmt file, print the version number
-% and turn on active characters that we couldn't do earlier because
-% they might have appeared in the input file name.
-\everyjob{\message{[Texinfo version \texinfoversion]}%
-  \catcode`+=\active \catcode`\_=\active}
-
-% Save some parts of plain tex whose names we will redefine.
-\let\ptexb=\b
-\let\ptexbullet=\bullet
-\let\ptexc=\c
-\let\ptexcomma=\,
-\let\ptexdot=\.
-\let\ptexdots=\dots
-\let\ptexend=\end
-\let\ptexequiv=\equiv
-\let\ptexexclam=\!
-\let\ptexi=\i
-\let\ptexlbrace=\{
-\let\ptexrbrace=\}
-\let\ptexstar=\*
-\let\ptext=\t
-
-% We never want plain's outer \+ definition in Texinfo.
-% For @tex, we can use \tabalign.
-\let\+ = \relax
-
-\message{Basics,}
-\chardef\other=12
-
-% If this character appears in an error message or help string, it
-% starts a new line in the output.
-\newlinechar = `^^J
-
-% Set up fixed words for English if not already set.
-\ifx\putwordAppendix\undefined  \gdef\putwordAppendix{Appendix}\fi
-\ifx\putwordChapter\undefined   \gdef\putwordChapter{Chapter}\fi
-\ifx\putwordfile\undefined      \gdef\putwordfile{file}\fi
-\ifx\putwordin\undefined        \gdef\putwordin{in}\fi
-\ifx\putwordIndexIsEmpty\undefined     \gdef\putwordIndexIsEmpty{(Index is empty)}\fi
-\ifx\putwordIndexNonexistent\undefined \gdef\putwordIndexNonexistent{(Index is nonexistent)}\fi
-\ifx\putwordInfo\undefined      \gdef\putwordInfo{Info}\fi
-\ifx\putwordInstanceVariableof\undefined \gdef\putwordInstanceVariableof{Instance Variable of}\fi
-\ifx\putwordMethodon\undefined  \gdef\putwordMethodon{Method on}\fi
-\ifx\putwordNoTitle\undefined   \gdef\putwordNoTitle{No Title}\fi
-\ifx\putwordof\undefined        \gdef\putwordof{of}\fi
-\ifx\putwordon\undefined        \gdef\putwordon{on}\fi
-\ifx\putwordpage\undefined      \gdef\putwordpage{page}\fi
-\ifx\putwordsection\undefined   \gdef\putwordsection{section}\fi
-\ifx\putwordSection\undefined   \gdef\putwordSection{Section}\fi
-\ifx\putwordsee\undefined       \gdef\putwordsee{see}\fi
-\ifx\putwordSee\undefined       \gdef\putwordSee{See}\fi
-\ifx\putwordShortTOC\undefined  \gdef\putwordShortTOC{Short Contents}\fi
-\ifx\putwordTOC\undefined       \gdef\putwordTOC{Table of Contents}\fi
-%
-\ifx\putwordMJan\undefined \gdef\putwordMJan{January}\fi
-\ifx\putwordMFeb\undefined \gdef\putwordMFeb{February}\fi
-\ifx\putwordMMar\undefined \gdef\putwordMMar{March}\fi
-\ifx\putwordMApr\undefined \gdef\putwordMApr{April}\fi
-\ifx\putwordMMay\undefined \gdef\putwordMMay{May}\fi
-\ifx\putwordMJun\undefined \gdef\putwordMJun{June}\fi
-\ifx\putwordMJul\undefined \gdef\putwordMJul{July}\fi
-\ifx\putwordMAug\undefined \gdef\putwordMAug{August}\fi
-\ifx\putwordMSep\undefined \gdef\putwordMSep{September}\fi
-\ifx\putwordMOct\undefined \gdef\putwordMOct{October}\fi
-\ifx\putwordMNov\undefined \gdef\putwordMNov{November}\fi
-\ifx\putwordMDec\undefined \gdef\putwordMDec{December}\fi
-%
-\ifx\putwordDefmac\undefined    \gdef\putwordDefmac{Macro}\fi
-\ifx\putwordDefspec\undefined   \gdef\putwordDefspec{Special Form}\fi
-\ifx\putwordDefvar\undefined    \gdef\putwordDefvar{Variable}\fi
-\ifx\putwordDefopt\undefined    \gdef\putwordDefopt{User Option}\fi
-\ifx\putwordDeftypevar\undefined\gdef\putwordDeftypevar{Variable}\fi
-\ifx\putwordDeffunc\undefined   \gdef\putwordDeffunc{Function}\fi
-\ifx\putwordDeftypefun\undefined\gdef\putwordDeftypefun{Function}\fi
-
-% Ignore a token.
-%
-\def\gobble#1{}
-
-\hyphenation{ap-pen-dix}
-\hyphenation{mini-buf-fer mini-buf-fers}
-\hyphenation{eshell}
-\hyphenation{white-space}
-
-% Margin to add to right of even pages, to left of odd pages.
-\newdimen \bindingoffset
-\newdimen \normaloffset
-\newdimen\pagewidth \newdimen\pageheight
-
-% Sometimes it is convenient to have everything in the transcript file
-% and nothing on the terminal.  We don't just call \tracingall here,
-% since that produces some useless output on the terminal.
-%
-\def\gloggingall{\begingroup \globaldefs = 1 \loggingall \endgroup}%
-\ifx\eTeXversion\undefined
-\def\loggingall{\tracingcommands2 \tracingstats2
-   \tracingpages1 \tracingoutput1 \tracinglostchars1
-   \tracingmacros2 \tracingparagraphs1 \tracingrestores1
-   \showboxbreadth\maxdimen\showboxdepth\maxdimen
-}%
-\else
-\def\loggingall{\tracingcommands3 \tracingstats2
-   \tracingpages1 \tracingoutput1 \tracinglostchars1
-   \tracingmacros2 \tracingparagraphs1 \tracingrestores1
-   \tracingscantokens1 \tracingassigns1 \tracingifs1
-   \tracinggroups1 \tracingnesting2
-   \showboxbreadth\maxdimen\showboxdepth\maxdimen
-}%
-\fi
-
-% For @cropmarks command.
-% Do @cropmarks to get crop marks.
-%
-\newif\ifcropmarks
-\let\cropmarks = \cropmarkstrue
-%
-% Dimensions to add cropmarks at corners.
-% Added by P. A. MacKay, 12 Nov. 1986
-%
-\newdimen\outerhsize \newdimen\outervsize % set by the paper size routines
-\newdimen\cornerlong  \cornerlong=1pc
-\newdimen\cornerthick \cornerthick=.3pt
-\newdimen\topandbottommargin \topandbottommargin=.75in
-
-% Main output routine.
-\chardef\PAGE = 255
-\output = {\onepageout{\pagecontents\PAGE}}
-
-\newbox\headlinebox
-\newbox\footlinebox
-
-% \onepageout takes a vbox as an argument.  Note that \pagecontents
-% does insertions, but you have to call it yourself.
-\def\onepageout#1{%
-  \ifcropmarks \hoffset=0pt \else \hoffset=\normaloffset \fi
-  %
-  \ifodd\pageno  \advance\hoffset by \bindingoffset
-  \else \advance\hoffset by -\bindingoffset\fi
-  %
-  % Do this outside of the \shipout so @code etc. will be expanded in
-  % the headline as they should be, not taken literally (outputting ''code).
-  \setbox\headlinebox = \vbox{\let\hsize=\pagewidth \makeheadline}%
-  \setbox\footlinebox = \vbox{\let\hsize=\pagewidth \makefootline}%
-  %
-  {%
-    % Have to do this stuff outside the \shipout because we want it to
-    % take effect in \write's, yet the group defined by the \vbox ends
-    % before the \shipout runs.
-    %
-    \escapechar = `\\     % use backslash in output files.
-    \indexdummies         % don't expand commands in the output.
-    \normalturnoffactive  % \ in index entries must not stay \, e.g., if
-                   % the page break happens to be in the middle of an example.
-    \shipout\vbox{%
-      % Do this early so pdf references go to the beginning of the page.
-      \ifpdfmakepagedest \pdfmkdest{\the\pageno} \fi
-      %
-      \ifcropmarks \vbox to \outervsize\bgroup
-        \hsize = \outerhsize
-        \vskip-\topandbottommargin
-        \vtop to0pt{%
-          \line{\ewtop\hfil\ewtop}%
-          \nointerlineskip
-          \line{%
-            \vbox{\moveleft\cornerthick\nstop}%
-            \hfill
-            \vbox{\moveright\cornerthick\nstop}%
-          }%
-          \vss}%
-        \vskip\topandbottommargin
-        \line\bgroup
-          \hfil % center the page within the outer (page) hsize.
-          \ifodd\pageno\hskip\bindingoffset\fi
-          \vbox\bgroup
-      \fi
-      %
-      \unvbox\headlinebox
-      \pagebody{#1}%
-      \ifdim\ht\footlinebox > 0pt
-        % Only leave this space if the footline is nonempty.
-        % (We lessened \vsize for it in \oddfootingxxx.)
-        % The \baselineskip=24pt in plain's \makefootline has no effect.
-        \vskip 2\baselineskip
-        \unvbox\footlinebox
-      \fi
-      %
-      \ifcropmarks
-          \egroup % end of \vbox\bgroup
-        \hfil\egroup % end of (centering) \line\bgroup
-        \vskip\topandbottommargin plus1fill minus1fill
-        \boxmaxdepth = \cornerthick
-        \vbox to0pt{\vss
-          \line{%
-            \vbox{\moveleft\cornerthick\nsbot}%
-            \hfill
-            \vbox{\moveright\cornerthick\nsbot}%
-          }%
-          \nointerlineskip
-          \line{\ewbot\hfil\ewbot}%
-        }%
-      \egroup % \vbox from first cropmarks clause
-      \fi
-    }% end of \shipout\vbox
-  }% end of group with \turnoffactive
-  \advancepageno
-  \ifnum\outputpenalty>-20000 \else\dosupereject\fi
-}
-
-\newinsert\margin \dimen\margin=\maxdimen
-
-\def\pagebody#1{\vbox to\pageheight{\boxmaxdepth=\maxdepth #1}}
-{\catcode`\@ =11
-\gdef\pagecontents#1{\ifvoid\topins\else\unvbox\topins\fi
-% marginal hacks, juha at viisa.uucp (Juha Takala)
-\ifvoid\margin\else % marginal info is present
-  \rlap{\kern\hsize\vbox to\z@{\kern1pt\box\margin \vss}}\fi
-\dimen@=\dp#1 \unvbox#1
-\ifvoid\footins\else\vskip\skip\footins\footnoterule \unvbox\footins\fi
-\ifr at ggedbottom \kern-\dimen@ \vfil \fi}
-}
-
-% Here are the rules for the cropmarks.  Note that they are
-% offset so that the space between them is truly \outerhsize or \outervsize
-% (P. A. MacKay, 12 November, 1986)
-%
-\def\ewtop{\vrule height\cornerthick depth0pt width\cornerlong}
-\def\nstop{\vbox
-  {\hrule height\cornerthick depth\cornerlong width\cornerthick}}
-\def\ewbot{\vrule height0pt depth\cornerthick width\cornerlong}
-\def\nsbot{\vbox
-  {\hrule height\cornerlong depth\cornerthick width\cornerthick}}
-
-% Parse an argument, then pass it to #1.  The argument is the rest of
-% the input line (except we remove a trailing comment).  #1 should be a
-% macro which expects an ordinary undelimited TeX argument.
-%
-\def\parsearg#1{%
-  \let\next = #1%
-  \begingroup
-    \obeylines
-    \futurelet\temp\parseargx
-}
-
-% If the next token is an obeyed space (from an @example environment or
-% the like), remove it and recurse.  Otherwise, we're done.
-\def\parseargx{%
-  % \obeyedspace is defined far below, after the definition of \sepspaces.
-  \ifx\obeyedspace\temp
-    \expandafter\parseargdiscardspace
-  \else
-    \expandafter\parseargline
-  \fi
-}
-
-% Remove a single space (as the delimiter token to the macro call).
-{\obeyspaces %
- \gdef\parseargdiscardspace {\futurelet\temp\parseargx}}
-
-{\obeylines %
-  \gdef\parseargline#1^^M{%
-    \endgroup % End of the group started in \parsearg.
-    %
-    % First remove any @c comment, then any @comment.
-    % Result of each macro is put in \toks0.
-    \argremovec #1\c\relax %
-    \expandafter\argremovecomment \the\toks0 \comment\relax %
-    %
-    % Call the caller's macro, saved as \next in \parsearg.
-    \expandafter\next\expandafter{\the\toks0}%
-  }%
-}
-
-% Since all \c{,omment} does is throw away the argument, we can let TeX
-% do that for us.  The \relax here is matched by the \relax in the call
-% in \parseargline; it could be more or less anything, its purpose is
-% just to delimit the argument to the \c.
-\def\argremovec#1\c#2\relax{\toks0 = {#1}}
-\def\argremovecomment#1\comment#2\relax{\toks0 = {#1}}
-
-% \argremovec{,omment} might leave us with trailing spaces, though; e.g.,
-%    @end itemize  @c foo
-% will have two active spaces as part of the argument with the
-% `itemize'.  Here we remove all active spaces from #1, and assign the
-% result to \toks0.
-%
-% This loses if there are any *other* active characters besides spaces
-% in the argument -- _ ^ +, for example -- since they get expanded.
-% Fortunately, Texinfo does not define any such commands.  (If it ever
-% does, the catcode of the characters in questionwill have to be changed
-% here.)  But this means we cannot call \removeactivespaces as part of
-% \argremovec{,omment}, since @c uses \parsearg, and thus the argument
-% that \parsearg gets might well have any character at all in it.
-%
-\def\removeactivespaces#1{%
-  \begingroup
-    \ignoreactivespaces
-    \edef\temp{#1}%
-    \global\toks0 = \expandafter{\temp}%
-  \endgroup
-}
-
-% Change the active space to expand to nothing.
-%
-\begingroup
-  \obeyspaces
-  \gdef\ignoreactivespaces{\obeyspaces\let =\empty}
-\endgroup
-
-
-\def\flushcr{\ifx\par\lisppar \def\next##1{}\else \let\next=\relax \fi \next}
-
-%% These are used to keep @begin/@end levels from running away
-%% Call \inENV within environments (after a \begingroup)
-\newif\ifENV \ENVfalse \def\inENV{\ifENV\relax\else\ENVtrue\fi}
-\def\ENVcheck{%
-\ifENV\errmessage{Still within an environment; press RETURN to continue}
-\endgroup\fi} % This is not perfect, but it should reduce lossage
-
-% @begin foo  is the same as @foo, for now.
-\newhelp\EMsimple{Press RETURN to continue.}
-
-\outer\def\begin{\parsearg\beginxxx}
-
-\def\beginxxx #1{%
-\expandafter\ifx\csname #1\endcsname\relax
-{\errhelp=\EMsimple \errmessage{Undefined command @begin #1}}\else
-\csname #1\endcsname\fi}
-
-% @end foo executes the definition of \Efoo.
-%
-\def\end{\parsearg\endxxx}
-\def\endxxx #1{%
-  \removeactivespaces{#1}%
-  \edef\endthing{\the\toks0}%
-  %
-  \expandafter\ifx\csname E\endthing\endcsname\relax
-    \expandafter\ifx\csname \endthing\endcsname\relax
-      % There's no \foo, i.e., no ``environment'' foo.
-      \errhelp = \EMsimple
-      \errmessage{Undefined command `@end \endthing'}%
-    \else
-      \unmatchedenderror\endthing
-    \fi
-  \else
-    % Everything's ok; the right environment has been started.
-    \csname E\endthing\endcsname
-  \fi
-}
-
-% There is an environment #1, but it hasn't been started.  Give an error.
-%
-\def\unmatchedenderror#1{%
-  \errhelp = \EMsimple
-  \errmessage{This `@end #1' doesn't have a matching `@#1'}%
-}
-
-% Define the control sequence \E#1 to give an unmatched @end error.
-%
-\def\defineunmatchedend#1{%
-  \expandafter\def\csname E#1\endcsname{\unmatchedenderror{#1}}%
-}
-
-
-% Single-spacing is done by various environments (specifically, in
-% \nonfillstart and \quotations).
-\newskip\singlespaceskip \singlespaceskip = 12.5pt
-\def\singlespace{%
-  % Why was this kern here?  It messes up equalizing space above and below
-  % environments.  --karl, 6may93
-  %{\advance \baselineskip by -\singlespaceskip
-  %\kern \baselineskip}%
-  \setleading \singlespaceskip
-}
-
-%% Simple single-character @ commands
-
-% @@ prints an @
-% Kludge this until the fonts are right (grr).
-\def\@{{\tt\char64}}
-
-% This is turned off because it was never documented
-% and you can use @w{...} around a quote to suppress ligatures.
-%% Define @` and @' to be the same as ` and '
-%% but suppressing ligatures.
-%\def\`{{`}}
-%\def\'{{'}}
-
-% Used to generate quoted braces.
-\def\mylbrace {{\tt\char123}}
-\def\myrbrace {{\tt\char125}}
-\let\{=\mylbrace
-\let\}=\myrbrace
-\begingroup
-  % Definitions to produce actual \{ & \} command in an index.
-  \catcode`\{ = 12 \catcode`\} = 12
-  \catcode`\[ = 1 \catcode`\] = 2
-  \catcode`\@ = 0 \catcode`\\ = 12
-  @gdef at lbracecmd[\{]%
-  @gdef at rbracecmd[\}]%
- at endgroup
-
-% Accents: @, @dotaccent @ringaccent @ubaraccent @udotaccent
-% Others are defined by plain TeX: @` @' @" @^ @~ @= @v @H.
-\let\, = \c
-\let\dotaccent = \.
-\def\ringaccent#1{{\accent23 #1}}
-\let\tieaccent = \t
-\let\ubaraccent = \b
-\let\udotaccent = \d
-
-% Other special characters: @questiondown @exclamdown
-% Plain TeX defines: @AA @AE @O @OE @L (and lowercase versions) @ss.
-\def\questiondown{?`}
-\def\exclamdown{!`}
-
-% Dotless i and dotless j, used for accents.
-\def\imacro{i}
-\def\jmacro{j}
-\def\dotless#1{%
-  \def\temp{#1}%
-  \ifx\temp\imacro \ptexi
-  \else\ifx\temp\jmacro \j
-  \else \errmessage{@dotless can be used only with i or j}%
-  \fi\fi
-}
-
-% Be sure we're in horizontal mode when doing a tie, since we make space
-% equivalent to this in @example-like environments. Otherwise, a space
-% at the beginning of a line will start with \penalty -- and
-% since \penalty is valid in vertical mode, we'd end up putting the
-% penalty on the vertical list instead of in the new paragraph.
-{\catcode`@ = 11
- % Avoid using \@M directly, because that causes trouble
- % if the definition is written into an index file.
- \global\let\tiepenalty = \@M
- \gdef\tie{\leavevmode\penalty\tiepenalty\ }
-}
-
-% @: forces normal size whitespace following.
-\def\:{\spacefactor=1000 }
-
-% @* forces a line break.
-\def\*{\hfil\break\hbox{}\ignorespaces}
-
-% @. is an end-of-sentence period.
-\def\.{.\spacefactor=3000 }
-
-% @! is an end-of-sentence bang.
-\def\!{!\spacefactor=3000 }
-
-% @? is an end-of-sentence query.
-\def\?{?\spacefactor=3000 }
-
-% @w prevents a word break.  Without the \leavevmode, @w at the
-% beginning of a paragraph, when TeX is still in vertical mode, would
-% produce a whole line of output instead of starting the paragraph.
-\def\w#1{\leavevmode\hbox{#1}}
-
-% @group ... @end group forces ... to be all on one page, by enclosing
-% it in a TeX vbox.  We use \vtop instead of \vbox to construct the box
-% to keep its height that of a normal line.  According to the rules for
-% \topskip (p.114 of the TeXbook), the glue inserted is
-% max (\topskip - \ht (first item), 0).  If that height is large,
-% therefore, no glue is inserted, and the space between the headline and
-% the text is small, which looks bad.
-%
-\def\group{\begingroup
-  \ifnum\catcode13=\active \else
-    \errhelp = \groupinvalidhelp
-    \errmessage{@group invalid in context where filling is enabled}%
-  \fi
-  %
-  % The \vtop we start below produces a box with normal height and large
-  % depth; thus, TeX puts \baselineskip glue before it, and (when the
-  % next line of text is done) \lineskip glue after it.  (See p.82 of
-  % the TeXbook.)  Thus, space below is not quite equal to space
-  % above.  But it's pretty close.
-  \def\Egroup{%
-    \egroup           % End the \vtop.
-    \endgroup         % End the \group.
-  }%
-  %
-  \vtop\bgroup
-    % We have to put a strut on the last line in case the @group is in
-    % the midst of an example, rather than completely enclosing it.
-    % Otherwise, the interline space between the last line of the group
-    % and the first line afterwards is too small.  But we can't put the
-    % strut in \Egroup, since there it would be on a line by itself.
-    % Hence this just inserts a strut at the beginning of each line.
-    \everypar = {\strut}%
-    %
-    % Since we have a strut on every line, we don't need any of TeX's
-    % normal interline spacing.
-    \offinterlineskip
-    %
-    % OK, but now we have to do something about blank
-    % lines in the input in @example-like environments, which normally
-    % just turn into \lisppar, which will insert no space now that we've
-    % turned off the interline space.  Simplest is to make them be an
-    % empty paragraph.
-    \ifx\par\lisppar
-      \edef\par{\leavevmode \par}%
-      %
-      % Reset ^^M's definition to new definition of \par.
-      \obeylines
-    \fi
-    %
-    % Do @comment since we are called inside an environment such as
-    % @example, where each end-of-line in the input causes an
-    % end-of-line in the output.  We don't want the end-of-line after
-    % the `@group' to put extra space in the output.  Since @group
-    % should appear on a line by itself (according to the Texinfo
-    % manual), we don't worry about eating any user text.
-    \comment
-}
-%
-% TeX puts in an \escapechar (i.e., `@') at the beginning of the help
-% message, so this ends up printing `@group can only ...'.
-%
-\newhelp\groupinvalidhelp{%
-group can only be used in environments such as @example,^^J%
-where each line of input produces a line of output.}
-
-% @need space-in-mils
-% forces a page break if there is not space-in-mils remaining.
-
-\newdimen\mil  \mil=0.001in
-
-\def\need{\parsearg\needx}
-
-% Old definition--didn't work.
-%\def\needx #1{\par %
-%% This method tries to make TeX break the page naturally
-%% if the depth of the box does not fit.
-%{\baselineskip=0pt%
-%\vtop to #1\mil{\vfil}\kern -#1\mil\nobreak
-%\prevdepth=-1000pt
-%}}
-
-\def\needx#1{%
-  % Ensure vertical mode, so we don't make a big box in the middle of a
-  % paragraph.
-  \par
-  %
-  % If the @need value is less than one line space, it's useless.
-  \dimen0 = #1\mil
-  \dimen2 = \ht\strutbox
-  \advance\dimen2 by \dp\strutbox
-  \ifdim\dimen0 > \dimen2
-    %
-    % Do a \strut just to make the height of this box be normal, so the
-    % normal leading is inserted relative to the preceding line.
-    % And a page break here is fine.
-    \vtop to #1\mil{\strut\vfil}%
-    %
-    % TeX does not even consider page breaks if a penalty added to the
-    % main vertical list is 10000 or more.  But in order to see if the
-    % empty box we just added fits on the page, we must make it consider
-    % page breaks.  On the other hand, we don't want to actually break the
-    % page after the empty box.  So we use a penalty of 9999.
-    %
-    % There is an extremely small chance that TeX will actually break the
-    % page at this \penalty, if there are no other feasible breakpoints in
-    % sight.  (If the user is using lots of big @group commands, which
-    % almost-but-not-quite fill up a page, TeX will have a hard time doing
-    % good page breaking, for example.)  However, I could not construct an
-    % example where a page broke at this \penalty; if it happens in a real
-    % document, then we can reconsider our strategy.
-    \penalty9999
-    %
-    % Back up by the size of the box, whether we did a page break or not.
-    \kern -#1\mil
-    %
-    % Do not allow a page break right after this kern.
-    \nobreak
-  \fi
-}
-
-% @br   forces paragraph break
-
-\let\br = \par
-
-% @dots{} output an ellipsis using the current font.
-% We do .5em per period so that it has the same spacing in a typewriter
-% font as three actual period characters.
-%
-\def\dots{%
-  \leavevmode
-  \hbox to 1.5em{%
-    \hskip 0pt plus 0.25fil minus 0.25fil
-    .\hss.\hss.%
-    \hskip 0pt plus 0.5fil minus 0.5fil
-  }%
-}
-
-% @enddots{} is an end-of-sentence ellipsis.
-%
-\def\enddots{%
-  \leavevmode
-  \hbox to 2em{%
-    \hskip 0pt plus 0.25fil minus 0.25fil
-    .\hss.\hss.\hss.%
-    \hskip 0pt plus 0.5fil minus 0.5fil
-  }%
-  \spacefactor=3000
-}
-
-
-% @page    forces the start of a new page
-%
-\def\page{\par\vfill\supereject}
-
-% @exdent text....
-% outputs text on separate line in roman font, starting at standard page margin
-
-% This records the amount of indent in the innermost environment.
-% That's how much \exdent should take out.
-\newskip\exdentamount
-
-% This defn is used inside fill environments such as @defun.
-\def\exdent{\parsearg\exdentyyy}
-\def\exdentyyy #1{{\hfil\break\hbox{\kern -\exdentamount{\rm#1}}\hfil\break}}
-
-% This defn is used inside nofill environments such as @example.
-\def\nofillexdent{\parsearg\nofillexdentyyy}
-\def\nofillexdentyyy #1{{\advance \leftskip by -\exdentamount
-\leftline{\hskip\leftskip{\rm#1}}}}
-
-% @inmargin{TEXT} puts TEXT in the margin next to the current paragraph.
-
-\def\inmargin#1{%
-\strut\vadjust{\nobreak\kern-\strutdepth
-  \vtop to \strutdepth{\baselineskip\strutdepth\vss
-  \llap{\rightskip=\inmarginspacing \vbox{\noindent #1}}\null}}}
-\newskip\inmarginspacing \inmarginspacing=1cm
-\def\strutdepth{\dp\strutbox}
-
-%\hbox{{\rm#1}}\hfil\break}}
-
-% @include file    insert text of that file as input.
-% Allow normal characters that  we make active in the argument (a file name).
-\def\include{\begingroup
-  \catcode`\\=12
-  \catcode`~=12
-  \catcode`^=12
-  \catcode`_=12
-  \catcode`|=12
-  \catcode`<=12
-  \catcode`>=12
-  \catcode`+=12
-  \parsearg\includezzz}
-% Restore active chars for included file.
-\def\includezzz#1{\endgroup\begingroup
-  % Read the included file in a group so nested @include's work.
-  \def\thisfile{#1}%
-  \input\thisfile
-\endgroup}
-
-\def\thisfile{}
-
-% @center line   outputs that line, centered
-
-\def\center{\parsearg\centerzzz}
-\def\centerzzz #1{{\advance\hsize by -\leftskip
-\advance\hsize by -\rightskip
-\centerline{#1}}}
-
-% @sp n   outputs n lines of vertical space
-
-\def\sp{\parsearg\spxxx}
-\def\spxxx #1{\vskip #1\baselineskip}
-
-% @comment ...line which is ignored...
-% @c is the same as @comment
-% @ignore ... @end ignore  is another way to write a comment
-
-\def\comment{\begingroup \catcode`\^^M=\other%
-\catcode`\@=\other \catcode`\{=\other \catcode`\}=\other%
-\commentxxx}
-{\catcode`\^^M=\other \gdef\commentxxx#1^^M{\endgroup}}
-
-\let\c=\comment
-
-% @paragraphindent NCHARS
-% We'll use ems for NCHARS, close enough.
-% We cannot implement @paragraphindent asis, though.
-% 
-\def\asisword{asis} % no translation, these are keywords
-\def\noneword{none}
-%
-\def\paragraphindent{\parsearg\doparagraphindent}
-\def\doparagraphindent#1{%
-  \def\temp{#1}%
-  \ifx\temp\asisword
-  \else
-    \ifx\temp\noneword
-      \defaultparindent = 0pt
-    \else
-      \defaultparindent = #1em
-    \fi
-  \fi
-  \parindent = \defaultparindent
-}
-
-% @exampleindent NCHARS
-% We'll use ems for NCHARS like @paragraphindent.
-% It seems @exampleindent asis isn't necessary, but
-% I preserve it to make it similar to @paragraphindent.
-\def\exampleindent{\parsearg\doexampleindent}
-\def\doexampleindent#1{%
-  \def\temp{#1}%
-  \ifx\temp\asisword
-  \else
-    \ifx\temp\noneword
-      \lispnarrowing = 0pt
-    \else
-      \lispnarrowing = #1em
-    \fi
-  \fi
-}
-
-% @asis just yields its argument.  Used with @table, for example.
-%
-\def\asis#1{#1}
-
-% @math means output in math mode.
-% We don't use $'s directly in the definition of \math because control
-% sequences like \math are expanded when the toc file is written.  Then,
-% we read the toc file back, the $'s will be normal characters (as they
-% should be, according to the definition of Texinfo).  So we must use a
-% control sequence to switch into and out of math mode.
-%
-% This isn't quite enough for @math to work properly in indices, but it
-% seems unlikely it will ever be needed there.
-%
-\let\implicitmath = $
-\def\math#1{\implicitmath #1\implicitmath}
-
-% @bullet and @minus need the same treatment as @math, just above.
-\def\bullet{\implicitmath\ptexbullet\implicitmath}
-\def\minus{\implicitmath-\implicitmath}
-
-% @refill is a no-op.
-\let\refill=\relax
-
-% If working on a large document in chapters, it is convenient to
-% be able to disable indexing, cross-referencing, and contents, for test runs.
-% This is done with @novalidate (before @setfilename).
-%
-\newif\iflinks \linkstrue % by default we want the aux files.
-\let\novalidate = \linksfalse
-
-% @setfilename is done at the beginning of every texinfo file.
-% So open here the files we need to have open while reading the input.
-% This makes it possible to make a .fmt file for texinfo.
-\def\setfilename{%
-   \iflinks
-     \readauxfile
-   \fi % \openindices needs to do some work in any case.
-   \openindices
-   \fixbackslash  % Turn off hack to swallow `\input texinfo'.
-   \global\let\setfilename=\comment % Ignore extra @setfilename cmds.
-   %
-   % If texinfo.cnf is present on the system, read it.
-   % Useful for site-wide @afourpaper, etc.
-   % Just to be on the safe side, close the input stream before the \input.
-   \openin 1 texinfo.cnf
-   \ifeof1 \let\temp=\relax \else \def\temp{\input texinfo.cnf }\fi
-   \closein1
-   \temp
-   %
-   \comment % Ignore the actual filename.
-}
-
-% Called from \setfilename.
-%
-\def\openindices{%
-  \newindex{cp}%
-  \newcodeindex{fn}%
-  \newcodeindex{vr}%
-  \newcodeindex{tp}%
-  \newcodeindex{ky}%
-  \newcodeindex{pg}%
-}
-
-% @bye.
-\outer\def\bye{\pagealignmacro\tracingstats=1\ptexend}
-
-
-\message{pdf,}
-% adobe `portable' document format
-\newcount\tempnum
-\newcount\lnkcount
-\newtoks\filename
-\newcount\filenamelength
-\newcount\pgn
-\newtoks\toksA
-\newtoks\toksB
-\newtoks\toksC
-\newtoks\toksD
-\newbox\boxA
-\newcount\countA
-\newif\ifpdf
-\newif\ifpdfmakepagedest
-
-\ifx\pdfoutput\undefined
-  \pdffalse
-  \let\pdfmkdest = \gobble
-  \let\pdfurl = \gobble
-  \let\endlink = \relax
-  \let\linkcolor = \relax
-  \let\pdfmakeoutlines = \relax
-\else
-  \pdftrue
-  \pdfoutput = 1
-  \input pdfcolor
-  \def\dopdfimage#1#2#3{%
-    \def\imagewidth{#2}%
-    \def\imageheight{#3}%
-    \ifnum\pdftexversion < 14
-      \pdfimage
-    \else
-      \pdfximage
-    \fi
-      \ifx\empty\imagewidth\else width \imagewidth \fi
-      \ifx\empty\imageheight\else height \imageheight \fi
-      {#1.pdf}%
-    \ifnum\pdftexversion < 14 \else
-      \pdfrefximage \pdflastximage
-    \fi}
-  \def\pdfmkdest#1{\pdfdest name{#1@} xyz}
-  \def\pdfmkpgn#1{#1@}
-  \let\linkcolor = \Blue  % was Cyan, but that seems light?
-  \def\endlink{\Black\pdfendlink}
-  % Adding outlines to PDF; macros for calculating structure of outlines
-  % come from Petr Olsak
-  \def\expnumber#1{\expandafter\ifx\csname#1\endcsname\relax 0%
-    \else \csname#1\endcsname \fi}
-  \def\advancenumber#1{\tempnum=\expnumber{#1}\relax
-    \advance\tempnum by1
-    \expandafter\xdef\csname#1\endcsname{\the\tempnum}}
-  \def\pdfmakeoutlines{{%
-    \openin 1 \jobname.toc
-    \ifeof 1\else\bgroup
-      \closein 1 
-      \indexnofonts
-      \def\tt{}
-      \let\_ = \normalunderscore
-      % Thanh's hack / proper braces in bookmarks  
-      \edef\mylbrace{\iftrue \string{\else}\fi}\let\{=\mylbrace
-      \edef\myrbrace{\iffalse{\else\string}\fi}\let\}=\myrbrace
-      %
-      \def\chapentry ##1##2##3{}
-      \def\unnumbchapentry ##1##2{}
-      \def\secentry ##1##2##3##4{\advancenumber{chap##2}}
-      \def\unnumbsecentry ##1##2{}
-      \def\subsecentry ##1##2##3##4##5{\advancenumber{sec##2.##3}}
-      \def\unnumbsubsecentry ##1##2{}
-      \def\subsubsecentry ##1##2##3##4##5##6{\advancenumber{subsec##2.##3.##4}}
-      \def\unnumbsubsubsecentry ##1##2{}
-      \input \jobname.toc
-      \def\chapentry ##1##2##3{%
-        \pdfoutline goto name{\pdfmkpgn{##3}}count-\expnumber{chap##2}{##1}}
-      \def\unnumbchapentry ##1##2{%
-        \pdfoutline goto name{\pdfmkpgn{##2}}{##1}}
-      \def\secentry ##1##2##3##4{%
-        \pdfoutline goto name{\pdfmkpgn{##4}}count-\expnumber{sec##2.##3}{##1}}
-      \def\unnumbsecentry ##1##2{%
-        \pdfoutline goto name{\pdfmkpgn{##2}}{##1}}
-      \def\subsecentry ##1##2##3##4##5{%
-        \pdfoutline goto name{\pdfmkpgn{##5}}count-\expnumber{subsec##2.##3.##4}{##1}}
-      \def\unnumbsubsecentry ##1##2{%
-        \pdfoutline goto name{\pdfmkpgn{##2}}{##1}}
-      \def\subsubsecentry ##1##2##3##4##5##6{%
-        \pdfoutline goto name{\pdfmkpgn{##6}}{##1}}
-      \def\unnumbsubsubsecentry ##1##2{%
-        \pdfoutline goto name{\pdfmkpgn{##2}}{##1}}
-      \input \jobname.toc
-    \egroup\fi
-  }}
-  \def\makelinks #1,{%
-    \def\params{#1}\def\E{END}%
-    \ifx\params\E
-      \let\nextmakelinks=\relax
-    \else
-      \let\nextmakelinks=\makelinks
-      \ifnum\lnkcount>0,\fi
-      \picknum{#1}%
-      \startlink attr{/Border [0 0 0]} 
-        goto name{\pdfmkpgn{\the\pgn}}%
-      \linkcolor #1%
-      \advance\lnkcount by 1%
-      \endlink
-    \fi
-    \nextmakelinks
-  }
-  \def\picknum#1{\expandafter\pn#1}
-  \def\pn#1{%
-    \def\p{#1}%
-    \ifx\p\lbrace
-      \let\nextpn=\ppn
-    \else
-      \let\nextpn=\ppnn
-      \def\first{#1}
-    \fi
-    \nextpn
-  }
-  \def\ppn#1{\pgn=#1\gobble}
-  \def\ppnn{\pgn=\first}
-  \def\pdfmklnk#1{\lnkcount=0\makelinks #1,END,}
-  \def\addtokens#1#2{\edef\addtoks{\noexpand#1={\the#1#2}}\addtoks}
-  \def\skipspaces#1{\def\PP{#1}\def\D{|}%
-    \ifx\PP\D\let\nextsp\relax
-    \else\let\nextsp\skipspaces
-      \ifx\p\space\else\addtokens{\filename}{\PP}%
-        \advance\filenamelength by 1
-      \fi
-    \fi
-    \nextsp}
-  \def\getfilename#1{\filenamelength=0\expandafter\skipspaces#1|\relax}
-  \ifnum\pdftexversion < 14
-    \let \startlink \pdfannotlink
-  \else
-    \let \startlink \pdfstartlink
-  \fi
-  \def\pdfurl#1{%
-    \begingroup
-      \normalturnoffactive\def\@{@}%
-      \leavevmode\Red
-      \startlink attr{/Border [0 0 0]}%
-        user{/Subtype /Link /A << /S /URI /URI (#1) >>}%
-        % #1
-    \endgroup}
-  \def\pdfgettoks#1.{\setbox\boxA=\hbox{\toksA={#1.}\toksB={}\maketoks}}
-  \def\addtokens#1#2{\edef\addtoks{\noexpand#1={\the#1#2}}\addtoks}
-  \def\adn#1{\addtokens{\toksC}{#1}\global\countA=1\let\next=\maketoks}
-  \def\poptoks#1#2|ENDTOKS|{\let\first=#1\toksD={#1}\toksA={#2}}
-  \def\maketoks{%
-    \expandafter\poptoks\the\toksA|ENDTOKS|
-    \ifx\first0\adn0
-    \else\ifx\first1\adn1 \else\ifx\first2\adn2 \else\ifx\first3\adn3
-    \else\ifx\first4\adn4 \else\ifx\first5\adn5 \else\ifx\first6\adn6
-    \else\ifx\first7\adn7 \else\ifx\first8\adn8 \else\ifx\first9\adn9 
-    \else
-      \ifnum0=\countA\else\makelink\fi
-      \ifx\first.\let\next=\done\else
-        \let\next=\maketoks
-        \addtokens{\toksB}{\the\toksD}
-        \ifx\first,\addtokens{\toksB}{\space}\fi
-      \fi
-    \fi\fi\fi\fi\fi\fi\fi\fi\fi\fi
-    \next}
-  \def\makelink{\addtokens{\toksB}%
-    {\noexpand\pdflink{\the\toksC}}\toksC={}\global\countA=0}
-  \def\pdflink#1{%
-    \startlink attr{/Border [0 0 0]} goto name{\mkpgn{#1}}
-    \linkcolor #1\endlink}
-  \def\mkpgn#1{#1@} 
-  \def\done{\edef\st{\global\noexpand\toksA={\the\toksB}}\st}
-\fi % \ifx\pdfoutput
-
-
-\message{fonts,}
-% Font-change commands.
-
-% Texinfo sort of supports the sans serif font style, which plain TeX does not.
-% So we set up a \sf analogous to plain's \rm, etc.
-\newfam\sffam
-\def\sf{\fam=\sffam \tensf}
-\let\li = \sf % Sometimes we call it \li, not \sf.
-
-% We don't need math for this one.
-\def\ttsl{\tenttsl}
-
-% Use Computer Modern fonts at \magstephalf (11pt).
-\newcount\mainmagstep
-\mainmagstep=\magstephalf
-
-% Set the font macro #1 to the font named #2, adding on the
-% specified font prefix (normally `cm').
-% #3 is the font's design size, #4 is a scale factor
-\def\setfont#1#2#3#4{\font#1=\fontprefix#2#3 scaled #4}
-
-% Use cm as the default font prefix.
-% To specify the font prefix, you must define \fontprefix
-% before you read in texinfo.tex.
-\ifx\fontprefix\undefined
-\def\fontprefix{cm}
-\fi
-% Support font families that don't use the same naming scheme as CM.
-\def\rmshape{r}
-\def\rmbshape{bx}               %where the normal face is bold
-\def\bfshape{b}
-\def\bxshape{bx}
-\def\ttshape{tt}
-\def\ttbshape{tt}
-\def\ttslshape{sltt}
-\def\itshape{ti}
-\def\itbshape{bxti}
-\def\slshape{sl}
-\def\slbshape{bxsl}
-\def\sfshape{ss}
-\def\sfbshape{ss}
-\def\scshape{csc}
-\def\scbshape{csc}
-
-\ifx\bigger\relax
-\let\mainmagstep=\magstep1
-\setfont\textrm\rmshape{12}{1000}
-\setfont\texttt\ttshape{12}{1000}
-\else
-\setfont\textrm\rmshape{10}{\mainmagstep}
-\setfont\texttt\ttshape{10}{\mainmagstep}
-\fi
-% Instead of cmb10, you many want to use cmbx10.
-% cmbx10 is a prettier font on its own, but cmb10
-% looks better when embedded in a line with cmr10.
-\setfont\textbf\bfshape{10}{\mainmagstep}
-\setfont\textit\itshape{10}{\mainmagstep}
-\setfont\textsl\slshape{10}{\mainmagstep}
-\setfont\textsf\sfshape{10}{\mainmagstep}
-\setfont\textsc\scshape{10}{\mainmagstep}
-\setfont\textttsl\ttslshape{10}{\mainmagstep}
-\font\texti=cmmi10 scaled \mainmagstep
-\font\textsy=cmsy10 scaled \mainmagstep
-
-% A few fonts for @defun, etc.
-\setfont\defbf\bxshape{10}{\magstep1} %was 1314
-\setfont\deftt\ttshape{10}{\magstep1}
-\def\df{\let\tentt=\deftt \let\tenbf = \defbf \bf}
-
-% Fonts for indices, footnotes, small examples (9pt).
-\setfont\smallrm\rmshape{9}{1000}
-\setfont\smalltt\ttshape{9}{1000}
-\setfont\smallbf\bfshape{10}{900}
-\setfont\smallit\itshape{9}{1000}
-\setfont\smallsl\slshape{9}{1000}
-\setfont\smallsf\sfshape{9}{1000}
-\setfont\smallsc\scshape{10}{900}
-\setfont\smallttsl\ttslshape{10}{900}
-\font\smalli=cmmi9
-\font\smallsy=cmsy9
-
-% Fonts for title page:
-\setfont\titlerm\rmbshape{12}{\magstep3}
-\setfont\titleit\itbshape{10}{\magstep4}
-\setfont\titlesl\slbshape{10}{\magstep4}
-\setfont\titlett\ttbshape{12}{\magstep3}
-\setfont\titlettsl\ttslshape{10}{\magstep4}
-\setfont\titlesf\sfbshape{17}{\magstep1}
-\let\titlebf=\titlerm
-\setfont\titlesc\scbshape{10}{\magstep4}
-\font\titlei=cmmi12 scaled \magstep3
-\font\titlesy=cmsy10 scaled \magstep4
-\def\authorrm{\secrm}
-
-% Chapter (and unnumbered) fonts (17.28pt).
-\setfont\chaprm\rmbshape{12}{\magstep2}
-\setfont\chapit\itbshape{10}{\magstep3}
-\setfont\chapsl\slbshape{10}{\magstep3}
-\setfont\chaptt\ttbshape{12}{\magstep2}
-\setfont\chapttsl\ttslshape{10}{\magstep3}
-\setfont\chapsf\sfbshape{17}{1000}
-\let\chapbf=\chaprm
-\setfont\chapsc\scbshape{10}{\magstep3}
-\font\chapi=cmmi12 scaled \magstep2
-\font\chapsy=cmsy10 scaled \magstep3
-
-% Section fonts (14.4pt).
-\setfont\secrm\rmbshape{12}{\magstep1}
-\setfont\secit\itbshape{10}{\magstep2}
-\setfont\secsl\slbshape{10}{\magstep2}
-\setfont\sectt\ttbshape{12}{\magstep1}
-\setfont\secttsl\ttslshape{10}{\magstep2}
-\setfont\secsf\sfbshape{12}{\magstep1}
-\let\secbf\secrm
-\setfont\secsc\scbshape{10}{\magstep2}
-\font\seci=cmmi12 scaled \magstep1
-\font\secsy=cmsy10 scaled \magstep2
-
-% \setfont\ssecrm\bxshape{10}{\magstep1}    % This size an font looked bad.
-% \setfont\ssecit\itshape{10}{\magstep1}    % The letters were too crowded.
-% \setfont\ssecsl\slshape{10}{\magstep1}
-% \setfont\ssectt\ttshape{10}{\magstep1}
-% \setfont\ssecsf\sfshape{10}{\magstep1}
-
-%\setfont\ssecrm\bfshape{10}{1315}      % Note the use of cmb rather than cmbx.
-%\setfont\ssecit\itshape{10}{1315}      % Also, the size is a little larger than
-%\setfont\ssecsl\slshape{10}{1315}      % being scaled magstep1.
-%\setfont\ssectt\ttshape{10}{1315}
-%\setfont\ssecsf\sfshape{10}{1315}
-
-%\let\ssecbf=\ssecrm
-
-% Subsection fonts (13.15pt).
-\setfont\ssecrm\rmbshape{12}{\magstephalf}
-\setfont\ssecit\itbshape{10}{1315}
-\setfont\ssecsl\slbshape{10}{1315}
-\setfont\ssectt\ttbshape{12}{\magstephalf}
-\setfont\ssecttsl\ttslshape{10}{1315}
-\setfont\ssecsf\sfbshape{12}{\magstephalf}
-\let\ssecbf\ssecrm
-\setfont\ssecsc\scbshape{10}{\magstep1}
-\font\sseci=cmmi12 scaled \magstephalf
-\font\ssecsy=cmsy10 scaled 1315
-% The smallcaps and symbol fonts should actually be scaled \magstep1.5,
-% but that is not a standard magnification.
-
-% In order for the font changes to affect most math symbols and letters,
-% we have to define the \textfont of the standard families.  Since
-% texinfo doesn't allow for producing subscripts and superscripts, we
-% don't bother to reset \scriptfont and \scriptscriptfont (which would
-% also require loading a lot more fonts).
-%
-\def\resetmathfonts{%
-  \textfont0 = \tenrm \textfont1 = \teni \textfont2 = \tensy
-  \textfont\itfam = \tenit \textfont\slfam = \tensl \textfont\bffam = \tenbf
-  \textfont\ttfam = \tentt \textfont\sffam = \tensf
-}
-
-
-% The font-changing commands redefine the meanings of \tenSTYLE, instead
-% of just \STYLE.  We do this so that font changes will continue to work
-% in math mode, where it is the current \fam that is relevant in most
-% cases, not the current font.  Plain TeX does \def\bf{\fam=\bffam
-% \tenbf}, for example.  By redefining \tenbf, we obviate the need to
-% redefine \bf itself.
-\def\textfonts{%
-  \let\tenrm=\textrm \let\tenit=\textit \let\tensl=\textsl
-  \let\tenbf=\textbf \let\tentt=\texttt \let\smallcaps=\textsc
-  \let\tensf=\textsf \let\teni=\texti \let\tensy=\textsy \let\tenttsl=\textttsl
-  \resetmathfonts}
-\def\titlefonts{%
-  \let\tenrm=\titlerm \let\tenit=\titleit \let\tensl=\titlesl
-  \let\tenbf=\titlebf \let\tentt=\titlett \let\smallcaps=\titlesc
-  \let\tensf=\titlesf \let\teni=\titlei \let\tensy=\titlesy
-  \let\tenttsl=\titlettsl
-  \resetmathfonts \setleading{25pt}}
-\def\titlefont#1{{\titlefonts\rm #1}}
-\def\chapfonts{%
-  \let\tenrm=\chaprm \let\tenit=\chapit \let\tensl=\chapsl
-  \let\tenbf=\chapbf \let\tentt=\chaptt \let\smallcaps=\chapsc
-  \let\tensf=\chapsf \let\teni=\chapi \let\tensy=\chapsy \let\tenttsl=\chapttsl
-  \resetmathfonts \setleading{19pt}}
-\def\secfonts{%
-  \let\tenrm=\secrm \let\tenit=\secit \let\tensl=\secsl
-  \let\tenbf=\secbf \let\tentt=\sectt \let\smallcaps=\secsc
-  \let\tensf=\secsf \let\teni=\seci \let\tensy=\secsy \let\tenttsl=\secttsl
-  \resetmathfonts \setleading{16pt}}
-\def\subsecfonts{%
-  \let\tenrm=\ssecrm \let\tenit=\ssecit \let\tensl=\ssecsl
-  \let\tenbf=\ssecbf \let\tentt=\ssectt \let\smallcaps=\ssecsc
-  \let\tensf=\ssecsf \let\teni=\sseci \let\tensy=\ssecsy \let\tenttsl=\ssecttsl
-  \resetmathfonts \setleading{15pt}}
-\let\subsubsecfonts = \subsecfonts % Maybe make sssec fonts scaled magstephalf?
-\def\smallfonts{%
-  \let\tenrm=\smallrm \let\tenit=\smallit \let\tensl=\smallsl
-  \let\tenbf=\smallbf \let\tentt=\smalltt \let\smallcaps=\smallsc
-  \let\tensf=\smallsf \let\teni=\smalli \let\tensy=\smallsy
-  \let\tenttsl=\smallttsl
-  \resetmathfonts \setleading{11pt}}
-
-% Set up the default fonts, so we can use them for creating boxes.
-%
-\textfonts
-
-% Define these so they can be easily changed for other fonts.
-\def\angleleft{$\langle$}
-\def\angleright{$\rangle$}
-
-% Count depth in font-changes, for error checks
-\newcount\fontdepth \fontdepth=0
-
-% Fonts for short table of contents.
-\setfont\shortcontrm\rmshape{12}{1000}
-\setfont\shortcontbf\bxshape{12}{1000}
-\setfont\shortcontsl\slshape{12}{1000}
-
-%% Add scribe-like font environments, plus @l for inline lisp (usually sans
-%% serif) and @ii for TeX italic
-
-% \smartitalic{ARG} outputs arg in italics, followed by an italic correction
-% unless the following character is such as not to need one.
-\def\smartitalicx{\ifx\next,\else\ifx\next-\else\ifx\next.\else\/\fi\fi\fi}
-\def\smartslanted#1{{\sl #1}\futurelet\next\smartitalicx}
-\def\smartitalic#1{{\it #1}\futurelet\next\smartitalicx}
-
-\let\i=\smartitalic
-\let\var=\smartslanted
-\let\dfn=\smartslanted
-\let\emph=\smartitalic
-\let\cite=\smartslanted
-
-\def\b#1{{\bf #1}}
-\let\strong=\b
-
-% We can't just use \exhyphenpenalty, because that only has effect at
-% the end of a paragraph.  Restore normal hyphenation at the end of the
-% group within which \nohyphenation is presumably called.
-%
-\def\nohyphenation{\hyphenchar\font = -1  \aftergroup\restorehyphenation}
-\def\restorehyphenation{\hyphenchar\font = `- }
-
-\def\t#1{%
-  {\tt \rawbackslash \frenchspacing #1}%
-  \null
-}
-\let\ttfont=\t
-\def\samp#1{`\tclose{#1}'\null}
-\setfont\keyrm\rmshape{8}{1000}
-\font\keysy=cmsy9
-\def\key#1{{\keyrm\textfont2=\keysy \leavevmode\hbox{%
-  \raise0.4pt\hbox{\angleleft}\kern-.08em\vtop{%
-    \vbox{\hrule\kern-0.4pt
-     \hbox{\raise0.4pt\hbox{\vphantom{\angleleft}}#1}}%
-    \kern-0.4pt\hrule}%
-  \kern-.06em\raise0.4pt\hbox{\angleright}}}}
-% The old definition, with no lozenge:
-%\def\key #1{{\ttsl \nohyphenation \uppercase{#1}}\null}
-\def\ctrl #1{{\tt \rawbackslash \hat}#1}
-
-% @file, @option are the same as @samp.
-\let\file=\samp
-\let\option=\samp
-
-% @code is a modification of @t,
-% which makes spaces the same size as normal in the surrounding text.
-\def\tclose#1{%
-  {%
-    % Change normal interword space to be same as for the current font.
-    \spaceskip = \fontdimen2\font
-    %
-    % Switch to typewriter.
-    \tt
-    %
-    % But `\ ' produces the large typewriter interword space.
-    \def\ {{\spaceskip = 0pt{} }}%
-    %
-    % Turn off hyphenation.
-    \nohyphenation
-    %
-    \rawbackslash
-    \frenchspacing
-    #1%
-  }%
-  \null
-}
-
-% We *must* turn on hyphenation at `-' and `_' in \code.
-% Otherwise, it is too hard to avoid overfull hboxes
-% in the Emacs manual, the Library manual, etc.
-
-% Unfortunately, TeX uses one parameter (\hyphenchar) to control
-% both hyphenation at - and hyphenation within words.
-% We must therefore turn them both off (\tclose does that)
-% and arrange explicitly to hyphenate at a dash.
-%  -- rms.
-{
-  \catcode`\-=\active
-  \catcode`\_=\active
-  %
-  \global\def\code{\begingroup
-    \catcode`\-=\active \let-\codedash
-    \catcode`\_=\active \let_\codeunder
-    \codex
-  }
-  %
-  % If we end up with any active - characters when handling the index,
-  % just treat them as a normal -.
-  \global\def\indexbreaks{\catcode`\-=\active \let-\realdash}
-}
-
-\def\realdash{-}
-\def\codedash{-\discretionary{}{}{}}
-\def\codeunder{\ifusingtt{\normalunderscore\discretionary{}{}{}}{\_}}
-\def\codex #1{\tclose{#1}\endgroup}
-
-%\let\exp=\tclose  %Was temporary
-
-% @kbd is like @code, except that if the argument is just one @key command,
-% then @kbd has no effect.
-
-% @kbdinputstyle -- arg is `distinct' (@kbd uses slanted tty font always),
-%   `example' (@kbd uses ttsl only inside of @example and friends),
-%   or `code' (@kbd uses normal tty font always).
-\def\kbdinputstyle{\parsearg\kbdinputstylexxx}
-\def\kbdinputstylexxx#1{%
-  \def\arg{#1}%
-  \ifx\arg\worddistinct
-    \gdef\kbdexamplefont{\ttsl}\gdef\kbdfont{\ttsl}%
-  \else\ifx\arg\wordexample
-    \gdef\kbdexamplefont{\ttsl}\gdef\kbdfont{\tt}%
-  \else\ifx\arg\wordcode
-    \gdef\kbdexamplefont{\tt}\gdef\kbdfont{\tt}%
-  \fi\fi\fi
-}
-\def\worddistinct{distinct}
-\def\wordexample{example}
-\def\wordcode{code}
-
-% Default is kbdinputdistinct.  (Too much of a hassle to call the macro,
-% the catcodes are wrong for parsearg to work.)
-\gdef\kbdexamplefont{\ttsl}\gdef\kbdfont{\ttsl}
-
-\def\xkey{\key}
-\def\kbdfoo#1#2#3\par{\def\one{#1}\def\three{#3}\def\threex{??}%
-\ifx\one\xkey\ifx\threex\three \key{#2}%
-\else{\tclose{\kbdfont\look}}\fi
-\else{\tclose{\kbdfont\look}}\fi}
-
-% For @url, @env, @command quotes seem unnecessary, so use \code.
-\let\url=\code
-\let\env=\code
-\let\command=\code
-
-% @uref (abbreviation for `urlref') takes an optional (comma-separated)
-% second argument specifying the text to display and an optional third
-% arg as text to display instead of (rather than in addition to) the url
-% itself.  First (mandatory) arg is the url.  Perhaps eventually put in
-% a hypertex \special here.
-%
-\def\uref#1{\douref #1,,,\finish}
-\def\douref#1,#2,#3,#4\finish{\begingroup
-  \unsepspaces
-  \pdfurl{#1}%
-  \setbox0 = \hbox{\ignorespaces #3}%
-  \ifdim\wd0 > 0pt
-    \unhbox0 % third arg given, show only that
-  \else
-    \setbox0 = \hbox{\ignorespaces #2}%
-    \ifdim\wd0 > 0pt
-      \ifpdf
-        \unhbox0             % PDF: 2nd arg given, show only it
-      \else
-        \unhbox0\ (\code{#1})% DVI: 2nd arg given, show both it and url
-      \fi
-    \else
-      \code{#1}% only url given, so show it
-    \fi
-  \fi
-  \endlink
-\endgroup}
-
-% rms does not like angle brackets --karl, 17may97.
-% So now @email is just like @uref, unless we are pdf.
-% 
-%\def\email#1{\angleleft{\tt #1}\angleright}
-\ifpdf
-  \def\email#1{\doemail#1,,\finish}
-  \def\doemail#1,#2,#3\finish{\begingroup
-    \unsepspaces
-    \pdfurl{mailto:#1}%
-    \setbox0 = \hbox{\ignorespaces #2}%
-    \ifdim\wd0>0pt\unhbox0\else\code{#1}\fi
-    \endlink
-  \endgroup}
-\else
-  \let\email=\uref
-\fi
-
-% Check if we are currently using a typewriter font.  Since all the
-% Computer Modern typewriter fonts have zero interword stretch (and
-% shrink), and it is reasonable to expect all typewriter fonts to have
-% this property, we can check that font parameter.
-%
-\def\ifmonospace{\ifdim\fontdimen3\font=0pt }
-
-% Typeset a dimension, e.g., `in' or `pt'.  The only reason for the
-% argument is to make the input look right: @dmn{pt} instead of @dmn{}pt.
-%
-\def\dmn#1{\thinspace #1}
-
-\def\kbd#1{\def\look{#1}\expandafter\kbdfoo\look??\par}
-
-% @l was never documented to mean ``switch to the Lisp font'',
-% and it is not used as such in any manual I can find.  We need it for
-% Polish suppressed-l.  --karl, 22sep96.
-%\def\l#1{{\li #1}\null}
-
-% Explicit font changes: @r, @sc, undocumented @ii.
-\def\r#1{{\rm #1}}              % roman font
-\def\sc#1{{\smallcaps#1}}       % smallcaps font
-\def\ii#1{{\it #1}}             % italic font
-
-% @acronym downcases the argument and prints in smallcaps.
-\def\acronym#1{{\smallcaps \lowercase{#1}}}
-
-% @pounds{} is a sterling sign.
-\def\pounds{{\it\$}}
-
-
-\message{page headings,}
-
-\newskip\titlepagetopglue \titlepagetopglue = 1.5in
-\newskip\titlepagebottomglue \titlepagebottomglue = 2pc
-
-% First the title page.  Must do @settitle before @titlepage.
-\newif\ifseenauthor
-\newif\iffinishedtitlepage
-
-% Do an implicit @contents or @shortcontents after @end titlepage if the
-% user says @setcontentsaftertitlepage or @setshortcontentsaftertitlepage.
-%
-\newif\ifsetcontentsaftertitlepage
- \let\setcontentsaftertitlepage = \setcontentsaftertitlepagetrue
-\newif\ifsetshortcontentsaftertitlepage
- \let\setshortcontentsaftertitlepage = \setshortcontentsaftertitlepagetrue
-
-\def\shorttitlepage{\parsearg\shorttitlepagezzz}
-\def\shorttitlepagezzz #1{\begingroup\hbox{}\vskip 1.5in \chaprm \centerline{#1}%
-        \endgroup\page\hbox{}\page}
-
-\def\titlepage{\begingroup \parindent=0pt \textfonts
-   \let\subtitlerm=\tenrm
-   \def\subtitlefont{\subtitlerm \normalbaselineskip = 13pt \normalbaselines}%
-   %
-   \def\authorfont{\authorrm \normalbaselineskip = 16pt \normalbaselines}%
-   %
-   % Leave some space at the very top of the page.
-   \vglue\titlepagetopglue
-   %
-   % Now you can print the title using @title.
-   \def\title{\parsearg\titlezzz}%
-   \def\titlezzz##1{\leftline{\titlefonts\rm ##1}
-                    % print a rule at the page bottom also.
-                    \finishedtitlepagefalse
-                    \vskip4pt \hrule height 4pt width \hsize \vskip4pt}%
-   % No rule at page bottom unless we print one at the top with @title.
-   \finishedtitlepagetrue
-   %
-   % Now you can put text using @subtitle.
-   \def\subtitle{\parsearg\subtitlezzz}%
-   \def\subtitlezzz##1{{\subtitlefont \rightline{##1}}}%
-   %
-   % @author should come last, but may come many times.
-   \def\author{\parsearg\authorzzz}%
-   \def\authorzzz##1{\ifseenauthor\else\vskip 0pt plus 1filll\seenauthortrue\fi
-      {\authorfont \leftline{##1}}}%
-   %
-   % Most title ``pages'' are actually two pages long, with space
-   % at the top of the second.  We don't want the ragged left on the second.
-   \let\oldpage = \page
-   \def\page{%
-      \iffinishedtitlepage\else
-         \finishtitlepage
-      \fi
-      \oldpage
-      \let\page = \oldpage
-      \hbox{}}%
-%   \def\page{\oldpage \hbox{}}
-}
-
-\def\Etitlepage{%
-   \iffinishedtitlepage\else
-      \finishtitlepage
-   \fi
-   % It is important to do the page break before ending the group,
-   % because the headline and footline are only empty inside the group.
-   % If we use the new definition of \page, we always get a blank page
-   % after the title page, which we certainly don't want.
-   \oldpage
-   \endgroup
-   %
-   % If they want short, they certainly want long too.
-   \ifsetshortcontentsaftertitlepage
-     \shortcontents
-     \contents
-     \global\let\shortcontents = \relax
-     \global\let\contents = \relax
-   \fi
-   %
-   \ifsetcontentsaftertitlepage
-     \contents
-     \global\let\contents = \relax
-     \global\let\shortcontents = \relax
-   \fi
-   %
-   \ifpdf \pdfmakepagedesttrue \fi
-   %
-   \HEADINGSon
-}
-
-\def\finishtitlepage{%
-   \vskip4pt \hrule height 2pt width \hsize
-   \vskip\titlepagebottomglue
-   \finishedtitlepagetrue
-}
-
-%%% Set up page headings and footings.
-
-\let\thispage=\folio
-
-\newtoks\evenheadline    % headline on even pages
-\newtoks\oddheadline     % headline on odd pages
-\newtoks\evenfootline    % footline on even pages
-\newtoks\oddfootline     % footline on odd pages
-
-% Now make Tex use those variables
-\headline={{\textfonts\rm \ifodd\pageno \the\oddheadline
-                            \else \the\evenheadline \fi}}
-\footline={{\textfonts\rm \ifodd\pageno \the\oddfootline
-                            \else \the\evenfootline \fi}\HEADINGShook}
-\let\HEADINGShook=\relax
-
-% Commands to set those variables.
-% For example, this is what  @headings on  does
-% @evenheading @thistitle|@thispage|@thischapter
-% @oddheading @thischapter|@thispage|@thistitle
-% @evenfooting @thisfile||
-% @oddfooting ||@thisfile
-
-\def\evenheading{\parsearg\evenheadingxxx}
-\def\oddheading{\parsearg\oddheadingxxx}
-\def\everyheading{\parsearg\everyheadingxxx}
-
-\def\evenfooting{\parsearg\evenfootingxxx}
-\def\oddfooting{\parsearg\oddfootingxxx}
-\def\everyfooting{\parsearg\everyfootingxxx}
-
-{\catcode`\@=0 %
-
-\gdef\evenheadingxxx #1{\evenheadingyyy #1@|@|@|@|\finish}
-\gdef\evenheadingyyy #1@|#2@|#3@|#4\finish{%
-\global\evenheadline={\rlap{\centerline{#2}}\line{#1\hfil#3}}}
-
-\gdef\oddheadingxxx #1{\oddheadingyyy #1@|@|@|@|\finish}
-\gdef\oddheadingyyy #1@|#2@|#3@|#4\finish{%
-\global\oddheadline={\rlap{\centerline{#2}}\line{#1\hfil#3}}}
-
-\gdef\everyheadingxxx#1{\oddheadingxxx{#1}\evenheadingxxx{#1}}%
-
-\gdef\evenfootingxxx #1{\evenfootingyyy #1@|@|@|@|\finish}
-\gdef\evenfootingyyy #1@|#2@|#3@|#4\finish{%
-\global\evenfootline={\rlap{\centerline{#2}}\line{#1\hfil#3}}}
-
-\gdef\oddfootingxxx #1{\oddfootingyyy #1@|@|@|@|\finish}
-\gdef\oddfootingyyy #1@|#2@|#3@|#4\finish{%
-  \global\oddfootline = {\rlap{\centerline{#2}}\line{#1\hfil#3}}%
-  %
-  % Leave some space for the footline.  Hopefully ok to assume
-  % @evenfooting will not be used by itself.
-  \global\advance\pageheight by -\baselineskip
-  \global\advance\vsize by -\baselineskip
-}
-
-\gdef\everyfootingxxx#1{\oddfootingxxx{#1}\evenfootingxxx{#1}}
-%
-}% unbind the catcode of @.
-
-% @headings double      turns headings on for double-sided printing.
-% @headings single      turns headings on for single-sided printing.
-% @headings off         turns them off.
-% @headings on          same as @headings double, retained for compatibility.
-% @headings after       turns on double-sided headings after this page.
-% @headings doubleafter turns on double-sided headings after this page.
-% @headings singleafter turns on single-sided headings after this page.
-% By default, they are off at the start of a document,
-% and turned `on' after @end titlepage.
-
-\def\headings #1 {\csname HEADINGS#1\endcsname}
-
-\def\HEADINGSoff{
-\global\evenheadline={\hfil} \global\evenfootline={\hfil}
-\global\oddheadline={\hfil} \global\oddfootline={\hfil}}
-\HEADINGSoff
-% When we turn headings on, set the page number to 1.
-% For double-sided printing, put current file name in lower left corner,
-% chapter name on inside top of right hand pages, document
-% title on inside top of left hand pages, and page numbers on outside top
-% edge of all pages.
-\def\HEADINGSdouble{
-\global\pageno=1
-\global\evenfootline={\hfil}
-\global\oddfootline={\hfil}
-\global\evenheadline={\line{\folio\hfil\thistitle}}
-\global\oddheadline={\line{\thischapter\hfil\folio}}
-\global\let\contentsalignmacro = \chapoddpage
-}
-\let\contentsalignmacro = \chappager
-
-% For single-sided printing, chapter title goes across top left of page,
-% page number on top right.
-\def\HEADINGSsingle{
-\global\pageno=1
-\global\evenfootline={\hfil}
-\global\oddfootline={\hfil}
-\global\evenheadline={\line{\thischapter\hfil\folio}}
-\global\oddheadline={\line{\thischapter\hfil\folio}}
-\global\let\contentsalignmacro = \chappager
-}
-\def\HEADINGSon{\HEADINGSdouble}
-
-\def\HEADINGSafter{\let\HEADINGShook=\HEADINGSdoublex}
-\let\HEADINGSdoubleafter=\HEADINGSafter
-\def\HEADINGSdoublex{%
-\global\evenfootline={\hfil}
-\global\oddfootline={\hfil}
-\global\evenheadline={\line{\folio\hfil\thistitle}}
-\global\oddheadline={\line{\thischapter\hfil\folio}}
-\global\let\contentsalignmacro = \chapoddpage
-}
-
-\def\HEADINGSsingleafter{\let\HEADINGShook=\HEADINGSsinglex}
-\def\HEADINGSsinglex{%
-\global\evenfootline={\hfil}
-\global\oddfootline={\hfil}
-\global\evenheadline={\line{\thischapter\hfil\folio}}
-\global\oddheadline={\line{\thischapter\hfil\folio}}
-\global\let\contentsalignmacro = \chappager
-}
-
-% Subroutines used in generating headings
-% This produces Day Month Year style of output.
-% Only define if not already defined, in case a txi-??.tex file has set
-% up a different format (e.g., txi-cs.tex does this).
-\ifx\today\undefined
-\def\today{%
-  \number\day\space
-  \ifcase\month
-  \or\putwordMJan\or\putwordMFeb\or\putwordMMar\or\putwordMApr
-  \or\putwordMMay\or\putwordMJun\or\putwordMJul\or\putwordMAug
-  \or\putwordMSep\or\putwordMOct\or\putwordMNov\or\putwordMDec
-  \fi
-  \space\number\year}
-\fi
-
-% @settitle line...  specifies the title of the document, for headings.
-% It generates no output of its own.
-\def\thistitle{\putwordNoTitle}
-\def\settitle{\parsearg\settitlezzz}
-\def\settitlezzz #1{\gdef\thistitle{#1}}
-
-
-\message{tables,}
-% Tables -- @table, @ftable, @vtable, @item(x), @kitem(x), @xitem(x).
-
-% default indentation of table text
-\newdimen\tableindent \tableindent=.8in
-% default indentation of @itemize and @enumerate text
-\newdimen\itemindent  \itemindent=.3in
-% margin between end of table item and start of table text.
-\newdimen\itemmargin  \itemmargin=.1in
-
-% used internally for \itemindent minus \itemmargin
-\newdimen\itemmax
-
-% Note @table, @vtable, and @vtable define @item, @itemx, etc., with
-% these defs.
-% They also define \itemindex
-% to index the item name in whatever manner is desired (perhaps none).
-
-\newif\ifitemxneedsnegativevskip
-
-\def\itemxpar{\par\ifitemxneedsnegativevskip\nobreak\vskip-\parskip\nobreak\fi}
-
-\def\internalBitem{\smallbreak \parsearg\itemzzz}
-\def\internalBitemx{\itemxpar \parsearg\itemzzz}
-
-\def\internalBxitem "#1"{\def\xitemsubtopix{#1} \smallbreak \parsearg\xitemzzz}
-\def\internalBxitemx "#1"{\def\xitemsubtopix{#1} \itemxpar \parsearg\xitemzzz}
-
-\def\internalBkitem{\smallbreak \parsearg\kitemzzz}
-\def\internalBkitemx{\itemxpar \parsearg\kitemzzz}
-
-\def\kitemzzz #1{\dosubind {kw}{\code{#1}}{for {\bf \lastfunction}}%
-                 \itemzzz {#1}}
-
-\def\xitemzzz #1{\dosubind {kw}{\code{#1}}{for {\bf \xitemsubtopic}}%
-                 \itemzzz {#1}}
-
-\def\itemzzz #1{\begingroup %
-  \advance\hsize by -\rightskip
-  \advance\hsize by -\tableindent
-  \setbox0=\hbox{\itemfont{#1}}%
-  \itemindex{#1}%
-  \nobreak % This prevents a break before @itemx.
-  %
-  % If the item text does not fit in the space we have, put it on a line
-  % by itself, and do not allow a page break either before or after that
-  % line.  We do not start a paragraph here because then if the next
-  % command is, e.g., @kindex, the whatsit would get put into the
-  % horizontal list on a line by itself, resulting in extra blank space.
-  \ifdim \wd0>\itemmax
-    %
-    % Make this a paragraph so we get the \parskip glue and wrapping,
-    % but leave it ragged-right.
-    \begingroup
-      \advance\leftskip by-\tableindent
-      \advance\hsize by\tableindent
-      \advance\rightskip by0pt plus1fil
-      \leavevmode\unhbox0\par
-    \endgroup
-    %
-    % We're going to be starting a paragraph, but we don't want the
-    % \parskip glue -- logically it's part of the @item we just started.
-    \nobreak \vskip-\parskip
-    %
-    % Stop a page break at the \parskip glue coming up.  Unfortunately
-    % we can't prevent a possible page break at the following
-    % \baselineskip glue.
-    \nobreak
-    \endgroup
-    \itemxneedsnegativevskipfalse
-  \else
-    % The item text fits into the space.  Start a paragraph, so that the
-    % following text (if any) will end up on the same line.
-    \noindent
-    % Do this with kerns and \unhbox so that if there is a footnote in
-    % the item text, it can migrate to the main vertical list and
-    % eventually be printed.
-    \nobreak\kern-\tableindent
-    \dimen0 = \itemmax  \advance\dimen0 by \itemmargin \advance\dimen0 by -\wd0
-    \unhbox0
-    \nobreak\kern\dimen0
-    \endgroup
-    \itemxneedsnegativevskiptrue
-  \fi
-}
-
-\def\item{\errmessage{@item while not in a table}}
-\def\itemx{\errmessage{@itemx while not in a table}}
-\def\kitem{\errmessage{@kitem while not in a table}}
-\def\kitemx{\errmessage{@kitemx while not in a table}}
-\def\xitem{\errmessage{@xitem while not in a table}}
-\def\xitemx{\errmessage{@xitemx while not in a table}}
-
-% Contains a kludge to get @end[description] to work.
-\def\description{\tablez{\dontindex}{1}{}{}{}{}}
-
-% @table, @ftable, @vtable.
-\def\table{\begingroup\inENV\obeylines\obeyspaces\tablex}
-{\obeylines\obeyspaces%
-\gdef\tablex #1^^M{%
-\tabley\dontindex#1        \endtabley}}
-
-\def\ftable{\begingroup\inENV\obeylines\obeyspaces\ftablex}
-{\obeylines\obeyspaces%
-\gdef\ftablex #1^^M{%
-\tabley\fnitemindex#1        \endtabley
-\def\Eftable{\endgraf\afterenvbreak\endgroup}%
-\let\Etable=\relax}}
-
-\def\vtable{\begingroup\inENV\obeylines\obeyspaces\vtablex}
-{\obeylines\obeyspaces%
-\gdef\vtablex #1^^M{%
-\tabley\vritemindex#1        \endtabley
-\def\Evtable{\endgraf\afterenvbreak\endgroup}%
-\let\Etable=\relax}}
-
-\def\dontindex #1{}
-\def\fnitemindex #1{\doind {fn}{\code{#1}}}%
-\def\vritemindex #1{\doind {vr}{\code{#1}}}%
-
-{\obeyspaces %
-\gdef\tabley#1#2 #3 #4 #5 #6 #7\endtabley{\endgroup%
-\tablez{#1}{#2}{#3}{#4}{#5}{#6}}}
-
-\def\tablez #1#2#3#4#5#6{%
-\aboveenvbreak %
-\begingroup %
-\def\Edescription{\Etable}% Necessary kludge.
-\let\itemindex=#1%
-\ifnum 0#3>0 \advance \leftskip by #3\mil \fi %
-\ifnum 0#4>0 \tableindent=#4\mil \fi %
-\ifnum 0#5>0 \advance \rightskip by #5\mil \fi %
-\def\itemfont{#2}%
-\itemmax=\tableindent %
-\advance \itemmax by -\itemmargin %
-\advance \leftskip by \tableindent %
-\exdentamount=\tableindent
-\parindent = 0pt
-\parskip = \smallskipamount
-\ifdim \parskip=0pt \parskip=2pt \fi%
-\def\Etable{\endgraf\afterenvbreak\endgroup}%
-\let\item = \internalBitem %
-\let\itemx = \internalBitemx %
-\let\kitem = \internalBkitem %
-\let\kitemx = \internalBkitemx %
-\let\xitem = \internalBxitem %
-\let\xitemx = \internalBxitemx %
-}
-
-% This is the counter used by @enumerate, which is really @itemize
-
-\newcount \itemno
-
-\def\itemize{\parsearg\itemizezzz}
-
-\def\itemizezzz #1{%
-  \begingroup % ended by the @end itemize
-  \itemizey {#1}{\Eitemize}
-}
-
-\def\itemizey #1#2{%
-\aboveenvbreak %
-\itemmax=\itemindent %
-\advance \itemmax by -\itemmargin %
-\advance \leftskip by \itemindent %
-\exdentamount=\itemindent
-\parindent = 0pt %
-\parskip = \smallskipamount %
-\ifdim \parskip=0pt \parskip=2pt \fi%
-\def#2{\endgraf\afterenvbreak\endgroup}%
-\def\itemcontents{#1}%
-\let\item=\itemizeitem}
-
-% Set sfcode to normal for the chars that usually have another value.
-% These are `.?!:;,'
-\def\frenchspacing{\sfcode46=1000 \sfcode63=1000 \sfcode33=1000
-  \sfcode58=1000 \sfcode59=1000 \sfcode44=1000 }
-
-% \splitoff TOKENS\endmark defines \first to be the first token in
-% TOKENS, and \rest to be the remainder.
-%
-\def\splitoff#1#2\endmark{\def\first{#1}\def\rest{#2}}%
-
-% Allow an optional argument of an uppercase letter, lowercase letter,
-% or number, to specify the first label in the enumerated list.  No
-% argument is the same as `1'.
-%
-\def\enumerate{\parsearg\enumeratezzz}
-\def\enumeratezzz #1{\enumeratey #1  \endenumeratey}
-\def\enumeratey #1 #2\endenumeratey{%
-  \begingroup % ended by the @end enumerate
-  %
-  % If we were given no argument, pretend we were given `1'.
-  \def\thearg{#1}%
-  \ifx\thearg\empty \def\thearg{1}\fi
-  %
-  % Detect if the argument is a single token.  If so, it might be a
-  % letter.  Otherwise, the only valid thing it can be is a number.
-  % (We will always have one token, because of the test we just made.
-  % This is a good thing, since \splitoff doesn't work given nothing at
-  % all -- the first parameter is undelimited.)
-  \expandafter\splitoff\thearg\endmark
-  \ifx\rest\empty
-    % Only one token in the argument.  It could still be anything.
-    % A ``lowercase letter'' is one whose \lccode is nonzero.
-    % An ``uppercase letter'' is one whose \lccode is both nonzero, and
-    %   not equal to itself.
-    % Otherwise, we assume it's a number.
-    %
-    % We need the \relax at the end of the \ifnum lines to stop TeX from
-    % continuing to look for a <number>.
-    %
-    \ifnum\lccode\expandafter`\thearg=0\relax
-      \numericenumerate % a number (we hope)
-    \else
-      % It's a letter.
-      \ifnum\lccode\expandafter`\thearg=\expandafter`\thearg\relax
-        \lowercaseenumerate % lowercase letter
-      \else
-        \uppercaseenumerate % uppercase letter
-      \fi
-    \fi
-  \else
-    % Multiple tokens in the argument.  We hope it's a number.
-    \numericenumerate
-  \fi
-}
-
-% An @enumerate whose labels are integers.  The starting integer is
-% given in \thearg.
-%
-\def\numericenumerate{%
-  \itemno = \thearg
-  \startenumeration{\the\itemno}%
-}
-
-% The starting (lowercase) letter is in \thearg.
-\def\lowercaseenumerate{%
-  \itemno = \expandafter`\thearg
-  \startenumeration{%
-    % Be sure we're not beyond the end of the alphabet.
-    \ifnum\itemno=0
-      \errmessage{No more lowercase letters in @enumerate; get a bigger
-                  alphabet}%
-    \fi
-    \char\lccode\itemno
-  }%
-}
-
-% The starting (uppercase) letter is in \thearg.
-\def\uppercaseenumerate{%
-  \itemno = \expandafter`\thearg
-  \startenumeration{%
-    % Be sure we're not beyond the end of the alphabet.
-    \ifnum\itemno=0
-      \errmessage{No more uppercase letters in @enumerate; get a bigger
-                  alphabet}
-    \fi
-    \char\uccode\itemno
-  }%
-}
-
-% Call itemizey, adding a period to the first argument and supplying the
-% common last two arguments.  Also subtract one from the initial value in
-% \itemno, since @item increments \itemno.
-%
-\def\startenumeration#1{%
-  \advance\itemno by -1
-  \itemizey{#1.}\Eenumerate\flushcr
-}
-
-% @alphaenumerate and @capsenumerate are abbreviations for giving an arg
-% to @enumerate.
-%
-\def\alphaenumerate{\enumerate{a}}
-\def\capsenumerate{\enumerate{A}}
-\def\Ealphaenumerate{\Eenumerate}
-\def\Ecapsenumerate{\Eenumerate}
-
-% Definition of @item while inside @itemize.
-
-\def\itemizeitem{%
-\advance\itemno by 1
-{\let\par=\endgraf \smallbreak}%
-\ifhmode \errmessage{In hmode at itemizeitem}\fi
-{\parskip=0in \hskip 0pt
-\hbox to 0pt{\hss \itemcontents\hskip \itemmargin}%
-\vadjust{\penalty 1200}}%
-\flushcr}
-
-% @multitable macros
-% Amy Hendrickson, 8/18/94, 3/6/96
-%
-% @multitable ... @end multitable will make as many columns as desired.
-% Contents of each column will wrap at width given in preamble.  Width
-% can be specified either with sample text given in a template line,
-% or in percent of \hsize, the current width of text on page.
-
-% Table can continue over pages but will only break between lines.
-
-% To make preamble:
-%
-% Either define widths of columns in terms of percent of \hsize:
-%   @multitable @columnfractions .25 .3 .45
-%   @item ...
-%
-%   Numbers following @columnfractions are the percent of the total
-%   current hsize to be used for each column. You may use as many
-%   columns as desired.
-
-
-% Or use a template:
-%   @multitable {Column 1 template} {Column 2 template} {Column 3 template}
-%   @item ...
-%   using the widest term desired in each column.
-%
-% For those who want to use more than one line's worth of words in
-% the preamble, break the line within one argument and it
-% will parse correctly, i.e.,
-%
-%     @multitable {Column 1 template} {Column 2 template} {Column 3
-%      template}
-% Not:
-%     @multitable {Column 1 template} {Column 2 template}
-%      {Column 3 template}
-
-% Each new table line starts with @item, each subsequent new column
-% starts with @tab. Empty columns may be produced by supplying @tab's
-% with nothing between them for as many times as empty columns are needed,
-% ie, @tab at tab@tab will produce two empty columns.
-
-% @item, @tab, @multitable or @end multitable do not need to be on their
-% own lines, but it will not hurt if they are.
-
-% Sample multitable:
-
-%   @multitable {Column 1 template} {Column 2 template} {Column 3 template}
-%   @item first col stuff @tab second col stuff @tab third col
-%   @item
-%   first col stuff
-%   @tab
-%   second col stuff
-%   @tab
-%   third col
-%   @item first col stuff @tab second col stuff
-%   @tab Many paragraphs of text may be used in any column.
-%
-%         They will wrap at the width determined by the template.
-%   @item at tab@tab This will be in third column.
-%   @end multitable
-
-% Default dimensions may be reset by user.
-% @multitableparskip is vertical space between paragraphs in table.
-% @multitableparindent is paragraph indent in table.
-% @multitablecolmargin is horizontal space to be left between columns.
-% @multitablelinespace is space to leave between table items, baseline
-%                                                            to baseline.
-%   0pt means it depends on current normal line spacing.
-%
-\newskip\multitableparskip
-\newskip\multitableparindent
-\newdimen\multitablecolspace
-\newskip\multitablelinespace
-\multitableparskip=0pt
-\multitableparindent=6pt
-\multitablecolspace=12pt
-\multitablelinespace=0pt
-
-% Macros used to set up halign preamble:
-%
-\let\endsetuptable\relax
-\def\xendsetuptable{\endsetuptable}
-\let\columnfractions\relax
-\def\xcolumnfractions{\columnfractions}
-\newif\ifsetpercent
-
-% #1 is the part of the @columnfraction before the decimal point, which
-% is presumably either 0 or the empty string (but we don't check, we
-% just throw it away).  #2 is the decimal part, which we use as the
-% percent of \hsize for this column.
-\def\pickupwholefraction#1.#2 {%
-  \global\advance\colcount by 1
-  \expandafter\xdef\csname col\the\colcount\endcsname{.#2\hsize}%
-  \setuptable
-}
-
-\newcount\colcount
-\def\setuptable#1{%
-  \def\firstarg{#1}%
-  \ifx\firstarg\xendsetuptable
-    \let\go = \relax
-  \else
-    \ifx\firstarg\xcolumnfractions
-      \global\setpercenttrue
-    \else
-      \ifsetpercent
-         \let\go\pickupwholefraction
-      \else
-         \global\advance\colcount by 1
-         \setbox0=\hbox{#1\unskip }% Add a normal word space as a separator;
-                            % typically that is always in the input, anyway.
-         \expandafter\xdef\csname col\the\colcount\endcsname{\the\wd0}%
-      \fi
-    \fi
-    \ifx\go\pickupwholefraction
-      % Put the argument back for the \pickupwholefraction call, so
-      % we'll always have a period there to be parsed.
-      \def\go{\pickupwholefraction#1}%
-    \else
-      \let\go = \setuptable
-    \fi%
-  \fi
-  \go
-}
-
-% This used to have \hskip1sp.  But then the space in a template line is
-% not enough.  That is bad.  So let's go back to just & until we
-% encounter the problem it was intended to solve again.
-% --karl, nathan at acm.org, 20apr99.
-\def\tab{&}
-
-% @multitable ... @end multitable definitions:
-%
-\def\multitable{\parsearg\dotable}
-\def\dotable#1{\bgroup
-  \vskip\parskip
-  \let\item\crcr
-  \tolerance=9500
-  \hbadness=9500
-  \setmultitablespacing
-  \parskip=\multitableparskip
-  \parindent=\multitableparindent
-  \overfullrule=0pt
-  \global\colcount=0
-  \def\Emultitable{\global\setpercentfalse\cr\egroup\egroup}%
-  %
-  % To parse everything between @multitable and @item:
-  \setuptable#1 \endsetuptable
-  %
-  % \everycr will reset column counter, \colcount, at the end of
-  % each line. Every column entry will cause \colcount to advance by one.
-  % The table preamble
-  % looks at the current \colcount to find the correct column width.
-  \everycr{\noalign{%
-  %
-  % \filbreak%% keeps underfull box messages off when table breaks over pages.
-  % Maybe so, but it also creates really weird page breaks when the table
-  % breaks over pages. Wouldn't \vfil be better?  Wait until the problem
-  % manifests itself, so it can be fixed for real --karl.
-    \global\colcount=0\relax}}%
-  %
-  % This preamble sets up a generic column definition, which will
-  % be used as many times as user calls for columns.
-  % \vtop will set a single line and will also let text wrap and
-  % continue for many paragraphs if desired.
-  \halign\bgroup&\global\advance\colcount by 1\relax
-    \multistrut\vtop{\hsize=\expandafter\csname col\the\colcount\endcsname
-  %
-  % In order to keep entries from bumping into each other
-  % we will add a \leftskip of \multitablecolspace to all columns after
-  % the first one.
-  %
-  % If a template has been used, we will add \multitablecolspace
-  % to the width of each template entry.
-  %
-  % If the user has set preamble in terms of percent of \hsize we will
-  % use that dimension as the width of the column, and the \leftskip
-  % will keep entries from bumping into each other.  Table will start at
-  % left margin and final column will justify at right margin.
-  %
-  % Make sure we don't inherit \rightskip from the outer environment.
-  \rightskip=0pt
-  \ifnum\colcount=1
-    % The first column will be indented with the surrounding text.
-    \advance\hsize by\leftskip
-  \else
-    \ifsetpercent \else
-      % If user has not set preamble in terms of percent of \hsize
-      % we will advance \hsize by \multitablecolspace.
-      \advance\hsize by \multitablecolspace
-    \fi
-   % In either case we will make \leftskip=\multitablecolspace:
-  \leftskip=\multitablecolspace
-  \fi
-  % Ignoring space at the beginning and end avoids an occasional spurious
-  % blank line, when TeX decides to break the line at the space before the
-  % box from the multistrut, so the strut ends up on a line by itself.
-  % For example:
-  % @multitable @columnfractions .11 .89
-  % @item @code{#}
-  % @tab Legal holiday which is valid in major parts of the whole country.
-  % Is automatically provided with highlighting sequences respectively marking
-  % characters.
-  \noindent\ignorespaces##\unskip\multistrut}\cr
-}
-
-\def\setmultitablespacing{% test to see if user has set \multitablelinespace.
-% If so, do nothing. If not, give it an appropriate dimension based on
-% current baselineskip.
-\ifdim\multitablelinespace=0pt
-\setbox0=\vbox{X}\global\multitablelinespace=\the\baselineskip
-\global\advance\multitablelinespace by-\ht0
-%% strut to put in table in case some entry doesn't have descenders,
-%% to keep lines equally spaced
-\let\multistrut = \strut
-\else
-%% FIXME: what is \box0 supposed to be?
-\gdef\multistrut{\vrule height\multitablelinespace depth\dp0
-width0pt\relax} \fi
-%% Test to see if parskip is larger than space between lines of
-%% table. If not, do nothing.
-%%        If so, set to same dimension as multitablelinespace.
-\ifdim\multitableparskip>\multitablelinespace
-\global\multitableparskip=\multitablelinespace
-\global\advance\multitableparskip-7pt %% to keep parskip somewhat smaller
-                                      %% than skip between lines in the table.
-\fi%
-\ifdim\multitableparskip=0pt
-\global\multitableparskip=\multitablelinespace
-\global\advance\multitableparskip-7pt %% to keep parskip somewhat smaller
-                                      %% than skip between lines in the table.
-\fi}
-
-
-\message{conditionals,}
-% Prevent errors for section commands.
-% Used in @ignore and in failing conditionals.
-\def\ignoresections{%
-  \let\chapter=\relax
-  \let\unnumbered=\relax
-  \let\top=\relax
-  \let\unnumberedsec=\relax
-  \let\unnumberedsection=\relax
-  \let\unnumberedsubsec=\relax
-  \let\unnumberedsubsection=\relax
-  \let\unnumberedsubsubsec=\relax
-  \let\unnumberedsubsubsection=\relax
-  \let\section=\relax
-  \let\subsec=\relax
-  \let\subsubsec=\relax
-  \let\subsection=\relax
-  \let\subsubsection=\relax
-  \let\appendix=\relax
-  \let\appendixsec=\relax
-  \let\appendixsection=\relax
-  \let\appendixsubsec=\relax
-  \let\appendixsubsection=\relax
-  \let\appendixsubsubsec=\relax
-  \let\appendixsubsubsection=\relax
-  \let\contents=\relax
-  \let\smallbook=\relax
-  \let\titlepage=\relax
-}
-
-% Used in nested conditionals, where we have to parse the Texinfo source
-% and so want to turn off most commands, in case they are used
-% incorrectly.
-%
-\def\ignoremorecommands{%
-  \let\defcodeindex = \relax
-  \let\defcv = \relax
-  \let\deffn = \relax
-  \let\deffnx = \relax
-  \let\defindex = \relax
-  \let\defivar = \relax
-  \let\defmac = \relax
-  \let\defmethod = \relax
-  \let\defop = \relax
-  \let\defopt = \relax
-  \let\defspec = \relax
-  \let\deftp = \relax
-  \let\deftypefn = \relax
-  \let\deftypefun = \relax
-  \let\deftypeivar = \relax
-  \let\deftypeop = \relax
-  \let\deftypevar = \relax
-  \let\deftypevr = \relax
-  \let\defun = \relax
-  \let\defvar = \relax
-  \let\defvr = \relax
-  \let\ref = \relax
-  \let\xref = \relax
-  \let\printindex = \relax
-  \let\pxref = \relax
-  \let\settitle = \relax
-  \let\setchapternewpage = \relax
-  \let\setchapterstyle = \relax
-  \let\everyheading = \relax
-  \let\evenheading = \relax
-  \let\oddheading = \relax
-  \let\everyfooting = \relax
-  \let\evenfooting = \relax
-  \let\oddfooting = \relax
-  \let\headings = \relax
-  \let\include = \relax
-  \let\lowersections = \relax
-  \let\down = \relax
-  \let\raisesections = \relax
-  \let\up = \relax
-  \let\set = \relax
-  \let\clear = \relax
-  \let\item = \relax
-}
-
-% Ignore @ignore ... @end ignore.
-%
-\def\ignore{\doignore{ignore}}
-
-% Ignore @ifinfo, @ifhtml, @ifnottex, @html, @menu, and @direntry text.
-%
-\def\ifinfo{\doignore{ifinfo}}
-\def\ifhtml{\doignore{ifhtml}}
-\def\ifnottex{\doignore{ifnottex}}
-\def\html{\doignore{html}}
-\def\menu{\doignore{menu}}
-\def\direntry{\doignore{direntry}}
-
-% @dircategory CATEGORY  -- specify a category of the dir file
-% which this file should belong to.  Ignore this in TeX.
-\let\dircategory = \comment
-
-% Ignore text until a line `@end #1'.
-%
-\def\doignore#1{\begingroup
-  % Don't complain about control sequences we have declared \outer.
-  \ignoresections
-  %
-  % Define a command to swallow text until we reach `@end #1'.
-  % This @ is a catcode 12 token (that is the normal catcode of @ in
-  % this texinfo.tex file).  We change the catcode of @ below to match.
-  \long\def\doignoretext##1 at end #1{\enddoignore}%
-  %
-  % Make sure that spaces turn into tokens that match what \doignoretext wants.
-  \catcode32 = 10
-  %
-  % Ignore braces, too, so mismatched braces don't cause trouble.
-  \catcode`\{ = 9
-  \catcode`\} = 9
-  %
-  % We must not have @c interpreted as a control sequence.
-  \catcode`\@ = 12
-  %
-  % Make the letter c a comment character so that the rest of the line
-  % will be ignored. This way, the document can have (for example)
-  %   @c @end ifinfo
-  % and the @end ifinfo will be properly ignored.
-  % (We've just changed @ to catcode 12.)
-  \catcode`\c = 14
-  %
-  % And now expand that command.
-  \doignoretext
-}
-
-% What we do to finish off ignored text.
-%
-\def\enddoignore{\endgroup\ignorespaces}%
-
-\newif\ifwarnedobs\warnedobsfalse
-\def\obstexwarn{%
-  \ifwarnedobs\relax\else
-  % We need to warn folks that they may have trouble with TeX 3.0.
-  % This uses \immediate\write16 rather than \message to get newlines.
-    \immediate\write16{}
-    \immediate\write16{WARNING: for users of Unix TeX 3.0!}
-    \immediate\write16{This manual trips a bug in TeX version 3.0 (tex hangs).}
-    \immediate\write16{If you are running another version of TeX, relax.}
-    \immediate\write16{If you are running Unix TeX 3.0, kill this TeX process.}
-    \immediate\write16{  Then upgrade your TeX installation if you can.}
-    \immediate\write16{  (See ftp://ftp.gnu.org/pub/gnu/TeX.README.)}
-    \immediate\write16{If you are stuck with version 3.0, run the}
-    \immediate\write16{  script ``tex3patch'' from the Texinfo distribution}
-    \immediate\write16{  to use a workaround.}
-    \immediate\write16{}
-    \global\warnedobstrue
-    \fi
-}
-
-% **In TeX 3.0, setting text in \nullfont hangs tex.  For a
-% workaround (which requires the file ``dummy.tfm'' to be installed),
-% uncomment the following line:
-%%%%%\font\nullfont=dummy\let\obstexwarn=\relax
-
-% Ignore text, except that we keep track of conditional commands for
-% purposes of nesting, up to an `@end #1' command.
-%
-\def\nestedignore#1{%
-  \obstexwarn
-  % We must actually expand the ignored text to look for the @end
-  % command, so that nested ignore constructs work.  Thus, we put the
-  % text into a \vbox and then do nothing with the result.  To minimize
-  % the change of memory overflow, we follow the approach outlined on
-  % page 401 of the TeXbook: make the current font be a dummy font.
-  %
-  \setbox0 = \vbox\bgroup
-    % Don't complain about control sequences we have declared \outer.
-    \ignoresections
-    %
-    % Define `@end #1' to end the box, which will in turn undefine the
-    % @end command again.
-    \expandafter\def\csname E#1\endcsname{\egroup\ignorespaces}%
-    %
-    % We are going to be parsing Texinfo commands.  Most cause no
-    % trouble when they are used incorrectly, but some commands do
-    % complicated argument parsing or otherwise get confused, so we
-    % undefine them.
-    %
-    % We can't do anything about stray @-signs, unfortunately;
-    % they'll produce `undefined control sequence' errors.
-    \ignoremorecommands
-    %
-    % Set the current font to be \nullfont, a TeX primitive, and define
-    % all the font commands to also use \nullfont.  We don't use
-    % dummy.tfm, as suggested in the TeXbook, because not all sites
-    % might have that installed.  Therefore, math mode will still
-    % produce output, but that should be an extremely small amount of
-    % stuff compared to the main input.
-    %
-    \nullfont
-    \let\tenrm=\nullfont \let\tenit=\nullfont \let\tensl=\nullfont
-    \let\tenbf=\nullfont \let\tentt=\nullfont \let\smallcaps=\nullfont
-    \let\tensf=\nullfont
-    % Similarly for index fonts (mostly for their use in smallexample).
-    \let\smallrm=\nullfont \let\smallit=\nullfont \let\smallsl=\nullfont
-    \let\smallbf=\nullfont \let\smalltt=\nullfont \let\smallsc=\nullfont
-    \let\smallsf=\nullfont
-    %
-    % Don't complain when characters are missing from the fonts.
-    \tracinglostchars = 0
-    %
-    % Don't bother to do space factor calculations.
-    \frenchspacing
-    %
-    % Don't report underfull hboxes.
-    \hbadness = 10000
-    %
-    % Do minimal line-breaking.
-    \pretolerance = 10000
-    %
-    % Do not execute instructions in @tex
-    \def\tex{\doignore{tex}}%
-    % Do not execute macro definitions.
-    % `c' is a comment character, so the word `macro' will get cut off.
-    \def\macro{\doignore{ma}}%
-}
-
-% @set VAR sets the variable VAR to an empty value.
-% @set VAR REST-OF-LINE sets VAR to the value REST-OF-LINE.
-%
-% Since we want to separate VAR from REST-OF-LINE (which might be
-% empty), we can't just use \parsearg; we have to insert a space of our
-% own to delimit the rest of the line, and then take it out again if we
-% didn't need it.  Make sure the catcode of space is correct to avoid
-% losing inside @example, for instance.
-%
-\def\set{\begingroup\catcode` =10
-  \catcode`\-=12 \catcode`\_=12 % Allow - and _ in VAR.
-  \parsearg\setxxx}
-\def\setxxx#1{\setyyy#1 \endsetyyy}
-\def\setyyy#1 #2\endsetyyy{%
-  \def\temp{#2}%
-  \ifx\temp\empty \global\expandafter\let\csname SET#1\endcsname = \empty
-  \else \setzzz{#1}#2\endsetzzz % Remove the trailing space \setxxx inserted.
-  \fi
-  \endgroup
-}
-% Can't use \xdef to pre-expand #2 and save some time, since \temp or
-% \next or other control sequences that we've defined might get us into
-% an infinite loop. Consider `@set foo @cite{bar}'.
-\def\setzzz#1#2 \endsetzzz{\expandafter\gdef\csname SET#1\endcsname{#2}}
-
-% @clear VAR clears (i.e., unsets) the variable VAR.
-%
-\def\clear{\parsearg\clearxxx}
-\def\clearxxx#1{\global\expandafter\let\csname SET#1\endcsname=\relax}
-
-% @value{foo} gets the text saved in variable foo.
-{
-  \catcode`\_ = \active
-  %
-  % We might end up with active _ or - characters in the argument if
-  % we're called from @code, as @code{@value{foo-bar_}}.  So \let any
-  % such active characters to their normal equivalents.
-  \gdef\value{\begingroup
-    \catcode`\-=12 \catcode`\_=12
-    \indexbreaks \let_\normalunderscore
-    \valuexxx}
-}
-\def\valuexxx#1{\expandablevalue{#1}\endgroup}
-
-% We have this subroutine so that we can handle at least some @value's
-% properly in indexes (we \let\value to this in \indexdummies).  Ones
-% whose names contain - or _ still won't work, but we can't do anything
-% about that.  The command has to be fully expandable, since the result
-% winds up in the index file.  This means that if the variable's value
-% contains other Texinfo commands, it's almost certain it will fail
-% (although perhaps we could fix that with sufficient work to do a
-% one-level expansion on the result, instead of complete).
-%
-\def\expandablevalue#1{%
-  \expandafter\ifx\csname SET#1\endcsname\relax
-    {[No value for ``#1'']}%
-  \else
-    \csname SET#1\endcsname
-  \fi
-}
-
-% @ifset VAR ... @end ifset reads the `...' iff VAR has been defined
-% with @set.
-%
-\def\ifset{\parsearg\ifsetxxx}
-\def\ifsetxxx #1{%
-  \expandafter\ifx\csname SET#1\endcsname\relax
-    \expandafter\ifsetfail
-  \else
-    \expandafter\ifsetsucceed
-  \fi
-}
-\def\ifsetsucceed{\conditionalsucceed{ifset}}
-\def\ifsetfail{\nestedignore{ifset}}
-\defineunmatchedend{ifset}
-
-% @ifclear VAR ... @end ifclear reads the `...' iff VAR has never been
-% defined with @set, or has been undefined with @clear.
-%
-\def\ifclear{\parsearg\ifclearxxx}
-\def\ifclearxxx #1{%
-  \expandafter\ifx\csname SET#1\endcsname\relax
-    \expandafter\ifclearsucceed
-  \else
-    \expandafter\ifclearfail
-  \fi
-}
-\def\ifclearsucceed{\conditionalsucceed{ifclear}}
-\def\ifclearfail{\nestedignore{ifclear}}
-\defineunmatchedend{ifclear}
-
-% @iftex, @ifnothtml, @ifnotinfo always succeed; we read the text
-% following, through the first @end iftex (etc.).  Make `@end iftex'
-% (etc.) valid only after an @iftex.
-%
-\def\iftex{\conditionalsucceed{iftex}}
-\def\ifnothtml{\conditionalsucceed{ifnothtml}}
-\def\ifnotinfo{\conditionalsucceed{ifnotinfo}}
-\defineunmatchedend{iftex}
-\defineunmatchedend{ifnothtml}
-\defineunmatchedend{ifnotinfo}
-
-% We can't just want to start a group at @iftex (for example) and end it
-% at @end iftex, since then @set commands inside the conditional have no
-% effect (they'd get reverted at the end of the group).  So we must
-% define \Eiftex to redefine itself to be its previous value.  (We can't
-% just define it to fail again with an ``unmatched end'' error, since
-% the @ifset might be nested.)
-%
-\def\conditionalsucceed#1{%
-  \edef\temp{%
-    % Remember the current value of \E#1.
-    \let\nece{prevE#1} = \nece{E#1}%
-    %
-    % At the `@end #1', redefine \E#1 to be its previous value.
-    \def\nece{E#1}{\let\nece{E#1} = \nece{prevE#1}}%
-  }%
-  \temp
-}
-
-% We need to expand lots of \csname's, but we don't want to expand the
-% control sequences after we've constructed them.
-%
-\def\nece#1{\expandafter\noexpand\csname#1\endcsname}
-
-% @defininfoenclose.
-\let\definfoenclose=\comment
-
-
-\message{indexing,}
-% Index generation facilities
-
-% Define \newwrite to be identical to plain tex's \newwrite
-% except not \outer, so it can be used within \newindex.
-{\catcode`\@=11
-\gdef\newwrite{\alloc at 7\write\chardef\sixt@@n}}
-
-% \newindex {foo} defines an index named foo.
-% It automatically defines \fooindex such that
-% \fooindex ...rest of line... puts an entry in the index foo.
-% It also defines \fooindfile to be the number of the output channel for
-% the file that accumulates this index.  The file's extension is foo.
-% The name of an index should be no more than 2 characters long
-% for the sake of vms.
-%
-\def\newindex#1{%
-  \iflinks
-    \expandafter\newwrite \csname#1indfile\endcsname
-    \openout \csname#1indfile\endcsname \jobname.#1 % Open the file
-  \fi
-  \expandafter\xdef\csname#1index\endcsname{%     % Define @#1index
-    \noexpand\doindex{#1}}
-}
-
-% @defindex foo  ==  \newindex{foo}
-
-\def\defindex{\parsearg\newindex}
-
-% Define @defcodeindex, like @defindex except put all entries in @code.
-
-\def\newcodeindex#1{%
-  \iflinks
-    \expandafter\newwrite \csname#1indfile\endcsname
-    \openout \csname#1indfile\endcsname \jobname.#1
-  \fi
-  \expandafter\xdef\csname#1index\endcsname{%
-    \noexpand\docodeindex{#1}}
-}
-
-\def\defcodeindex{\parsearg\newcodeindex}
-
-% @synindex foo bar    makes index foo feed into index bar.
-% Do this instead of @defindex foo if you don't want it as a separate index.
-% The \closeout helps reduce unnecessary open files; the limit on the
-% Acorn RISC OS is a mere 16 files.
-\def\synindex#1 #2 {%
-  \expandafter\let\expandafter\synindexfoo\expandafter=\csname#2indfile\endcsname
-  \expandafter\closeout\csname#1indfile\endcsname
-  \expandafter\let\csname#1indfile\endcsname=\synindexfoo
-  \expandafter\xdef\csname#1index\endcsname{% define \xxxindex
-    \noexpand\doindex{#2}}%
-}
-
-% @syncodeindex foo bar   similar, but put all entries made for index foo
-% inside @code.
-\def\syncodeindex#1 #2 {%
-  \expandafter\let\expandafter\synindexfoo\expandafter=\csname#2indfile\endcsname
-  \expandafter\closeout\csname#1indfile\endcsname
-  \expandafter\let\csname#1indfile\endcsname=\synindexfoo
-  \expandafter\xdef\csname#1index\endcsname{% define \xxxindex
-    \noexpand\docodeindex{#2}}%
-}
-
-% Define \doindex, the driver for all \fooindex macros.
-% Argument #1 is generated by the calling \fooindex macro,
-%  and it is "foo", the name of the index.
-
-% \doindex just uses \parsearg; it calls \doind for the actual work.
-% This is because \doind is more useful to call from other macros.
-
-% There is also \dosubind {index}{topic}{subtopic}
-% which makes an entry in a two-level index such as the operation index.
-
-\def\doindex#1{\edef\indexname{#1}\parsearg\singleindexer}
-\def\singleindexer #1{\doind{\indexname}{#1}}
-
-% like the previous two, but they put @code around the argument.
-\def\docodeindex#1{\edef\indexname{#1}\parsearg\singlecodeindexer}
-\def\singlecodeindexer #1{\doind{\indexname}{\code{#1}}}
-
-\def\indexdummies{%
-\def\ { }%
-% Take care of the plain tex accent commands.
-\def\"{\realbackslash "}%
-\def\`{\realbackslash `}%
-\def\'{\realbackslash '}%
-\def\^{\realbackslash ^}%
-\def\~{\realbackslash ~}%
-\def\={\realbackslash =}%
-\def\b{\realbackslash b}%
-\def\c{\realbackslash c}%
-\def\d{\realbackslash d}%
-\def\u{\realbackslash u}%
-\def\v{\realbackslash v}%
-\def\H{\realbackslash H}%
-% Take care of the plain tex special European modified letters.
-\def\oe{\realbackslash oe}%
-\def\ae{\realbackslash ae}%
-\def\aa{\realbackslash aa}%
-\def\OE{\realbackslash OE}%
-\def\AE{\realbackslash AE}%
-\def\AA{\realbackslash AA}%
-\def\o{\realbackslash o}%
-\def\O{\realbackslash O}%
-\def\l{\realbackslash l}%
-\def\L{\realbackslash L}%
-\def\ss{\realbackslash ss}%
-% Take care of texinfo commands likely to appear in an index entry.
-% (Must be a way to avoid doing expansion at all, and thus not have to
-% laboriously list every single command here.)
-\def\@{@}% will be @@ when we switch to @ as escape char.
-% Need these in case \tex is in effect and \{ is a \delimiter again.
-% But can't use \lbracecmd and \rbracecmd because texindex assumes
-% braces and backslashes are used only as delimiters.  
-\let\{ = \mylbrace
-\let\} = \myrbrace
-\def\_{{\realbackslash _}}%
-\def\w{\realbackslash w }%
-\def\bf{\realbackslash bf }%
-%\def\rm{\realbackslash rm }%
-\def\sl{\realbackslash sl }%
-\def\sf{\realbackslash sf}%
-\def\tt{\realbackslash tt}%
-\def\gtr{\realbackslash gtr}%
-\def\less{\realbackslash less}%
-\def\hat{\realbackslash hat}%
-\def\TeX{\realbackslash TeX}%
-\def\dots{\realbackslash dots }%
-\def\result{\realbackslash result}%
-\def\equiv{\realbackslash equiv}%
-\def\expansion{\realbackslash expansion}%
-\def\print{\realbackslash print}%
-\def\error{\realbackslash error}%
-\def\point{\realbackslash point}%
-\def\copyright{\realbackslash copyright}%
-\def\tclose##1{\realbackslash tclose {##1}}%
-\def\code##1{\realbackslash code {##1}}%
-\def\uref##1{\realbackslash uref {##1}}%
-\def\url##1{\realbackslash url {##1}}%
-\def\env##1{\realbackslash env {##1}}%
-\def\command##1{\realbackslash command {##1}}%
-\def\option##1{\realbackslash option {##1}}%
-\def\dotless##1{\realbackslash dotless {##1}}%
-\def\samp##1{\realbackslash samp {##1}}%
-\def\,##1{\realbackslash ,{##1}}%
-\def\t##1{\realbackslash t {##1}}%
-\def\r##1{\realbackslash r {##1}}%
-\def\i##1{\realbackslash i {##1}}%
-\def\b##1{\realbackslash b {##1}}%
-\def\sc##1{\realbackslash sc {##1}}%
-\def\cite##1{\realbackslash cite {##1}}%
-\def\key##1{\realbackslash key {##1}}%
-\def\file##1{\realbackslash file {##1}}%
-\def\var##1{\realbackslash var {##1}}%
-\def\kbd##1{\realbackslash kbd {##1}}%
-\def\dfn##1{\realbackslash dfn {##1}}%
-\def\emph##1{\realbackslash emph {##1}}%
-\def\acronym##1{\realbackslash acronym {##1}}%
-%
-% Handle some cases of @value -- where the variable name does not
-% contain - or _, and the value does not contain any
-% (non-fully-expandable) commands.
-\let\value = \expandablevalue
-%
-\unsepspaces
-% Turn off macro expansion
-\turnoffmacros
-}
-
-% If an index command is used in an @example environment, any spaces
-% therein should become regular spaces in the raw index file, not the
-% expansion of \tie (\\leavevmode \penalty \@M \ ).
-{\obeyspaces
- \gdef\unsepspaces{\obeyspaces\let =\space}}
-
-% \indexnofonts no-ops all font-change commands.
-% This is used when outputting the strings to sort the index by.
-\def\indexdummyfont#1{#1}
-\def\indexdummytex{TeX}
-\def\indexdummydots{...}
-
-\def\indexnofonts{%
-% Just ignore accents.
-\let\,=\indexdummyfont
-\let\"=\indexdummyfont
-\let\`=\indexdummyfont
-\let\'=\indexdummyfont
-\let\^=\indexdummyfont
-\let\~=\indexdummyfont
-\let\==\indexdummyfont
-\let\b=\indexdummyfont
-\let\c=\indexdummyfont
-\let\d=\indexdummyfont
-\let\u=\indexdummyfont
-\let\v=\indexdummyfont
-\let\H=\indexdummyfont
-\let\dotless=\indexdummyfont
-% Take care of the plain tex special European modified letters.
-\def\oe{oe}%
-\def\ae{ae}%
-\def\aa{aa}%
-\def\OE{OE}%
-\def\AE{AE}%
-\def\AA{AA}%
-\def\o{o}%
-\def\O{O}%
-\def\l{l}%
-\def\L{L}%
-\def\ss{ss}%
-\let\w=\indexdummyfont
-\let\t=\indexdummyfont
-\let\r=\indexdummyfont
-\let\i=\indexdummyfont
-\let\b=\indexdummyfont
-\let\emph=\indexdummyfont
-\let\strong=\indexdummyfont
-\let\cite=\indexdummyfont
-\let\sc=\indexdummyfont
-%Don't no-op \tt, since it isn't a user-level command
-% and is used in the definitions of the active chars like <, >, |...
-%\let\tt=\indexdummyfont
-\let\tclose=\indexdummyfont
-\let\code=\indexdummyfont
-\let\url=\indexdummyfont
-\let\uref=\indexdummyfont
-\let\env=\indexdummyfont
-\let\acronym=\indexdummyfont
-\let\command=\indexdummyfont
-\let\option=\indexdummyfont
-\let\file=\indexdummyfont
-\let\samp=\indexdummyfont
-\let\kbd=\indexdummyfont
-\let\key=\indexdummyfont
-\let\var=\indexdummyfont
-\let\TeX=\indexdummytex
-\let\dots=\indexdummydots
-\def\@{@}%
-}
-
-% To define \realbackslash, we must make \ not be an escape.
-% We must first make another character (@) an escape
-% so we do not become unable to do a definition.
-
-{\catcode`\@=0 \catcode`\\=\other
- @gdef at realbackslash{\}}
-
-\let\indexbackslash=0  %overridden during \printindex.
-\let\SETmarginindex=\relax % put index entries in margin (undocumented)?
-
-% For \ifx comparisons.
-\def\emptymacro{\empty}
-
-% Most index entries go through here, but \dosubind is the general case.
-%
-\def\doind#1#2{\dosubind{#1}{#2}\empty}
-
-% Workhorse for all \fooindexes.
-% #1 is name of index, #2 is stuff to put there, #3 is subentry --
-% \empty if called from \doind, as we usually are.  The main exception
-% is with defuns, which call us directly.
-%
-\def\dosubind#1#2#3{%
-  % Put the index entry in the margin if desired.
-  \ifx\SETmarginindex\relax\else
-    \insert\margin{\hbox{\vrule height8pt depth3pt width0pt #2}}%
-  \fi
-  {%
-    \count255=\lastpenalty
-    {%
-      \indexdummies % Must do this here, since \bf, etc expand at this stage
-      \escapechar=`\\
-      {%
-        \let\folio = 0% We will expand all macros now EXCEPT \folio.
-        \def\rawbackslashxx{\indexbackslash}% \indexbackslash isn't defined now
-        % so it will be output as is; and it will print as backslash.
-        %
-        \def\thirdarg{#3}%
-        %
-        % If third arg is present, precede it with space in sort key.
-        \ifx\thirdarg\emptymacro
-          \let\subentry = \empty
-        \else
-          \def\subentry{ #3}%
-        \fi
-        %
-        % First process the index entry with all font commands turned
-        % off to get the string to sort by.
-        {\indexnofonts \xdef\indexsorttmp{#2\subentry}}%
-        %
-        % Now the real index entry with the fonts.
-        \toks0 = {#2}%
-        %
-        % If third (subentry) arg is present, add it to the index
-        % string.  And include a space.
-        \ifx\thirdarg\emptymacro \else
-          \toks0 = \expandafter{\the\toks0 \space #3}%
-        \fi
-        %
-        % Set up the complete index entry, with both the sort key
-        % and the original text, including any font commands.  We write
-        % three arguments to \entry to the .?? file, texindex reduces to
-        % two when writing the .??s sorted result.
-        \edef\temp{%
-          \write\csname#1indfile\endcsname{%
-            \realbackslash entry{\indexsorttmp}{\folio}{\the\toks0}}%
-        }%
-        %
-        % If a skip is the last thing on the list now, preserve it
-        % by backing up by \lastskip, doing the \write, then inserting
-        % the skip again.  Otherwise, the whatsit generated by the
-        % \write will make \lastskip zero.  The result is that sequences
-        % like this:
-        % @end defun
-        % @tindex whatever
-        % @defun ...
-        % will have extra space inserted, because the \medbreak in the
-        % start of the @defun won't see the skip inserted by the @end of
-        % the previous defun.
-        %
-        % But don't do any of this if we're not in vertical mode.  We
-        % don't want to do a \vskip and prematurely end a paragraph.
-        %
-        % Avoid page breaks due to these extra skips, too.
-        %
-        \iflinks
-          \ifvmode
-            \skip0 = \lastskip
-            \ifdim\lastskip = 0pt \else \nobreak\vskip-\lastskip \fi
-          \fi
-          %
-          \temp % do the write
-          %
-          %
-          \ifvmode \ifdim\skip0 = 0pt \else \nobreak\vskip\skip0 \fi \fi
-        \fi
-      }%
-    }%
-    \penalty\count255
-  }%
-}
-
-% The index entry written in the file actually looks like
-%  \entry {sortstring}{page}{topic}
-% or
-%  \entry {sortstring}{page}{topic}{subtopic}
-% The texindex program reads in these files and writes files
-% containing these kinds of lines:
-%  \initial {c}
-%     before the first topic whose initial is c
-%  \entry {topic}{pagelist}
-%     for a topic that is used without subtopics
-%  \primary {topic}
-%     for the beginning of a topic that is used with subtopics
-%  \secondary {subtopic}{pagelist}
-%     for each subtopic.
-
-% Define the user-accessible indexing commands
-% @findex, @vindex, @kindex, @cindex.
-
-\def\findex {\fnindex}
-\def\kindex {\kyindex}
-\def\cindex {\cpindex}
-\def\vindex {\vrindex}
-\def\tindex {\tpindex}
-\def\pindex {\pgindex}
-
-\def\cindexsub {\begingroup\obeylines\cindexsub}
-{\obeylines %
-\gdef\cindexsub "#1" #2^^M{\endgroup %
-\dosubind{cp}{#2}{#1}}}
-
-% Define the macros used in formatting output of the sorted index material.
-
-% @printindex causes a particular index (the ??s file) to get printed.
-% It does not print any chapter heading (usually an @unnumbered).
-%
-\def\printindex{\parsearg\doprintindex}
-\def\doprintindex#1{\begingroup
-  \dobreak \chapheadingskip{10000}%
-  %
-  \smallfonts \rm
-  \tolerance = 9500
-  \indexbreaks
-  %
-  % See if the index file exists and is nonempty.
-  % Change catcode of @ here so that if the index file contains
-  % \initial {@}
-  % as its first line, TeX doesn't complain about mismatched braces
-  % (because it thinks @} is a control sequence).
-  \catcode`\@ = 11
-  \openin 1 \jobname.#1s
-  \ifeof 1
-    % \enddoublecolumns gets confused if there is no text in the index,
-    % and it loses the chapter title and the aux file entries for the
-    % index.  The easiest way to prevent this problem is to make sure
-    % there is some text.
-    \putwordIndexNonexistent
-  \else
-    %
-    % If the index file exists but is empty, then \openin leaves \ifeof
-    % false.  We have to make TeX try to read something from the file, so
-    % it can discover if there is anything in it.
-    \read 1 to \temp
-    \ifeof 1
-      \putwordIndexIsEmpty
-    \else
-      % Index files are almost Texinfo source, but we use \ as the escape
-      % character.  It would be better to use @, but that's too big a change
-      % to make right now.
-      \def\indexbackslash{\rawbackslashxx}%
-      \catcode`\\ = 0
-      \escapechar = `\\
-      \begindoublecolumns
-      \input \jobname.#1s
-      \enddoublecolumns
-    \fi
-  \fi
-  \closein 1
-\endgroup}
-
-% These macros are used by the sorted index file itself.
-% Change them to control the appearance of the index.
-
-\def\initial#1{{%
-  % Some minor font changes for the special characters.
-  \let\tentt=\sectt \let\tt=\sectt \let\sf=\sectt
-  %
-  % Remove any glue we may have, we'll be inserting our own.
-  \removelastskip
-  %
-  % We like breaks before the index initials, so insert a bonus.
-  \penalty -300
-  %
-  % Typeset the initial.  Making this add up to a whole number of
-  % baselineskips increases the chance of the dots lining up from column
-  % to column.  It still won't often be perfect, because of the stretch
-  % we need before each entry, but it's better.
-  %
-  % No shrink because it confuses \balancecolumns.
-  \vskip 1.67\baselineskip plus .5\baselineskip
-  \leftline{\secbf #1}%
-  \vskip .33\baselineskip plus .1\baselineskip
-  %
-  % Do our best not to break after the initial.
-  \nobreak
-}}
-
-% This typesets a paragraph consisting of #1, dot leaders, and then #2
-% flush to the right margin.  It is used for index and table of contents
-% entries.  The paragraph is indented by \leftskip.
-%
-\def\entry#1#2{\begingroup
-  %
-  % Start a new paragraph if necessary, so our assignments below can't
-  % affect previous text.
-  \par
-  %
-  % Do not fill out the last line with white space.
-  \parfillskip = 0in
-  %
-  % No extra space above this paragraph.
-  \parskip = 0in
-  %
-  % Do not prefer a separate line ending with a hyphen to fewer lines.
-  \finalhyphendemerits = 0
-  %
-  % \hangindent is only relevant when the entry text and page number
-  % don't both fit on one line.  In that case, bob suggests starting the
-  % dots pretty far over on the line.  Unfortunately, a large
-  % indentation looks wrong when the entry text itself is broken across
-  % lines.  So we use a small indentation and put up with long leaders.
-  %
-  % \hangafter is reset to 1 (which is the value we want) at the start
-  % of each paragraph, so we need not do anything with that.
-  \hangindent = 2em
-  %
-  % When the entry text needs to be broken, just fill out the first line
-  % with blank space.
-  \rightskip = 0pt plus1fil
-  %
-  % A bit of stretch before each entry for the benefit of balancing columns.
-  \vskip 0pt plus1pt
-  %
-  % Start a ``paragraph'' for the index entry so the line breaking
-  % parameters we've set above will have an effect.
-  \noindent
-  %
-  % Insert the text of the index entry.  TeX will do line-breaking on it.
-  #1%
-  % The following is kludged to not output a line of dots in the index if
-  % there are no page numbers.  The next person who breaks this will be
-  % cursed by a Unix daemon.
-  \def\tempa{{\rm }}%
-  \def\tempb{#2}%
-  \edef\tempc{\tempa}%
-  \edef\tempd{\tempb}%
-  \ifx\tempc\tempd\ \else%
-    %
-    % If we must, put the page number on a line of its own, and fill out
-    % this line with blank space.  (The \hfil is overwhelmed with the
-    % fill leaders glue in \indexdotfill if the page number does fit.)
-    \hfil\penalty50
-    \null\nobreak\indexdotfill % Have leaders before the page number.
-    %
-    % The `\ ' here is removed by the implicit \unskip that TeX does as
-    % part of (the primitive) \par.  Without it, a spurious underfull
-    % \hbox ensues.
-    \ifpdf
-      \pdfgettoks#2.\ \the\toksA % The page number ends the paragraph.
-    \else
-      \ #2% The page number ends the paragraph.
-    \fi
-  \fi%
-  \par
-\endgroup}
-
-% Like \dotfill except takes at least 1 em.
-\def\indexdotfill{\cleaders
-  \hbox{$\mathsurround=0pt \mkern1.5mu ${\it .}$ \mkern1.5mu$}\hskip 1em plus 1fill}
-
-\def\primary #1{\line{#1\hfil}}
-
-\newskip\secondaryindent \secondaryindent=0.5cm
-
-\def\secondary #1#2{
-{\parfillskip=0in \parskip=0in
-\hangindent =1in \hangafter=1
-\noindent\hskip\secondaryindent\hbox{#1}\indexdotfill #2\par
-}}
-
-% Define two-column mode, which we use to typeset indexes.
-% Adapted from the TeXbook, page 416, which is to say,
-% the manmac.tex format used to print the TeXbook itself.
-\catcode`\@=11
-
-\newbox\partialpage
-\newdimen\doublecolumnhsize
-
-\def\begindoublecolumns{\begingroup % ended by \enddoublecolumns
-  % Grab any single-column material above us.
-  \output = {%
-    %
-    % Here is a possibility not foreseen in manmac: if we accumulate a
-    % whole lot of material, we might end up calling this \output
-    % routine twice in a row (see the doublecol-lose test, which is
-    % essentially a couple of indexes with @setchapternewpage off).  In
-    % that case we just ship out what is in \partialpage with the normal
-    % output routine.  Generally, \partialpage will be empty when this
-    % runs and this will be a no-op.  See the indexspread.tex test case.
-    \ifvoid\partialpage \else
-      \onepageout{\pagecontents\partialpage}%
-    \fi
-    %
-    \global\setbox\partialpage = \vbox{%
-      % Unvbox the main output page.
-      \unvbox\PAGE
-      \kern-\topskip \kern\baselineskip
-    }%
-  }%
-  \eject % run that output routine to set \partialpage
-  %
-  % Use the double-column output routine for subsequent pages.
-  \output = {\doublecolumnout}%
-  %
-  % Change the page size parameters.  We could do this once outside this
-  % routine, in each of @smallbook, @afourpaper, and the default 8.5x11
-  % format, but then we repeat the same computation.  Repeating a couple
-  % of assignments once per index is clearly meaningless for the
-  % execution time, so we may as well do it in one place.
-  %
-  % First we halve the line length, less a little for the gutter between
-  % the columns.  We compute the gutter based on the line length, so it
-  % changes automatically with the paper format.  The magic constant
-  % below is chosen so that the gutter has the same value (well, +-<1pt)
-  % as it did when we hard-coded it.
-  %
-  % We put the result in a separate register, \doublecolumhsize, so we
-  % can restore it in \pagesofar, after \hsize itself has (potentially)
-  % been clobbered.
-  %
-  \doublecolumnhsize = \hsize
-    \advance\doublecolumnhsize by -.04154\hsize
-    \divide\doublecolumnhsize by 2
-  \hsize = \doublecolumnhsize
-  %
-  % Double the \vsize as well.  (We don't need a separate register here,
-  % since nobody clobbers \vsize.)
-  \advance\vsize by -\ht\partialpage
-  \vsize = 2\vsize
-}
-
-% The double-column output routine for all double-column pages except
-% the last.
-%
-\def\doublecolumnout{%
-  \splittopskip=\topskip \splitmaxdepth=\maxdepth
-  % Get the available space for the double columns -- the normal
-  % (undoubled) page height minus any material left over from the
-  % previous page.
-  \dimen@ = \vsize
-  \divide\dimen@ by 2
-  %
-  % box0 will be the left-hand column, box2 the right.
-  \setbox0=\vsplit255 to\dimen@ \setbox2=\vsplit255 to\dimen@
-  \onepageout\pagesofar
-  \unvbox255
-  \penalty\outputpenalty
-}
-\def\pagesofar{%
-  % Re-output the contents of the output page -- any previous material,
-  % followed by the two boxes we just split, in box0 and box2.
-  \unvbox\partialpage
-  %
-  \hsize = \doublecolumnhsize
-  \wd0=\hsize \wd2=\hsize
-  \hbox to\pagewidth{\box0\hfil\box2}%
-}
-\def\enddoublecolumns{%
-  \output = {%
-    % Split the last of the double-column material.  Leave it on the
-    % current page, no automatic page break.
-    \balancecolumns
-    %
-    % If we end up splitting too much material for the current page,
-    % though, there will be another page break right after this \output
-    % invocation ends.  Having called \balancecolumns once, we do not
-    % want to call it again.  Therefore, reset \output to its normal
-    % definition right away.  (We hope \balancecolumns will never be
-    % called on to balance too much material, but if it is, this makes
-    % the output somewhat more palatable.)
-    \global\output = {\onepageout{\pagecontents\PAGE}}%
-  }%
-  \eject
-  \endgroup % started in \begindoublecolumns
-  %
-  % \pagegoal was set to the doubled \vsize above, since we restarted
-  % the current page.  We're now back to normal single-column
-  % typesetting, so reset \pagegoal to the normal \vsize (after the
-  % \endgroup where \vsize got restored).
-  \pagegoal = \vsize
-}
-\def\balancecolumns{%
-  % Called at the end of the double column material.
-  \setbox0 = \vbox{\unvbox255}% like \box255 but more efficient, see p.120.
-  \dimen@ = \ht0
-  \advance\dimen@ by \topskip
-  \advance\dimen@ by-\baselineskip
-  \divide\dimen@ by 2 % target to split to
-  %debug\message{final 2-column material height=\the\ht0, target=\the\dimen at .}%
-  \splittopskip = \topskip
-  % Loop until we get a decent breakpoint.
-  {%
-    \vbadness = 10000
-    \loop
-      \global\setbox3 = \copy0
-      \global\setbox1 = \vsplit3 to \dimen@
-    \ifdim\ht3>\dimen@
-      \global\advance\dimen@ by 1pt
-    \repeat
-  }%
-  %debug\message{split to \the\dimen@, column heights: \the\ht1, \the\ht3.}%
-  \setbox0=\vbox to\dimen@{\unvbox1}%
-  \setbox2=\vbox to\dimen@{\unvbox3}%
-  %
-  \pagesofar
-}
-\catcode`\@ = \other
-
-
-\message{sectioning,}
-% Chapters, sections, etc.
-
-\newcount\chapno
-\newcount\secno        \secno=0
-\newcount\subsecno     \subsecno=0
-\newcount\subsubsecno  \subsubsecno=0
-
-% This counter is funny since it counts through charcodes of letters A, B, ...
-\newcount\appendixno  \appendixno = `\@
-% \def\appendixletter{\char\the\appendixno}
-% We do the following for the sake of pdftex, which needs the actual
-% letter in the expansion, not just typeset.
-\def\appendixletter{%
-  \ifnum\appendixno=`A A%
-  \else\ifnum\appendixno=`B B%
-  \else\ifnum\appendixno=`C C%
-  \else\ifnum\appendixno=`D D%
-  \else\ifnum\appendixno=`E E%
-  \else\ifnum\appendixno=`F F%
-  \else\ifnum\appendixno=`G G%
-  \else\ifnum\appendixno=`H H%
-  \else\ifnum\appendixno=`I I%
-  \else\ifnum\appendixno=`J J%
-  \else\ifnum\appendixno=`K K%
-  \else\ifnum\appendixno=`L L%
-  \else\ifnum\appendixno=`M M%
-  \else\ifnum\appendixno=`N N%
-  \else\ifnum\appendixno=`O O%
-  \else\ifnum\appendixno=`P P%
-  \else\ifnum\appendixno=`Q Q%
-  \else\ifnum\appendixno=`R R%
-  \else\ifnum\appendixno=`S S%
-  \else\ifnum\appendixno=`T T%
-  \else\ifnum\appendixno=`U U%
-  \else\ifnum\appendixno=`V V%
-  \else\ifnum\appendixno=`W W%
-  \else\ifnum\appendixno=`X X%
-  \else\ifnum\appendixno=`Y Y%
-  \else\ifnum\appendixno=`Z Z%
-  % The \the is necessary, despite appearances, because \appendixletter is
-  % expanded while writing the .toc file.  \char\appendixno is not
-  % expandable, thus it is written literally, thus all appendixes come out
-  % with the same letter (or @) in the toc without it.
-  \else\char\the\appendixno
-  \fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi
-  \fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi\fi}
-
-% Each @chapter defines this as the name of the chapter.
-% page headings and footings can use it.  @section does likewise.
-\def\thischapter{}
-\def\thissection{}
-
-\newcount\absseclevel % used to calculate proper heading level
-\newcount\secbase\secbase=0 % @raise/lowersections modify this count
-
-% @raisesections: treat @section as chapter, @subsection as section, etc.
-\def\raisesections{\global\advance\secbase by -1}
-\let\up=\raisesections % original BFox name
-
-% @lowersections: treat @chapter as section, @section as subsection, etc.
-\def\lowersections{\global\advance\secbase by 1}
-\let\down=\lowersections % original BFox name
-
-% Choose a numbered-heading macro
-% #1 is heading level if unmodified by @raisesections or @lowersections
-% #2 is text for heading
-\def\numhead#1#2{\absseclevel=\secbase\advance\absseclevel by #1
-\ifcase\absseclevel
-  \chapterzzz{#2}
-\or
-  \seczzz{#2}
-\or
-  \numberedsubseczzz{#2}
-\or
-  \numberedsubsubseczzz{#2}
-\else
-  \ifnum \absseclevel<0
-    \chapterzzz{#2}
-  \else
-    \numberedsubsubseczzz{#2}
-  \fi
-\fi
-}
-
-% like \numhead, but chooses appendix heading levels
-\def\apphead#1#2{\absseclevel=\secbase\advance\absseclevel by #1
-\ifcase\absseclevel
-  \appendixzzz{#2}
-\or
-  \appendixsectionzzz{#2}
-\or
-  \appendixsubseczzz{#2}
-\or
-  \appendixsubsubseczzz{#2}
-\else
-  \ifnum \absseclevel<0
-    \appendixzzz{#2}
-  \else
-    \appendixsubsubseczzz{#2}
-  \fi
-\fi
-}
-
-% like \numhead, but chooses numberless heading levels
-\def\unnmhead#1#2{\absseclevel=\secbase\advance\absseclevel by #1
-\ifcase\absseclevel
-  \unnumberedzzz{#2}
-\or
-  \unnumberedseczzz{#2}
-\or
-  \unnumberedsubseczzz{#2}
-\or
-  \unnumberedsubsubseczzz{#2}
-\else
-  \ifnum \absseclevel<0
-    \unnumberedzzz{#2}
-  \else
-    \unnumberedsubsubseczzz{#2}
-  \fi
-\fi
-}
-
-% @chapter, @appendix, @unnumbered.
-\def\thischaptername{No Chapter Title}
-\outer\def\chapter{\parsearg\chapteryyy}
-\def\chapteryyy #1{\numhead0{#1}} % normally numhead0 calls chapterzzz
-\def\chapterzzz #1{%
-\secno=0 \subsecno=0 \subsubsecno=0
-\global\advance \chapno by 1 \message{\putwordChapter\space \the\chapno}%
-\chapmacro {#1}{\the\chapno}%
-\gdef\thissection{#1}%
-\gdef\thischaptername{#1}%
-% We don't substitute the actual chapter name into \thischapter
-% because we don't want its macros evaluated now.
-\xdef\thischapter{\putwordChapter{} \the\chapno: \noexpand\thischaptername}%
-\toks0 = {#1}%
-\edef\temp{\noexpand\writetocentry{\realbackslash chapentry{\the\toks0}%
-                                  {\the\chapno}}}%
-\temp
-\donoderef
-\global\let\section = \numberedsec
-\global\let\subsection = \numberedsubsec
-\global\let\subsubsection = \numberedsubsubsec
-}
-
-\outer\def\appendix{\parsearg\appendixyyy}
-\def\appendixyyy #1{\apphead0{#1}} % normally apphead0 calls appendixzzz
-\def\appendixzzz #1{%
-\secno=0 \subsecno=0 \subsubsecno=0
-\global\advance \appendixno by 1
-\message{\putwordAppendix\space \appendixletter}%
-\chapmacro {#1}{\putwordAppendix{} \appendixletter}%
-\gdef\thissection{#1}%
-\gdef\thischaptername{#1}%
-\xdef\thischapter{\putwordAppendix{} \appendixletter: \noexpand\thischaptername}%
-\toks0 = {#1}%
-\edef\temp{\noexpand\writetocentry{\realbackslash chapentry{\the\toks0}%
-                       {\putwordAppendix{} \appendixletter}}}%
-\temp
-\appendixnoderef
-\global\let\section = \appendixsec
-\global\let\subsection = \appendixsubsec
-\global\let\subsubsection = \appendixsubsubsec
-}
-
-% @centerchap is like @unnumbered, but the heading is centered.
-\outer\def\centerchap{\parsearg\centerchapyyy}
-\def\centerchapyyy #1{{\let\unnumbchapmacro=\centerchapmacro \unnumberedyyy{#1}}}
-
-% @top is like @unnumbered.
-\outer\def\top{\parsearg\unnumberedyyy}
-
-\outer\def\unnumbered{\parsearg\unnumberedyyy}
-\def\unnumberedyyy #1{\unnmhead0{#1}} % normally unnmhead0 calls unnumberedzzz
-\def\unnumberedzzz #1{%
-\secno=0 \subsecno=0 \subsubsecno=0
-%
-% This used to be simply \message{#1}, but TeX fully expands the
-% argument to \message.  Therefore, if #1 contained @-commands, TeX
-% expanded them.  For example, in `@unnumbered The @cite{Book}', TeX
-% expanded @cite (which turns out to cause errors because \cite is meant
-% to be executed, not expanded).
-%
-% Anyway, we don't want the fully-expanded definition of @cite to appear
-% as a result of the \message, we just want `@cite' itself.  We use
-% \the<toks register> to achieve this: TeX expands \the<toks> only once,
-% simply yielding the contents of <toks register>.  (We also do this for
-% the toc entries.)
-\toks0 = {#1}\message{(\the\toks0)}%
-%
-\unnumbchapmacro {#1}%
-\gdef\thischapter{#1}\gdef\thissection{#1}%
-\toks0 = {#1}%
-\edef\temp{\noexpand\writetocentry{\realbackslash unnumbchapentry{\the\toks0}}}%
-\temp
-\unnumbnoderef
-\global\let\section = \unnumberedsec
-\global\let\subsection = \unnumberedsubsec
-\global\let\subsubsection = \unnumberedsubsubsec
-}
-
-% Sections.
-\outer\def\numberedsec{\parsearg\secyyy}
-\def\secyyy #1{\numhead1{#1}} % normally calls seczzz
-\def\seczzz #1{%
-\subsecno=0 \subsubsecno=0 \global\advance \secno by 1 %
-\gdef\thissection{#1}\secheading {#1}{\the\chapno}{\the\secno}%
-\toks0 = {#1}%
-\edef\temp{\noexpand\writetocentry{\realbackslash secentry{\the\toks0}%
-                                  {\the\chapno}{\the\secno}}}%
-\temp
-\donoderef
-\nobreak
-}
-
-\outer\def\appendixsection{\parsearg\appendixsecyyy}
-\outer\def\appendixsec{\parsearg\appendixsecyyy}
-\def\appendixsecyyy #1{\apphead1{#1}} % normally calls appendixsectionzzz
-\def\appendixsectionzzz #1{%
-\subsecno=0 \subsubsecno=0 \global\advance \secno by 1 %
-\gdef\thissection{#1}\secheading {#1}{\appendixletter}{\the\secno}%
-\toks0 = {#1}%
-\edef\temp{\noexpand\writetocentry{\realbackslash secentry{\the\toks0}%
-                                  {\appendixletter}{\the\secno}}}%
-\temp
-\appendixnoderef
-\nobreak
-}
-
-\outer\def\unnumberedsec{\parsearg\unnumberedsecyyy}
-\def\unnumberedsecyyy #1{\unnmhead1{#1}} % normally calls unnumberedseczzz
-\def\unnumberedseczzz #1{%
-\plainsecheading {#1}\gdef\thissection{#1}%
-\toks0 = {#1}%
-\edef\temp{\noexpand\writetocentry{\realbackslash unnumbsecentry{\the\toks0}}}%
-\temp
-\unnumbnoderef
-\nobreak
-}
-
-% Subsections.
-\outer\def\numberedsubsec{\parsearg\numberedsubsecyyy}
-\def\numberedsubsecyyy #1{\numhead2{#1}} % normally calls numberedsubseczzz
-\def\numberedsubseczzz #1{%
-\gdef\thissection{#1}\subsubsecno=0 \global\advance \subsecno by 1 %
-\subsecheading {#1}{\the\chapno}{\the\secno}{\the\subsecno}%
-\toks0 = {#1}%
-\edef\temp{\noexpand\writetocentry{\realbackslash subsecentry{\the\toks0}%
-                                    {\the\chapno}{\the\secno}{\the\subsecno}}}%
-\temp
-\donoderef
-\nobreak
-}
-
-\outer\def\appendixsubsec{\parsearg\appendixsubsecyyy}
-\def\appendixsubsecyyy #1{\apphead2{#1}} % normally calls appendixsubseczzz
-\def\appendixsubseczzz #1{%
-\gdef\thissection{#1}\subsubsecno=0 \global\advance \subsecno by 1 %
-\subsecheading {#1}{\appendixletter}{\the\secno}{\the\subsecno}%
-\toks0 = {#1}%
-\edef\temp{\noexpand\writetocentry{\realbackslash subsecentry{\the\toks0}%
-                                {\appendixletter}{\the\secno}{\the\subsecno}}}%
-\temp
-\appendixnoderef
-\nobreak
-}
-
-\outer\def\unnumberedsubsec{\parsearg\unnumberedsubsecyyy}
-\def\unnumberedsubsecyyy #1{\unnmhead2{#1}} %normally calls unnumberedsubseczzz
-\def\unnumberedsubseczzz #1{%
-\plainsubsecheading {#1}\gdef\thissection{#1}%
-\toks0 = {#1}%
-\edef\temp{\noexpand\writetocentry{\realbackslash unnumbsubsecentry%
-                                    {\the\toks0}}}%
-\temp
-\unnumbnoderef
-\nobreak
-}
-
-% Subsubsections.
-\outer\def\numberedsubsubsec{\parsearg\numberedsubsubsecyyy}
-\def\numberedsubsubsecyyy #1{\numhead3{#1}} % normally numberedsubsubseczzz
-\def\numberedsubsubseczzz #1{%
-\gdef\thissection{#1}\global\advance \subsubsecno by 1 %
-\subsubsecheading {#1}
-  {\the\chapno}{\the\secno}{\the\subsecno}{\the\subsubsecno}%
-\toks0 = {#1}%
-\edef\temp{\noexpand\writetocentry{\realbackslash subsubsecentry{\the\toks0}%
-  {\the\chapno}{\the\secno}{\the\subsecno}{\the\subsubsecno}}}%
-\temp
-\donoderef
-\nobreak
-}
-
-\outer\def\appendixsubsubsec{\parsearg\appendixsubsubsecyyy}
-\def\appendixsubsubsecyyy #1{\apphead3{#1}} % normally appendixsubsubseczzz
-\def\appendixsubsubseczzz #1{%
-\gdef\thissection{#1}\global\advance \subsubsecno by 1 %
-\subsubsecheading {#1}
-  {\appendixletter}{\the\secno}{\the\subsecno}{\the\subsubsecno}%
-\toks0 = {#1}%
-\edef\temp{\noexpand\writetocentry{\realbackslash subsubsecentry{\the\toks0}%
-  {\appendixletter}{\the\secno}{\the\subsecno}{\the\subsubsecno}}}%
-\temp
-\appendixnoderef
-\nobreak
-}
-
-\outer\def\unnumberedsubsubsec{\parsearg\unnumberedsubsubsecyyy}
-\def\unnumberedsubsubsecyyy #1{\unnmhead3{#1}} %normally unnumberedsubsubseczzz
-\def\unnumberedsubsubseczzz #1{%
-\plainsubsubsecheading {#1}\gdef\thissection{#1}%
-\toks0 = {#1}%
-\edef\temp{\noexpand\writetocentry{\realbackslash unnumbsubsubsecentry%
-                                    {\the\toks0}}}%
-\temp
-\unnumbnoderef
-\nobreak
-}
-
-% These are variants which are not "outer", so they can appear in @ifinfo.
-% Actually, they should now be obsolete; ordinary section commands should work.
-\def\infotop{\parsearg\unnumberedzzz}
-\def\infounnumbered{\parsearg\unnumberedzzz}
-\def\infounnumberedsec{\parsearg\unnumberedseczzz}
-\def\infounnumberedsubsec{\parsearg\unnumberedsubseczzz}
-\def\infounnumberedsubsubsec{\parsearg\unnumberedsubsubseczzz}
-
-\def\infoappendix{\parsearg\appendixzzz}
-\def\infoappendixsec{\parsearg\appendixseczzz}
-\def\infoappendixsubsec{\parsearg\appendixsubseczzz}
-\def\infoappendixsubsubsec{\parsearg\appendixsubsubseczzz}
-
-\def\infochapter{\parsearg\chapterzzz}
-\def\infosection{\parsearg\sectionzzz}
-\def\infosubsection{\parsearg\subsectionzzz}
-\def\infosubsubsection{\parsearg\subsubsectionzzz}
-
-% These macros control what the section commands do, according
-% to what kind of chapter we are in (ordinary, appendix, or unnumbered).
-% Define them by default for a numbered chapter.
-\global\let\section = \numberedsec
-\global\let\subsection = \numberedsubsec
-\global\let\subsubsection = \numberedsubsubsec
-
-% Define @majorheading, @heading and @subheading
-
-% NOTE on use of \vbox for chapter headings, section headings, and such:
-%       1) We use \vbox rather than the earlier \line to permit
-%          overlong headings to fold.
-%       2) \hyphenpenalty is set to 10000 because hyphenation in a
-%          heading is obnoxious; this forbids it.
-%       3) Likewise, headings look best if no \parindent is used, and
-%          if justification is not attempted.  Hence \raggedright.
-
-
-\def\majorheading{\parsearg\majorheadingzzz}
-\def\majorheadingzzz #1{%
-{\advance\chapheadingskip by 10pt \chapbreak }%
-{\chapfonts \vbox{\hyphenpenalty=10000\tolerance=5000
-                  \parindent=0pt\raggedright
-                  \rm #1\hfill}}\bigskip \par\penalty 200}
-
-\def\chapheading{\parsearg\chapheadingzzz}
-\def\chapheadingzzz #1{\chapbreak %
-{\chapfonts \vbox{\hyphenpenalty=10000\tolerance=5000
-                  \parindent=0pt\raggedright
-                  \rm #1\hfill}}\bigskip \par\penalty 200}
-
-% @heading, @subheading, @subsubheading.
-\def\heading{\parsearg\plainsecheading}
-\def\subheading{\parsearg\plainsubsecheading}
-\def\subsubheading{\parsearg\plainsubsubsecheading}
-
-% These macros generate a chapter, section, etc. heading only
-% (including whitespace, linebreaking, etc. around it),
-% given all the information in convenient, parsed form.
-
-%%% Args are the skip and penalty (usually negative)
-\def\dobreak#1#2{\par\ifdim\lastskip<#1\removelastskip\penalty#2\vskip#1\fi}
-
-\def\setchapterstyle #1 {\csname CHAPF#1\endcsname}
-
-%%% Define plain chapter starts, and page on/off switching for it
-% Parameter controlling skip before chapter headings (if needed)
-
-\newskip\chapheadingskip
-
-\def\chapbreak{\dobreak \chapheadingskip {-4000}}
-\def\chappager{\par\vfill\supereject}
-\def\chapoddpage{\chappager \ifodd\pageno \else \hbox to 0pt{} \chappager\fi}
-
-\def\setchapternewpage #1 {\csname CHAPPAG#1\endcsname}
-
-\def\CHAPPAGoff{%
-\global\let\contentsalignmacro = \chappager
-\global\let\pchapsepmacro=\chapbreak
-\global\let\pagealignmacro=\chappager}
-
-\def\CHAPPAGon{%
-\global\let\contentsalignmacro = \chappager
-\global\let\pchapsepmacro=\chappager
-\global\let\pagealignmacro=\chappager
-\global\def\HEADINGSon{\HEADINGSsingle}}
-
-\def\CHAPPAGodd{
-\global\let\contentsalignmacro = \chapoddpage
-\global\let\pchapsepmacro=\chapoddpage
-\global\let\pagealignmacro=\chapoddpage
-\global\def\HEADINGSon{\HEADINGSdouble}}
-
-\CHAPPAGon
-
-\def\CHAPFplain{
-\global\let\chapmacro=\chfplain
-\global\let\unnumbchapmacro=\unnchfplain
-\global\let\centerchapmacro=\centerchfplain}
-
-% Plain chapter opening.
-% #1 is the text, #2 the chapter number or empty if unnumbered.
-\def\chfplain#1#2{%
-  \pchapsepmacro
-  {%
-    \chapfonts \rm
-    \def\chapnum{#2}%
-    \setbox0 = \hbox{#2\ifx\chapnum\empty\else\enspace\fi}%
-    \vbox{\hyphenpenalty=10000 \tolerance=5000 \parindent=0pt \raggedright
-          \hangindent = \wd0 \centerparametersmaybe
-          \unhbox0 #1\par}%
-  }%
-  \nobreak\bigskip % no page break after a chapter title
-  \nobreak
-}
-
-% Plain opening for unnumbered.
-\def\unnchfplain#1{\chfplain{#1}{}}
-
-% @centerchap -- centered and unnumbered.
-\let\centerparametersmaybe = \relax
-\def\centerchfplain#1{{%
-  \def\centerparametersmaybe{%
-    \advance\rightskip by 3\rightskip
-    \leftskip = \rightskip
-    \parfillskip = 0pt
-  }%
-  \chfplain{#1}{}%
-}}
-
-\CHAPFplain % The default
-
-\def\unnchfopen #1{%
-\chapoddpage {\chapfonts \vbox{\hyphenpenalty=10000\tolerance=5000
-                       \parindent=0pt\raggedright
-                       \rm #1\hfill}}\bigskip \par\nobreak
-}
-
-\def\chfopen #1#2{\chapoddpage {\chapfonts
-\vbox to 3in{\vfil \hbox to\hsize{\hfil #2} \hbox to\hsize{\hfil #1} \vfil}}%
-\par\penalty 5000 %
-}
-
-\def\centerchfopen #1{%
-\chapoddpage {\chapfonts \vbox{\hyphenpenalty=10000\tolerance=5000
-                       \parindent=0pt
-                       \hfill {\rm #1}\hfill}}\bigskip \par\nobreak
-}
-
-\def\CHAPFopen{
-\global\let\chapmacro=\chfopen
-\global\let\unnumbchapmacro=\unnchfopen
-\global\let\centerchapmacro=\centerchfopen}
-
-
-% Section titles.
-\newskip\secheadingskip
-\def\secheadingbreak{\dobreak \secheadingskip {-1000}}
-\def\secheading#1#2#3{\sectionheading{sec}{#2.#3}{#1}}
-\def\plainsecheading#1{\sectionheading{sec}{}{#1}}
-
-% Subsection titles.
-\newskip \subsecheadingskip
-\def\subsecheadingbreak{\dobreak \subsecheadingskip {-500}}
-\def\subsecheading#1#2#3#4{\sectionheading{subsec}{#2.#3.#4}{#1}}
-\def\plainsubsecheading#1{\sectionheading{subsec}{}{#1}}
-
-% Subsubsection titles.
-\let\subsubsecheadingskip = \subsecheadingskip
-\let\subsubsecheadingbreak = \subsecheadingbreak
-\def\subsubsecheading#1#2#3#4#5{\sectionheading{subsubsec}{#2.#3.#4.#5}{#1}}
-\def\plainsubsubsecheading#1{\sectionheading{subsubsec}{}{#1}}
-
-
-% Print any size section title.
-%
-% #1 is the section type (sec/subsec/subsubsec), #2 is the section
-% number (maybe empty), #3 the text.
-\def\sectionheading#1#2#3{%
-  {%
-    \expandafter\advance\csname #1headingskip\endcsname by \parskip
-    \csname #1headingbreak\endcsname
-  }%
-  {%
-    % Switch to the right set of fonts.
-    \csname #1fonts\endcsname \rm
-    %
-    % Only insert the separating space if we have a section number.
-    \def\secnum{#2}%
-    \setbox0 = \hbox{#2\ifx\secnum\empty\else\enspace\fi}%
-    %
-    \vbox{\hyphenpenalty=10000 \tolerance=5000 \parindent=0pt \raggedright
-          \hangindent = \wd0 % zero if no section number
-          \unhbox0 #3}%
-  }%
-  \ifdim\parskip<10pt \nobreak\kern10pt\nobreak\kern-\parskip\fi \nobreak
-}
-
-
-\message{toc,}
-% Table of contents.
-\newwrite\tocfile
-
-% Write an entry to the toc file, opening it if necessary.
-% Called from @chapter, etc.  We supply {\folio} at the end of the
-% argument, which will end up as the last argument to the \...entry macro.
-%
-% We open the .toc file here instead of at @setfilename or any other
-% given time so that @contents can be put in the document anywhere.
-%
-\newif\iftocfileopened
-\def\writetocentry#1{%
-  \iftocfileopened\else
-    \immediate\openout\tocfile = \jobname.toc
-    \global\tocfileopenedtrue
-  \fi
-  \iflinks \write\tocfile{#1{\folio}}\fi
-}
-
-\newskip\contentsrightmargin \contentsrightmargin=1in
-\newcount\savepageno
-\newcount\lastnegativepageno \lastnegativepageno = -1
-
-% Finish up the main text and prepare to read what we've written
-% to \tocfile.
-%
-\def\startcontents#1{%
-   % If @setchapternewpage on, and @headings double, the contents should
-   % start on an odd page, unlike chapters.  Thus, we maintain
-   % \contentsalignmacro in parallel with \pagealignmacro.
-   % From: Torbjorn Granlund <tege at matematik.su.se>
-   \contentsalignmacro
-   \immediate\closeout\tocfile
-   %
-   % Don't need to put `Contents' or `Short Contents' in the headline.
-   % It is abundantly clear what they are.
-   \unnumbchapmacro{#1}\def\thischapter{}%
-   \savepageno = \pageno
-   \begingroup                  % Set up to handle contents files properly.
-      \catcode`\\=0  \catcode`\{=1  \catcode`\}=2  \catcode`\@=11
-      % We can't do this, because then an actual ^ in a section
-      % title fails, e.g., @chapter ^ -- exponentiation.  --karl, 9jul97.
-      %\catcode`\^=7 % to see ^^e4 as \"a etc. juha at piuha.ydi.vtt.fi
-      \raggedbottom             % Worry more about breakpoints than the bottom.
-      \advance\hsize by -\contentsrightmargin % Don't use the full line length.
-      %
-      % Roman numerals for page numbers.
-      \ifnum \pageno>0 \pageno = \lastnegativepageno \fi
-}
-
-
-% Normal (long) toc.
-\def\contents{%
-   \startcontents{\putwordTOC}%
-     \openin 1 \jobname.toc
-     \ifeof 1 \else
-       \closein 1
-       \input \jobname.toc
-     \fi
-     \vfill \eject
-     \contentsalignmacro % in case @setchapternewpage odd is in effect
-     \pdfmakeoutlines
-   \endgroup
-   \lastnegativepageno = \pageno
-   \pageno = \savepageno
-}
-
-% And just the chapters.
-\def\summarycontents{%
-   \startcontents{\putwordShortTOC}%
-      %
-      \let\chapentry = \shortchapentry
-      \let\unnumbchapentry = \shortunnumberedentry
-      % We want a true roman here for the page numbers.
-      \secfonts
-      \let\rm=\shortcontrm \let\bf=\shortcontbf \let\sl=\shortcontsl
-      \rm
-      \hyphenpenalty = 10000
-      \advance\baselineskip by 1pt % Open it up a little.
-      \def\secentry ##1##2##3##4{}
-      \def\unnumbsecentry ##1##2{}
-      \def\subsecentry ##1##2##3##4##5{}
-      \def\unnumbsubsecentry ##1##2{}
-      \def\subsubsecentry ##1##2##3##4##5##6{}
-      \def\unnumbsubsubsecentry ##1##2{}
-      \openin 1 \jobname.toc
-      \ifeof 1 \else
-        \closein 1
-        \input \jobname.toc
-      \fi
-     \vfill \eject
-     \contentsalignmacro % in case @setchapternewpage odd is in effect
-   \endgroup
-   \lastnegativepageno = \pageno
-   \pageno = \savepageno
-}
-\let\shortcontents = \summarycontents
-
-\ifpdf
-  \pdfcatalog{/PageMode /UseOutlines}%
-\fi
-
-% These macros generate individual entries in the table of contents.
-% The first argument is the chapter or section name.
-% The last argument is the page number.
-% The arguments in between are the chapter number, section number, ...
-
-% Chapter-level things, for both the long and short contents.
-\def\chapentry#1#2#3{\dochapentry{#2\labelspace#1}{#3}}
-
-% See comments in \dochapentry re vbox and related settings
-\def\shortchapentry#1#2#3{%
-  \tocentry{\shortchaplabel{#2}\labelspace #1}{\doshortpageno\bgroup#3\egroup}%
-}
-
-% Typeset the label for a chapter or appendix for the short contents.
-% The arg is, e.g. `Appendix A' for an appendix, or `3' for a chapter.
-% We could simplify the code here by writing out an \appendixentry
-% command in the toc file for appendices, instead of using \chapentry
-% for both, but it doesn't seem worth it.
-%
-\newdimen\shortappendixwidth
-%
-\def\shortchaplabel#1{%
-  % Compute width of word "Appendix", may change with language.
-  \setbox0 = \hbox{\shortcontrm \putwordAppendix}%
-  \shortappendixwidth = \wd0
-  %
-  % We typeset #1 in a box of constant width, regardless of the text of
-  % #1, so the chapter titles will come out aligned.
-  \setbox0 = \hbox{#1}%
-  \dimen0 = \ifdim\wd0 > \shortappendixwidth \shortappendixwidth \else 0pt \fi
-  %
-  % This space should be plenty, since a single number is .5em, and the
-  % widest letter (M) is 1em, at least in the Computer Modern fonts.
-  % (This space doesn't include the extra space that gets added after
-  % the label; that gets put in by \shortchapentry above.)
-  \advance\dimen0 by 1.1em
-  \hbox to \dimen0{#1\hfil}%
-}
-
-\def\unnumbchapentry#1#2{\dochapentry{#1}{#2}}
-\def\shortunnumberedentry#1#2{\tocentry{#1}{\doshortpageno\bgroup#2\egroup}}
-
-% Sections.
-\def\secentry#1#2#3#4{\dosecentry{#2.#3\labelspace#1}{#4}}
-\def\unnumbsecentry#1#2{\dosecentry{#1}{#2}}
-
-% Subsections.
-\def\subsecentry#1#2#3#4#5{\dosubsecentry{#2.#3.#4\labelspace#1}{#5}}
-\def\unnumbsubsecentry#1#2{\dosubsecentry{#1}{#2}}
-
-% And subsubsections.
-\def\subsubsecentry#1#2#3#4#5#6{%
-  \dosubsubsecentry{#2.#3.#4.#5\labelspace#1}{#6}}
-\def\unnumbsubsubsecentry#1#2{\dosubsubsecentry{#1}{#2}}
-
-% This parameter controls the indentation of the various levels.
-\newdimen\tocindent \tocindent = 3pc
-
-% Now for the actual typesetting. In all these, #1 is the text and #2 is the
-% page number.
-%
-% If the toc has to be broken over pages, we want it to be at chapters
-% if at all possible; hence the \penalty.
-\def\dochapentry#1#2{%
-   \penalty-300 \vskip1\baselineskip plus.33\baselineskip minus.25\baselineskip
-   \begingroup
-     \chapentryfonts
-     \tocentry{#1}{\dopageno\bgroup#2\egroup}%
-   \endgroup
-   \nobreak\vskip .25\baselineskip plus.1\baselineskip
-}
-
-\def\dosecentry#1#2{\begingroup
-  \secentryfonts \leftskip=\tocindent
-  \tocentry{#1}{\dopageno\bgroup#2\egroup}%
-\endgroup}
-
-\def\dosubsecentry#1#2{\begingroup
-  \subsecentryfonts \leftskip=2\tocindent
-  \tocentry{#1}{\dopageno\bgroup#2\egroup}%
-\endgroup}
-
-\def\dosubsubsecentry#1#2{\begingroup
-  \subsubsecentryfonts \leftskip=3\tocindent
-  \tocentry{#1}{\dopageno\bgroup#2\egroup}%
-\endgroup}
-
-% Final typesetting of a toc entry; we use the same \entry macro as for
-% the index entries, but we want to suppress hyphenation here.  (We
-% can't do that in the \entry macro, since index entries might consist
-% of hyphenated-identifiers-that-do-not-fit-on-a-line-and-nothing-else.)
-\def\tocentry#1#2{\begingroup
-  \vskip 0pt plus1pt % allow a little stretch for the sake of nice page breaks
-  % Do not use \turnoffactive in these arguments.  Since the toc is
-  % typeset in cmr, so characters such as _ would come out wrong; we
-  % have to do the usual translation tricks.
-  \entry{#1}{#2}%
-\endgroup}
-
-% Space between chapter (or whatever) number and the title.
-\def\labelspace{\hskip1em \relax}
-
-\def\dopageno#1{{\rm #1}}
-\def\doshortpageno#1{{\rm #1}}
-
-\def\chapentryfonts{\secfonts \rm}
-\def\secentryfonts{\textfonts}
-\let\subsecentryfonts = \textfonts
-\let\subsubsecentryfonts = \textfonts
-
-
-\message{environments,}
-% @foo ... @end foo.
-
-% Since these characters are used in examples, it should be an even number of
-% \tt widths. Each \tt character is 1en, so two makes it 1em.
-% Furthermore, these definitions must come after we define our fonts.
-\newbox\dblarrowbox    \newbox\longdblarrowbox
-\newbox\pushcharbox    \newbox\bullbox
-\newbox\equivbox       \newbox\errorbox
-
-%{\tentt
-%\global\setbox\dblarrowbox = \hbox to 1em{\hfil$\Rightarrow$\hfil}
-%\global\setbox\longdblarrowbox = \hbox to 1em{\hfil$\mapsto$\hfil}
-%\global\setbox\pushcharbox = \hbox to 1em{\hfil$\dashv$\hfil}
-%\global\setbox\equivbox = \hbox to 1em{\hfil$\ptexequiv$\hfil}
-% Adapted from the manmac format (p.420 of TeXbook)
-%\global\setbox\bullbox = \hbox to 1em{\kern.15em\vrule height .75ex width .85ex
-%                                      depth .1ex\hfil}
-%}
-
-% @point{}, @result{}, @expansion{}, @print{}, @equiv{}.
-\def\point{$\star$}
-\def\result{\leavevmode\raise.15ex\hbox to 1em{\hfil$\Rightarrow$\hfil}}
-\def\expansion{\leavevmode\raise.1ex\hbox to 1em{\hfil$\mapsto$\hfil}}
-\def\print{\leavevmode\lower.1ex\hbox to 1em{\hfil$\dashv$\hfil}}
-\def\equiv{\leavevmode\lower.1ex\hbox to 1em{\hfil$\ptexequiv$\hfil}}
-
-% Adapted from the TeXbook's \boxit.
-{\tentt \global\dimen0 = 3em}% Width of the box.
-\dimen2 = .55pt % Thickness of rules
-% The text. (`r' is open on the right, `e' somewhat less so on the left.)
-\setbox0 = \hbox{\kern-.75pt \tensf error\kern-1.5pt}
-
-\global\setbox\errorbox=\hbox to \dimen0{\hfil
-   \hsize = \dimen0 \advance\hsize by -5.8pt % Space to left+right.
-   \advance\hsize by -2\dimen2 % Rules.
-   \vbox{
-      \hrule height\dimen2
-      \hbox{\vrule width\dimen2 \kern3pt          % Space to left of text.
-         \vtop{\kern2.4pt \box0 \kern2.4pt}% Space above/below.
-         \kern3pt\vrule width\dimen2}% Space to right.
-      \hrule height\dimen2}
-    \hfil}
-
-% The @error{} command.
-\def\error{\leavevmode\lower.7ex\copy\errorbox}
-
-% @tex ... @end tex    escapes into raw Tex temporarily.
-% One exception: @ is still an escape character, so that @end tex works.
-% But \@ or @@ will get a plain tex @ character.
-
-\def\tex{\begingroup
-  \catcode `\\=0 \catcode `\{=1 \catcode `\}=2
-  \catcode `\$=3 \catcode `\&=4 \catcode `\#=6
-  \catcode `\^=7 \catcode `\_=8 \catcode `\~=13 \let~=\tie
-  \catcode `\%=14
-  \catcode 43=12 % plus
-  \catcode`\"=12
-  \catcode`\==12
-  \catcode`\|=12
-  \catcode`\<=12
-  \catcode`\>=12
-  \escapechar=`\\
-  %
-  \let\b=\ptexb
-  \let\bullet=\ptexbullet
-  \let\c=\ptexc
-  \let\,=\ptexcomma
-  \let\.=\ptexdot
-  \let\dots=\ptexdots
-  \let\equiv=\ptexequiv
-  \let\!=\ptexexclam
-  \let\i=\ptexi
-  \let\{=\ptexlbrace
-  \let\+=\tabalign
-  \let\}=\ptexrbrace
-  \let\*=\ptexstar
-  \let\t=\ptext
-  %
-  \def\endldots{\mathinner{\ldots\ldots\ldots\ldots}}%
-  \def\enddots{\relax\ifmmode\endldots\else$\mathsurround=0pt \endldots\,$\fi}%
-  \def\@{@}%
-\let\Etex=\endgroup}
-
-% Define @lisp ... @endlisp.
-% @lisp does a \begingroup so it can rebind things,
-% including the definition of @endlisp (which normally is erroneous).
-
-% Amount to narrow the margins by for @lisp.
-\newskip\lispnarrowing \lispnarrowing=0.4in
-
-% This is the definition that ^^M gets inside @lisp, @example, and other
-% such environments.  \null is better than a space, since it doesn't
-% have any width.
-\def\lisppar{\null\endgraf}
-
-% Make each space character in the input produce a normal interword
-% space in the output.  Don't allow a line break at this space, as this
-% is used only in environments like @example, where each line of input
-% should produce a line of output anyway.
-%
-{\obeyspaces %
-\gdef\sepspaces{\obeyspaces\let =\tie}}
-
-% Define \obeyedspace to be our active space, whatever it is.  This is
-% for use in \parsearg.
-{\sepspaces%
-\global\let\obeyedspace= }
-
-% This space is always present above and below environments.
-\newskip\envskipamount \envskipamount = 0pt
-
-% Make spacing and below environment symmetrical.  We use \parskip here
-% to help in doing that, since in @example-like environments \parskip
-% is reset to zero; thus the \afterenvbreak inserts no space -- but the
-% start of the next paragraph will insert \parskip
-%
-\def\aboveenvbreak{{\advance\envskipamount by \parskip
-\endgraf \ifdim\lastskip<\envskipamount
-\removelastskip \penalty-50 \vskip\envskipamount \fi}}
-
-\let\afterenvbreak = \aboveenvbreak
-
-% \nonarrowing is a flag.  If "set", @lisp etc don't narrow margins.
-\let\nonarrowing=\relax
-
-% @cartouche ... @end cartouche: draw rectangle w/rounded corners around
-% environment contents.
-\font\circle=lcircle10
-\newdimen\circthick
-\newdimen\cartouter\newdimen\cartinner
-\newskip\normbskip\newskip\normpskip\newskip\normlskip
-\circthick=\fontdimen8\circle
-%
-\def\ctl{{\circle\char'013\hskip -6pt}}% 6pt from pl file: 1/2charwidth
-\def\ctr{{\hskip 6pt\circle\char'010}}
-\def\cbl{{\circle\char'012\hskip -6pt}}
-\def\cbr{{\hskip 6pt\circle\char'011}}
-\def\carttop{\hbox to \cartouter{\hskip\lskip
-        \ctl\leaders\hrule height\circthick\hfil\ctr
-        \hskip\rskip}}
-\def\cartbot{\hbox to \cartouter{\hskip\lskip
-        \cbl\leaders\hrule height\circthick\hfil\cbr
-        \hskip\rskip}}
-%
-\newskip\lskip\newskip\rskip
-
-\long\def\cartouche{%
-\begingroup
-        \lskip=\leftskip \rskip=\rightskip
-        \leftskip=0pt\rightskip=0pt %we want these *outside*.
-        \cartinner=\hsize \advance\cartinner by-\lskip
-                          \advance\cartinner by-\rskip
-        \cartouter=\hsize
-        \advance\cartouter by 18.4pt % allow for 3pt kerns on either
-%                                    side, and for 6pt waste from
-%                                    each corner char, and rule thickness
-        \normbskip=\baselineskip \normpskip=\parskip \normlskip=\lineskip
-        % Flag to tell @lisp, etc., not to narrow margin.
-        \let\nonarrowing=\comment
-        \vbox\bgroup
-                \baselineskip=0pt\parskip=0pt\lineskip=0pt
-                \carttop
-                \hbox\bgroup
-                        \hskip\lskip
-                        \vrule\kern3pt
-                        \vbox\bgroup
-                                \hsize=\cartinner
-                                \kern3pt
-                                \begingroup
-                                        \baselineskip=\normbskip
-                                        \lineskip=\normlskip
-                                        \parskip=\normpskip
-                                        \vskip -\parskip
-\def\Ecartouche{%
-                                \endgroup
-                                \kern3pt
-                        \egroup
-                        \kern3pt\vrule
-                        \hskip\rskip
-                \egroup
-                \cartbot
-        \egroup
-\endgroup
-}}
-
-
-% This macro is called at the beginning of all the @example variants,
-% inside a group.
-\def\nonfillstart{%
-  \aboveenvbreak
-  \inENV % This group ends at the end of the body
-  \hfuzz = 12pt % Don't be fussy
-  \sepspaces % Make spaces be word-separators rather than space tokens.
-  \singlespace
-  \let\par = \lisppar % don't ignore blank lines
-  \obeylines % each line of input is a line of output
-  \parskip = 0pt
-  \parindent = 0pt
-  \emergencystretch = 0pt % don't try to avoid overfull boxes
-  % @cartouche defines \nonarrowing to inhibit narrowing
-  % at next level down.
-  \ifx\nonarrowing\relax
-    \advance \leftskip by \lispnarrowing
-    \exdentamount=\lispnarrowing
-    \let\exdent=\nofillexdent
-    \let\nonarrowing=\relax
-  \fi
-}
-
-% Define the \E... control sequence only if we are inside the particular
-% environment, so the error checking in \end will work.
-%
-% To end an @example-like environment, we first end the paragraph (via
-% \afterenvbreak's vertical glue), and then the group.  That way we keep
-% the zero \parskip that the environments set -- \parskip glue will be
-% inserted at the beginning of the next paragraph in the document, after
-% the environment.
-%
-\def\nonfillfinish{\afterenvbreak\endgroup}
-
-% @lisp: indented, narrowed, typewriter font.
-\def\lisp{\begingroup
-  \nonfillstart
-  \let\Elisp = \nonfillfinish
-  \tt
-  \let\kbdfont = \kbdexamplefont % Allow @kbd to do something special.
-  \gobble       % eat return
-}
-
-% @example: Same as @lisp.
-\def\example{\begingroup \def\Eexample{\nonfillfinish\endgroup}\lisp}
-
-% @small... is usually equivalent to the non-small (@smallbook
-% redefines).  We must call \example (or whatever) last in the
-% definition, since it reads the return following the @example (or
-% whatever) command.
-%
-% This actually allows (for example) @end display inside an
-% @smalldisplay.  Too bad, but makeinfo will catch the error anyway.
-%
-\def\smalldisplay{\begingroup\def\Esmalldisplay{\nonfillfinish\endgroup}\display}
-\def\smallexample{\begingroup\def\Esmallexample{\nonfillfinish\endgroup}\lisp}
-\def\smallformat{\begingroup\def\Esmallformat{\nonfillfinish\endgroup}\format}
-\def\smalllisp{\begingroup\def\Esmalllisp{\nonfillfinish\endgroup}\lisp}
-
-% Real @smallexample and @smalllisp (when @smallbook): use smaller fonts.
-% Originally contributed by Pavel at xerox.
-\def\smalllispx{\begingroup
-  \def\Esmalllisp{\nonfillfinish\endgroup}%
-  \def\Esmallexample{\nonfillfinish\endgroup}%
-  \smallfonts
-  \lisp
-}
-
-% @display: same as @lisp except keep current font.
-%
-\def\display{\begingroup
-  \nonfillstart
-  \let\Edisplay = \nonfillfinish
-  \gobble
-}
-
-% @smalldisplay (when @smallbook): @display plus smaller fonts.
-%
-\def\smalldisplayx{\begingroup
-  \def\Esmalldisplay{\nonfillfinish\endgroup}%
-  \smallfonts \rm
-  \display
-}
-
-% @format: same as @display except don't narrow margins.
-%
-\def\format{\begingroup
-  \let\nonarrowing = t
-  \nonfillstart
-  \let\Eformat = \nonfillfinish
-  \gobble
-}
-
-% @smallformat (when @smallbook): @format plus smaller fonts.
-%
-\def\smallformatx{\begingroup
-  \def\Esmallformat{\nonfillfinish\endgroup}%
-  \smallfonts \rm
-  \format
-}
-
-% @flushleft (same as @format).
-%
-\def\flushleft{\begingroup \def\Eflushleft{\nonfillfinish\endgroup}\format}
-
-% @flushright.
-%
-\def\flushright{\begingroup
-  \let\nonarrowing = t
-  \nonfillstart
-  \let\Eflushright = \nonfillfinish
-  \advance\leftskip by 0pt plus 1fill
-  \gobble
-}
-
-% @quotation does normal linebreaking (hence we can't use \nonfillstart)
-% and narrows the margins.
-%
-\def\quotation{%
-  \begingroup\inENV %This group ends at the end of the @quotation body
-  {\parskip=0pt \aboveenvbreak}% because \aboveenvbreak inserts \parskip
-  \singlespace
-  \parindent=0pt
-  % We have retained a nonzero parskip for the environment, since we're
-  % doing normal filling. So to avoid extra space below the environment...
-  \def\Equotation{\parskip = 0pt \nonfillfinish}%
-  %
-  % @cartouche defines \nonarrowing to inhibit narrowing at next level down.
-  \ifx\nonarrowing\relax
-    \advance\leftskip by \lispnarrowing
-    \advance\rightskip by \lispnarrowing
-    \exdentamount = \lispnarrowing
-    \let\nonarrowing = \relax
-  \fi
-}
-
-
-\message{defuns,}
-% @defun etc.
-
-% Allow user to change definition object font (\df) internally
-\def\setdeffont #1 {\csname DEF#1\endcsname}
-
-\newskip\defbodyindent \defbodyindent=.4in
-\newskip\defargsindent \defargsindent=50pt
-\newskip\deftypemargin \deftypemargin=12pt
-\newskip\deflastargmargin \deflastargmargin=18pt
-
-\newcount\parencount
-% define \functionparens, which makes ( and ) and & do special things.
-% \functionparens affects the group it is contained in.
-\def\activeparens{%
-\catcode`\(=\active \catcode`\)=\active \catcode`\&=\active
-\catcode`\[=\active \catcode`\]=\active}
-
-% Make control sequences which act like normal parenthesis chars.
-\let\lparen = ( \let\rparen = )
-
-{\activeparens % Now, smart parens don't turn on until &foo (see \amprm)
-
-% Be sure that we always have a definition for `(', etc.  For example,
-% if the fn name has parens in it, \boldbrax will not be in effect yet,
-% so TeX would otherwise complain about undefined control sequence.
-\global\let(=\lparen \global\let)=\rparen
-\global\let[=\lbrack \global\let]=\rbrack
-
-\gdef\functionparens{\boldbrax\let&=\amprm\parencount=0 }
-\gdef\boldbrax{\let(=\opnr\let)=\clnr\let[=\lbrb\let]=\rbrb}
-% This is used to turn on special parens
-% but make & act ordinary (given that it's active).
-\gdef\boldbraxnoamp{\let(=\opnr\let)=\clnr\let[=\lbrb\let]=\rbrb\let&=\ampnr}
-
-% Definitions of (, ) and & used in args for functions.
-% This is the definition of ( outside of all parentheses.
-\gdef\oprm#1 {{\rm\char`\(}#1 \bf \let(=\opnested
-  \global\advance\parencount by 1
-}
-%
-% This is the definition of ( when already inside a level of parens.
-\gdef\opnested{\char`\(\global\advance\parencount by 1 }
-%
-\gdef\clrm{% Print a paren in roman if it is taking us back to depth of 0.
-  % also in that case restore the outer-level definition of (.
-  \ifnum \parencount=1 {\rm \char `\)}\sl \let(=\oprm \else \char `\) \fi
-  \global\advance \parencount by -1 }
-% If we encounter &foo, then turn on ()-hacking afterwards
-\gdef\amprm#1 {{\rm\&#1}\let(=\oprm \let)=\clrm\ }
-%
-\gdef\normalparens{\boldbrax\let&=\ampnr}
-} % End of definition inside \activeparens
-%% These parens (in \boldbrax) actually are a little bolder than the
-%% contained text.  This is especially needed for [ and ]
-\def\opnr{{\sf\char`\(}\global\advance\parencount by 1 }
-\def\clnr{{\sf\char`\)}\global\advance\parencount by -1 }
-\let\ampnr = \&
-\def\lbrb{{\bf\char`\[}}
-\def\rbrb{{\bf\char`\]}}
-
-% Active &'s sneak into the index arguments, so make sure it's defined.
-{
-  \catcode`& = 13
-  \global\let& = \ampnr
-}
-
-% First, defname, which formats the header line itself.
-% #1 should be the function name.
-% #2 should be the type of definition, such as "Function".
-
-\def\defname #1#2{%
-% Get the values of \leftskip and \rightskip as they were
-% outside the @def...
-\dimen2=\leftskip
-\advance\dimen2 by -\defbodyindent
-\noindent
-\setbox0=\hbox{\hskip \deflastargmargin{\rm #2}\hskip \deftypemargin}%
-\dimen0=\hsize \advance \dimen0 by -\wd0 % compute size for first line
-\dimen1=\hsize \advance \dimen1 by -\defargsindent %size for continuations
-\parshape 2 0in \dimen0 \defargsindent \dimen1
-% Now output arg 2 ("Function" or some such)
-% ending at \deftypemargin from the right margin,
-% but stuck inside a box of width 0 so it does not interfere with linebreaking
-{% Adjust \hsize to exclude the ambient margins,
-% so that \rightline will obey them.
-\advance \hsize by -\dimen2
-\rlap{\rightline{{\rm #2}\hskip -1.25pc }}}%
-% Make all lines underfull and no complaints:
-\tolerance=10000 \hbadness=10000
-\advance\leftskip by -\defbodyindent
-\exdentamount=\defbodyindent
-{\df #1}\enskip        % Generate function name
-}
-
-% Actually process the body of a definition
-% #1 should be the terminating control sequence, such as \Edefun.
-% #2 should be the "another name" control sequence, such as \defunx.
-% #3 should be the control sequence that actually processes the header,
-%    such as \defunheader.
-
-\def\defparsebody #1#2#3{\begingroup\inENV% Environment for definitionbody
-\medbreak %
-% Define the end token that this defining construct specifies
-% so that it will exit this group.
-\def#1{\endgraf\endgroup\medbreak}%
-\def#2{\begingroup\obeylines\activeparens\spacesplit#3}%
-\parindent=0in
-\advance\leftskip by \defbodyindent
-\exdentamount=\defbodyindent
-\begingroup %
-\catcode 61=\active % 61 is `='
-\obeylines\activeparens\spacesplit#3}
-
-% #1 is the \E... control sequence to end the definition (which we define).
-% #2 is the \...x control sequence for consecutive fns (which we define).
-% #3 is the control sequence to call to resume processing.
-% #4, delimited by the space, is the class name.
-%
-\def\defmethparsebody#1#2#3#4 {\begingroup\inENV %
-\medbreak %
-% Define the end token that this defining construct specifies
-% so that it will exit this group.
-\def#1{\endgraf\endgroup\medbreak}%
-\def#2##1 {\begingroup\obeylines\activeparens\spacesplit{#3{##1}}}%
-\parindent=0in
-\advance\leftskip by \defbodyindent
-\exdentamount=\defbodyindent
-\begingroup\obeylines\activeparens\spacesplit{#3{#4}}}
-
-% Used for @deftypemethod and @deftypeivar.
-% #1 is the \E... control sequence to end the definition (which we define).
-% #2 is the \...x control sequence for consecutive fns (which we define).
-% #3 is the control sequence to call to resume processing.
-% #4, delimited by a space, is the class name.
-% #5 is the method's return type.
-%
-\def\deftypemethparsebody#1#2#3#4 #5 {\begingroup\inENV
-  \medbreak
-  \def#1{\endgraf\endgroup\medbreak}%
-  \def#2##1 ##2 {\begingroup\obeylines\activeparens\spacesplit{#3{##1}{##2}}}%
-  \parindent=0in
-  \advance\leftskip by \defbodyindent
-  \exdentamount=\defbodyindent
-  \begingroup\obeylines\activeparens\spacesplit{#3{#4}{#5}}}
-
-% Used for @deftypeop.  The change from \deftypemethparsebody is an
-% extra argument at the beginning which is the `category', instead of it
-% being the hardwired string `Method' or `Instance Variable'.  We have
-% to account for this both in the \...x definition and in parsing the
-% input at hand.  Thus also need a control sequence (passed as #5) for
-% the \E... definition to assign the category name to.
-% 
-\def\deftypeopparsebody#1#2#3#4#5 #6 {\begingroup\inENV
-  \medbreak
-  \def#1{\endgraf\endgroup\medbreak}%
-  \def#2##1 ##2 ##3 {%
-    \def#4{##1}%
-    \begingroup\obeylines\activeparens\spacesplit{#3{##2}{##3}}}%
-  \parindent=0in
-  \advance\leftskip by \defbodyindent
-  \exdentamount=\defbodyindent
-  \begingroup\obeylines\activeparens\spacesplit{#3{#5}{#6}}}
-
-\def\defopparsebody #1#2#3#4#5 {\begingroup\inENV %
-\medbreak %
-% Define the end token that this defining construct specifies
-% so that it will exit this group.
-\def#1{\endgraf\endgroup\medbreak}%
-\def#2##1 ##2 {\def#4{##1}%
-\begingroup\obeylines\activeparens\spacesplit{#3{##2}}}%
-\parindent=0in
-\advance\leftskip by \defbodyindent
-\exdentamount=\defbodyindent
-\begingroup\obeylines\activeparens\spacesplit{#3{#5}}}
-
-% These parsing functions are similar to the preceding ones
-% except that they do not make parens into active characters.
-% These are used for "variables" since they have no arguments.
-
-\def\defvarparsebody #1#2#3{\begingroup\inENV% Environment for definitionbody
-\medbreak %
-% Define the end token that this defining construct specifies
-% so that it will exit this group.
-\def#1{\endgraf\endgroup\medbreak}%
-\def#2{\begingroup\obeylines\spacesplit#3}%
-\parindent=0in
-\advance\leftskip by \defbodyindent
-\exdentamount=\defbodyindent
-\begingroup %
-\catcode 61=\active %
-\obeylines\spacesplit#3}
-
-% This is used for \def{tp,vr}parsebody.  It could probably be used for
-% some of the others, too, with some judicious conditionals.
-%
-\def\parsebodycommon#1#2#3{%
-  \begingroup\inENV %
-  \medbreak %
-  % Define the end token that this defining construct specifies
-  % so that it will exit this group.
-  \def#1{\endgraf\endgroup\medbreak}%
-  \def#2##1 {\begingroup\obeylines\spacesplit{#3{##1}}}%
-  \parindent=0in
-  \advance\leftskip by \defbodyindent
-  \exdentamount=\defbodyindent
-  \begingroup\obeylines
-}
-
-\def\defvrparsebody#1#2#3#4 {%
-  \parsebodycommon{#1}{#2}{#3}%
-  \spacesplit{#3{#4}}%
-}
-
-% This loses on `@deftp {Data Type} {struct termios}' -- it thinks the
-% type is just `struct', because we lose the braces in `{struct
-% termios}' when \spacesplit reads its undelimited argument.  Sigh.
-% \let\deftpparsebody=\defvrparsebody
-%
-% So, to get around this, we put \empty in with the type name.  That
-% way, TeX won't find exactly `{...}' as an undelimited argument, and
-% won't strip off the braces.
-%
-\def\deftpparsebody #1#2#3#4 {%
-  \parsebodycommon{#1}{#2}{#3}%
-  \spacesplit{\parsetpheaderline{#3{#4}}}\empty
-}
-
-% Fine, but then we have to eventually remove the \empty *and* the
-% braces (if any).  That's what this does.
-%
-\def\removeemptybraces\empty#1\relax{#1}
-
-% After \spacesplit has done its work, this is called -- #1 is the final
-% thing to call, #2 the type name (which starts with \empty), and #3
-% (which might be empty) the arguments.
-%
-\def\parsetpheaderline#1#2#3{%
-  #1{\removeemptybraces#2\relax}{#3}%
-}%
-
-\def\defopvarparsebody #1#2#3#4#5 {\begingroup\inENV %
-\medbreak %
-% Define the end token that this defining construct specifies
-% so that it will exit this group.
-\def#1{\endgraf\endgroup\medbreak}%
-\def#2##1 ##2 {\def#4{##1}%
-\begingroup\obeylines\spacesplit{#3{##2}}}%
-\parindent=0in
-\advance\leftskip by \defbodyindent
-\exdentamount=\defbodyindent
-\begingroup\obeylines\spacesplit{#3{#5}}}
-
-% Split up #2 at the first space token.
-% call #1 with two arguments:
-%  the first is all of #2 before the space token,
-%  the second is all of #2 after that space token.
-% If #2 contains no space token, all of it is passed as the first arg
-% and the second is passed as empty.
-
-{\obeylines
-\gdef\spacesplit#1#2^^M{\endgroup\spacesplitfoo{#1}#2 \relax\spacesplitfoo}%
-\long\gdef\spacesplitfoo#1#2 #3#4\spacesplitfoo{%
-\ifx\relax #3%
-#1{#2}{}\else #1{#2}{#3#4}\fi}}
-
-% So much for the things common to all kinds of definitions.
-
-% Define @defun.
-
-% First, define the processing that is wanted for arguments of \defun
-% Use this to expand the args and terminate the paragraph they make up
-
-\def\defunargs#1{\functionparens \sl
-% Expand, preventing hyphenation at `-' chars.
-% Note that groups don't affect changes in \hyphenchar.
-% Set the font temporarily and use \font in case \setfont made \tensl a macro.
-{\tensl\hyphenchar\font=0}%
-#1%
-{\tensl\hyphenchar\font=45}%
-\ifnum\parencount=0 \else \errmessage{Unbalanced parentheses in @def}\fi%
-\interlinepenalty=10000
-\advance\rightskip by 0pt plus 1fil
-\endgraf\nobreak\vskip -\parskip\nobreak
-}
-
-\def\deftypefunargs #1{%
-% Expand, preventing hyphenation at `-' chars.
-% Note that groups don't affect changes in \hyphenchar.
-% Use \boldbraxnoamp, not \functionparens, so that & is not special.
-\boldbraxnoamp
-\tclose{#1}% avoid \code because of side effects on active chars
-\interlinepenalty=10000
-\advance\rightskip by 0pt plus 1fil
-\endgraf\nobreak\vskip -\parskip\nobreak
-}
-
-% Do complete processing of one @defun or @defunx line already parsed.
-
-% @deffn Command forward-char nchars
-
-\def\deffn{\defmethparsebody\Edeffn\deffnx\deffnheader}
-
-\def\deffnheader #1#2#3{\doind {fn}{\code{#2}}%
-\begingroup\defname {#2}{#1}\defunargs{#3}\endgroup %
-\catcode 61=\other % Turn off change made in \defparsebody
-}
-
-% @defun == @deffn Function
-
-\def\defun{\defparsebody\Edefun\defunx\defunheader}
-
-\def\defunheader #1#2{\doind {fn}{\code{#1}}% Make entry in function index
-\begingroup\defname {#1}{\putwordDeffunc}%
-\defunargs {#2}\endgroup %
-\catcode 61=\other % Turn off change made in \defparsebody
-}
-
-% @deftypefun int foobar (int @var{foo}, float @var{bar})
-
-\def\deftypefun{\defparsebody\Edeftypefun\deftypefunx\deftypefunheader}
-
-% #1 is the data type.  #2 is the name and args.
-\def\deftypefunheader #1#2{\deftypefunheaderx{#1}#2 \relax}
-% #1 is the data type, #2 the name, #3 the args.
-\def\deftypefunheaderx #1#2 #3\relax{%
-\doind {fn}{\code{#2}}% Make entry in function index
-\begingroup\defname {\defheaderxcond#1\relax$$$#2}{\putwordDeftypefun}%
-\deftypefunargs {#3}\endgroup %
-\catcode 61=\other % Turn off change made in \defparsebody
-}
-
-% @deftypefn {Library Function} int foobar (int @var{foo}, float @var{bar})
-
-\def\deftypefn{\defmethparsebody\Edeftypefn\deftypefnx\deftypefnheader}
-
-% \defheaderxcond#1\relax$$$
-% puts #1 in @code, followed by a space, but does nothing if #1 is null.
-\def\defheaderxcond#1#2$$${\ifx#1\relax\else\code{#1#2} \fi}
-
-% #1 is the classification.  #2 is the data type.  #3 is the name and args.
-\def\deftypefnheader #1#2#3{\deftypefnheaderx{#1}{#2}#3 \relax}
-% #1 is the classification, #2 the data type, #3 the name, #4 the args.
-\def\deftypefnheaderx #1#2#3 #4\relax{%
-\doind {fn}{\code{#3}}% Make entry in function index
-\begingroup
-\normalparens % notably, turn off `&' magic, which prevents
-%               at least some C++ text from working
-\defname {\defheaderxcond#2\relax$$$#3}{#1}%
-\deftypefunargs {#4}\endgroup %
-\catcode 61=\other % Turn off change made in \defparsebody
-}
-
-% @defmac == @deffn Macro
-
-\def\defmac{\defparsebody\Edefmac\defmacx\defmacheader}
-
-\def\defmacheader #1#2{\doind {fn}{\code{#1}}% Make entry in function index
-\begingroup\defname {#1}{\putwordDefmac}%
-\defunargs {#2}\endgroup %
-\catcode 61=\other % Turn off change made in \defparsebody
-}
-
-% @defspec == @deffn Special Form
-
-\def\defspec{\defparsebody\Edefspec\defspecx\defspecheader}
-
-\def\defspecheader #1#2{\doind {fn}{\code{#1}}% Make entry in function index
-\begingroup\defname {#1}{\putwordDefspec}%
-\defunargs {#2}\endgroup %
-\catcode 61=\other % Turn off change made in \defparsebody
-}
-
-% @defop CATEGORY CLASS OPERATION ARG...
-%
-\def\defop #1 {\def\defoptype{#1}%
-\defopparsebody\Edefop\defopx\defopheader\defoptype}
-%
-\def\defopheader#1#2#3{%
-\dosubind {fn}{\code{#2}}{\putwordon\ #1}% Make entry in function index
-\begingroup\defname {#2}{\defoptype\ \putwordon\ #1}%
-\defunargs {#3}\endgroup %
-}
-
-% @deftypeop CATEGORY CLASS TYPE OPERATION ARG...
-%
-\def\deftypeop #1 {\def\deftypeopcategory{#1}%
-  \deftypeopparsebody\Edeftypeop\deftypeopx\deftypeopheader
-                       \deftypeopcategory}
-%
-% #1 is the class name, #2 the data type, #3 the operation name, #4 the args.
-\def\deftypeopheader#1#2#3#4{%
-  \dosubind{fn}{\code{#3}}{\putwordon\ \code{#1}}% entry in function index
-  \begingroup
-    \defname{\defheaderxcond#2\relax$$$#3}
-            {\deftypeopcategory\ \putwordon\ \code{#1}}%
-    \deftypefunargs{#4}%
-  \endgroup
-}
-
-% @deftypemethod CLASS TYPE METHOD ARG...
-%
-\def\deftypemethod{%
-  \deftypemethparsebody\Edeftypemethod\deftypemethodx\deftypemethodheader}
-%
-% #1 is the class name, #2 the data type, #3 the method name, #4 the args.
-\def\deftypemethodheader#1#2#3#4{%
-  \dosubind{fn}{\code{#3}}{\putwordon\ \code{#1}}% entry in function index
-  \begingroup
-    \defname{\defheaderxcond#2\relax$$$#3}{\putwordMethodon\ \code{#1}}%
-    \deftypefunargs{#4}%
-  \endgroup
-}
-
-% @deftypeivar CLASS TYPE VARNAME
-%
-\def\deftypeivar{%
-  \deftypemethparsebody\Edeftypeivar\deftypeivarx\deftypeivarheader}
-%
-% #1 is the class name, #2 the data type, #3 the variable name.
-\def\deftypeivarheader#1#2#3{%
-  \dosubind{vr}{\code{#3}}{\putwordof\ \code{#1}}% entry in variable index
-  \begingroup
-    \defname{\defheaderxcond#2\relax$$$#3}
-            {\putwordInstanceVariableof\ \code{#1}}%
-    \defvarargs{#3}%
-  \endgroup
-}
-
-% @defmethod == @defop Method
-%
-\def\defmethod{\defmethparsebody\Edefmethod\defmethodx\defmethodheader}
-%
-% #1 is the class name, #2 the method name, #3 the args.
-\def\defmethodheader#1#2#3{%
-  \dosubind{fn}{\code{#2}}{\putwordon\ \code{#1}}% entry in function index
-  \begingroup
-    \defname{#2}{\putwordMethodon\ \code{#1}}%
-    \defunargs{#3}%
-  \endgroup
-}
-
-% @defcv {Class Option} foo-class foo-flag
-
-\def\defcv #1 {\def\defcvtype{#1}%
-\defopvarparsebody\Edefcv\defcvx\defcvarheader\defcvtype}
-
-\def\defcvarheader #1#2#3{%
-\dosubind {vr}{\code{#2}}{\putwordof\ #1}% Make entry in var index
-\begingroup\defname {#2}{\defcvtype\ \putwordof\ #1}%
-\defvarargs {#3}\endgroup %
-}
-
-% @defivar CLASS VARNAME == @defcv {Instance Variable} CLASS VARNAME
-%
-\def\defivar{\defvrparsebody\Edefivar\defivarx\defivarheader}
-%
-\def\defivarheader#1#2#3{%
-  \dosubind {vr}{\code{#2}}{\putwordof\ #1}% entry in var index
-  \begingroup
-    \defname{#2}{\putwordInstanceVariableof\ #1}%
-    \defvarargs{#3}%
-  \endgroup
-}
-
-% @defvar
-% First, define the processing that is wanted for arguments of @defvar.
-% This is actually simple: just print them in roman.
-% This must expand the args and terminate the paragraph they make up
-\def\defvarargs #1{\normalparens #1%
-\interlinepenalty=10000
-\endgraf\nobreak\vskip -\parskip\nobreak}
-
-% @defvr Counter foo-count
-
-\def\defvr{\defvrparsebody\Edefvr\defvrx\defvrheader}
-
-\def\defvrheader #1#2#3{\doind {vr}{\code{#2}}%
-\begingroup\defname {#2}{#1}\defvarargs{#3}\endgroup}
-
-% @defvar == @defvr Variable
-
-\def\defvar{\defvarparsebody\Edefvar\defvarx\defvarheader}
-
-\def\defvarheader #1#2{\doind {vr}{\code{#1}}% Make entry in var index
-\begingroup\defname {#1}{\putwordDefvar}%
-\defvarargs {#2}\endgroup %
-}
-
-% @defopt == @defvr {User Option}
-
-\def\defopt{\defvarparsebody\Edefopt\defoptx\defoptheader}
-
-\def\defoptheader #1#2{\doind {vr}{\code{#1}}% Make entry in var index
-\begingroup\defname {#1}{\putwordDefopt}%
-\defvarargs {#2}\endgroup %
-}
-
-% @deftypevar int foobar
-
-\def\deftypevar{\defvarparsebody\Edeftypevar\deftypevarx\deftypevarheader}
-
-% #1 is the data type.  #2 is the name, perhaps followed by text that
-% is actually part of the data type, which should not be put into the index.
-\def\deftypevarheader #1#2{%
-\dovarind#2 \relax% Make entry in variables index
-\begingroup\defname {\defheaderxcond#1\relax$$$#2}{\putwordDeftypevar}%
-\interlinepenalty=10000
-\endgraf\nobreak\vskip -\parskip\nobreak
-\endgroup}
-\def\dovarind#1 #2\relax{\doind{vr}{\code{#1}}}
-
-% @deftypevr {Global Flag} int enable
-
-\def\deftypevr{\defvrparsebody\Edeftypevr\deftypevrx\deftypevrheader}
-
-\def\deftypevrheader #1#2#3{\dovarind#3 \relax%
-\begingroup\defname {\defheaderxcond#2\relax$$$#3}{#1}
-\interlinepenalty=10000
-\endgraf\nobreak\vskip -\parskip\nobreak
-\endgroup}
-
-% Now define @deftp
-% Args are printed in bold, a slight difference from @defvar.
-
-\def\deftpargs #1{\bf \defvarargs{#1}}
-
-% @deftp Class window height width ...
-
-\def\deftp{\deftpparsebody\Edeftp\deftpx\deftpheader}
-
-\def\deftpheader #1#2#3{\doind {tp}{\code{#2}}%
-\begingroup\defname {#2}{#1}\deftpargs{#3}\endgroup}
-
-% These definitions are used if you use @defunx (etc.)
-% anywhere other than immediately after a @defun or @defunx.
-% 
-\def\defcvx#1 {\errmessage{@defcvx in invalid context}}
-\def\deffnx#1 {\errmessage{@deffnx in invalid context}}
-\def\defivarx#1 {\errmessage{@defivarx in invalid context}}
-\def\defmacx#1 {\errmessage{@defmacx in invalid context}}
-\def\defmethodx#1 {\errmessage{@defmethodx in invalid context}}
-\def\defoptx #1 {\errmessage{@defoptx in invalid context}}
-\def\defopx#1 {\errmessage{@defopx in invalid context}}
-\def\defspecx#1 {\errmessage{@defspecx in invalid context}}
-\def\deftpx#1 {\errmessage{@deftpx in invalid context}}
-\def\deftypefnx#1 {\errmessage{@deftypefnx in invalid context}}
-\def\deftypefunx#1 {\errmessage{@deftypefunx in invalid context}}
-\def\deftypeivarx#1 {\errmessage{@deftypeivarx in invalid context}}
-\def\deftypemethodx#1 {\errmessage{@deftypemethodx in invalid context}}
-\def\deftypeopx#1 {\errmessage{@deftypeopx in invalid context}}
-\def\deftypevarx#1 {\errmessage{@deftypevarx in invalid context}}
-\def\deftypevrx#1 {\errmessage{@deftypevrx in invalid context}}
-\def\defunx#1 {\errmessage{@defunx in invalid context}}
-\def\defvarx#1 {\errmessage{@defvarx in invalid context}}
-\def\defvrx#1 {\errmessage{@defvrx in invalid context}}
-
-
-\message{macros,}
-% @macro.
-
-% To do this right we need a feature of e-TeX, \scantokens,
-% which we arrange to emulate with a temporary file in ordinary TeX.
-\ifx\eTeXversion\undefined
- \newwrite\macscribble
- \def\scanmacro#1{%
-   \begingroup \newlinechar`\^^M
-   % Undo catcode changes of \startcontents and \doprintindex
-   \catcode`\@=0 \catcode`\\=12 \escapechar=`\@
-   % Append \endinput to make sure that TeX does not see the ending newline.
-   \toks0={#1\endinput}%
-   \immediate\openout\macscribble=\jobname.tmp
-   \immediate\write\macscribble{\the\toks0}%
-   \immediate\closeout\macscribble
-   \let\xeatspaces\eatspaces
-   \input \jobname.tmp
-   \endgroup
-}
-\else
-\def\scanmacro#1{%
-\begingroup \newlinechar`\^^M
-% Undo catcode changes of \startcontents and \doprintindex
-\catcode`\@=0 \catcode`\\=12 \escapechar=`\@
-\let\xeatspaces\eatspaces\scantokens{#1\endinput}\endgroup}
-\fi
-
-\newcount\paramno   % Count of parameters
-\newtoks\macname    % Macro name
-\newif\ifrecursive  % Is it recursive?
-\def\macrolist{}    % List of all defined macros in the form
-                    % \do\macro1\do\macro2...
-
-% Utility routines.
-% Thisdoes \let #1 = #2, except with \csnames.
-\def\cslet#1#2{%
-\expandafter\expandafter
-\expandafter\let
-\expandafter\expandafter
-\csname#1\endcsname
-\csname#2\endcsname}
-
-% Trim leading and trailing spaces off a string.
-% Concepts from aro-bend problem 15 (see CTAN).
-{\catcode`\@=11
-\gdef\eatspaces #1{\expandafter\trim@\expandafter{#1 }}
-\gdef\trim@ #1{\trim@@ @#1 @ #1 @ @@}
-\gdef\trim@@ #1@ #2@ #3@@{\trim@@@\empty #2 @}
-\def\unbrace#1{#1}
-\unbrace{\gdef\trim@@@ #1 } #2@{#1}
-}
-
-% Trim a single trailing ^^M off a string.
-{\catcode`\^^M=12\catcode`\Q=3%
-\gdef\eatcr #1{\eatcra #1Q^^MQ}%
-\gdef\eatcra#1^^MQ{\eatcrb#1Q}%
-\gdef\eatcrb#1Q#2Q{#1}%
-}
-
-% Macro bodies are absorbed as an argument in a context where
-% all characters are catcode 10, 11 or 12, except \ which is active
-% (as in normal texinfo). It is necessary to change the definition of \.
-
-% It's necessary to have hard CRs when the macro is executed. This is
-% done by  making ^^M (\endlinechar) catcode 12 when reading the macro
-% body, and then making it the \newlinechar in \scanmacro.
-
-\def\macrobodyctxt{%
-  \catcode`\~=12
-  \catcode`\^=12
-  \catcode`\_=12
-  \catcode`\|=12
-  \catcode`\<=12
-  \catcode`\>=12
-  \catcode`\+=12
-  \catcode`\{=12
-  \catcode`\}=12
-  \catcode`\@=12
-  \catcode`\^^M=12
-  \usembodybackslash}
-
-\def\macroargctxt{%
-  \catcode`\~=12
-  \catcode`\^=12
-  \catcode`\_=12
-  \catcode`\|=12
-  \catcode`\<=12
-  \catcode`\>=12
-  \catcode`\+=12
-  \catcode`\@=12
-  \catcode`\\=12}
-
-% \mbodybackslash is the definition of \ in @macro bodies.
-% It maps \foo\ => \csname macarg.foo\endcsname => #N
-% where N is the macro parameter number.
-% We define \csname macarg.\endcsname to be \realbackslash, so
-% \\ in macro replacement text gets you a backslash.
-
-{\catcode`@=0 @catcode`@\=@active
- @gdef at usembodybackslash{@let\=@mbodybackslash}
- @gdef at mbodybackslash#1\{@csname macarg.#1 at endcsname}
-}
-\expandafter\def\csname macarg.\endcsname{\realbackslash}
-
-\def\macro{\recursivefalse\parsearg\macroxxx}
-\def\rmacro{\recursivetrue\parsearg\macroxxx}
-
-\def\macroxxx#1{%
-  \getargs{#1}%           now \macname is the macname and \argl the arglist
-  \ifx\argl\empty       % no arguments
-     \paramno=0%
-  \else
-     \expandafter\parsemargdef \argl;%
-  \fi
-  \if1\csname ismacro.\the\macname\endcsname
-     \message{Warning: redefining \the\macname}%
-  \else
-     \expandafter\ifx\csname \the\macname\endcsname \relax
-     \else \errmessage{The name \the\macname\space is reserved}\fi
-     \global\cslet{macsave.\the\macname}{\the\macname}%
-     \global\expandafter\let\csname ismacro.\the\macname\endcsname=1%
-     % Add the macroname to \macrolist
-     \toks0 = \expandafter{\macrolist\do}%
-     \xdef\macrolist{\the\toks0
-       \expandafter\noexpand\csname\the\macname\endcsname}%
-  \fi
-  \begingroup \macrobodyctxt
-  \ifrecursive \expandafter\parsermacbody
-  \else \expandafter\parsemacbody
-  \fi}
-
-\def\unmacro{\parsearg\unmacroxxx}
-\def\unmacroxxx#1{%
-  \if1\csname ismacro.#1\endcsname
-    \global\cslet{#1}{macsave.#1}%
-    \global\expandafter\let \csname ismacro.#1\endcsname=0%
-    % Remove the macro name from \macrolist
-    \begingroup
-      \edef\tempa{\expandafter\noexpand\csname#1\endcsname}%
-      \def\do##1{%
-        \def\tempb{##1}%
-        \ifx\tempa\tempb
-          % remove this
-        \else
-          \toks0 = \expandafter{\newmacrolist\do}%
-          \edef\newmacrolist{\the\toks0\expandafter\noexpand\tempa}%
-        \fi}%
-      \def\newmacrolist{}%
-      % Execute macro list to define \newmacrolist
-      \macrolist
-      \global\let\macrolist\newmacrolist
-    \endgroup
-  \else
-    \errmessage{Macro #1 not defined}%
-  \fi
-}
-
-% This makes use of the obscure feature that if the last token of a
-% <parameter list> is #, then the preceding argument is delimited by
-% an opening brace, and that opening brace is not consumed.
-\def\getargs#1{\getargsxxx#1{}}
-\def\getargsxxx#1#{\getmacname #1 \relax\getmacargs}
-\def\getmacname #1 #2\relax{\macname={#1}}
-\def\getmacargs#1{\def\argl{#1}}
-
-% Parse the optional {params} list.  Set up \paramno and \paramlist
-% so \defmacro knows what to do.  Define \macarg.blah for each blah
-% in the params list, to be ##N where N is the position in that list.
-% That gets used by \mbodybackslash (above).
-
-% We need to get `macro parameter char #' into several definitions.
-% The technique used is stolen from LaTeX:  let \hash be something
-% unexpandable, insert that wherever you need a #, and then redefine
-% it to # just before using the token list produced.
-%
-% The same technique is used to protect \eatspaces till just before
-% the macro is used.
-
-\def\parsemargdef#1;{\paramno=0\def\paramlist{}%
-        \let\hash\relax\let\xeatspaces\relax\parsemargdefxxx#1,;,}
-\def\parsemargdefxxx#1,{%
-  \if#1;\let\next=\relax
-  \else \let\next=\parsemargdefxxx
-    \advance\paramno by 1%
-    \expandafter\edef\csname macarg.\eatspaces{#1}\endcsname
-        {\xeatspaces{\hash\the\paramno}}%
-    \edef\paramlist{\paramlist\hash\the\paramno,}%
-  \fi\next}
-
-% These two commands read recursive and nonrecursive macro bodies.
-% (They're different since rec and nonrec macros end differently.)
-
-\long\def\parsemacbody#1 at end macro%
-{\xdef\temp{\eatcr{#1}}\endgroup\defmacro}%
-\long\def\parsermacbody#1 at end rmacro%
-{\xdef\temp{\eatcr{#1}}\endgroup\defmacro}%
-
-% This defines the macro itself. There are six cases: recursive and
-% nonrecursive macros of zero, one, and many arguments.
-% Much magic with \expandafter here.
-% \xdef is used so that macro definitions will survive the file
-% they're defined in; @include reads the file inside a group.
-\def\defmacro{%
-  \let\hash=##% convert placeholders to macro parameter chars
-  \ifrecursive
-    \ifcase\paramno
-    % 0
-      \expandafter\xdef\csname\the\macname\endcsname{%
-        \noexpand\scanmacro{\temp}}%
-    \or % 1
-      \expandafter\xdef\csname\the\macname\endcsname{%
-         \bgroup\noexpand\macroargctxt
-         \noexpand\braceorline
-         \expandafter\noexpand\csname\the\macname xxx\endcsname}%
-      \expandafter\xdef\csname\the\macname xxx\endcsname##1{%
-         \egroup\noexpand\scanmacro{\temp}}%
-    \else % many
-      \expandafter\xdef\csname\the\macname\endcsname{%
-         \bgroup\noexpand\macroargctxt
-         \noexpand\csname\the\macname xx\endcsname}%
-      \expandafter\xdef\csname\the\macname xx\endcsname##1{%
-          \expandafter\noexpand\csname\the\macname xxx\endcsname ##1,}%
-      \expandafter\expandafter
-      \expandafter\xdef
-      \expandafter\expandafter
-        \csname\the\macname xxx\endcsname
-          \paramlist{\egroup\noexpand\scanmacro{\temp}}%
-    \fi
-  \else
-    \ifcase\paramno
-    % 0
-      \expandafter\xdef\csname\the\macname\endcsname{%
-        \noexpand\norecurse{\the\macname}%
-        \noexpand\scanmacro{\temp}\egroup}%
-    \or % 1
-      \expandafter\xdef\csname\the\macname\endcsname{%
-         \bgroup\noexpand\macroargctxt
-         \noexpand\braceorline
-         \expandafter\noexpand\csname\the\macname xxx\endcsname}%
-      \expandafter\xdef\csname\the\macname xxx\endcsname##1{%
-        \egroup
-        \noexpand\norecurse{\the\macname}%
-        \noexpand\scanmacro{\temp}\egroup}%
-    \else % many
-      \expandafter\xdef\csname\the\macname\endcsname{%
-         \bgroup\noexpand\macroargctxt
-         \expandafter\noexpand\csname\the\macname xx\endcsname}%
-      \expandafter\xdef\csname\the\macname xx\endcsname##1{%
-          \expandafter\noexpand\csname\the\macname xxx\endcsname ##1,}%
-      \expandafter\expandafter
-      \expandafter\xdef
-      \expandafter\expandafter
-      \csname\the\macname xxx\endcsname
-      \paramlist{%
-          \egroup
-          \noexpand\norecurse{\the\macname}%
-          \noexpand\scanmacro{\temp}\egroup}%
-    \fi
-  \fi}
-
-\def\norecurse#1{\bgroup\cslet{#1}{macsave.#1}}
-
-% \braceorline decides whether the next nonwhitespace character is a
-% {.  If so it reads up to the closing }, if not, it reads the whole
-% line.  Whatever was read is then fed to the next control sequence
-% as an argument (by \parsebrace or \parsearg)
-\def\braceorline#1{\let\next=#1\futurelet\nchar\braceorlinexxx}
-\def\braceorlinexxx{%
-  \ifx\nchar\bgroup\else
-    \expandafter\parsearg
-  \fi \next}
-
-% We mant to disable all macros during \shipout so that they are not
-% expanded by \write.
-\def\turnoffmacros{\begingroup \def\do##1{\let\noexpand##1=\relax}%
-  \edef\next{\macrolist}\expandafter\endgroup\next}
-
-
-% @alias.
-% We need some trickery to remove the optional spaces around the equal
-% sign.  Just make them active and then expand them all to nothing.
-\def\alias{\begingroup\obeyspaces\parsearg\aliasxxx}
-\def\aliasxxx #1{\aliasyyy#1\relax}
-\def\aliasyyy #1=#2\relax{\ignoreactivespaces
-\edef\next{\global\let\expandafter\noexpand\csname#1\endcsname=%
-           \expandafter\noexpand\csname#2\endcsname}%
-\expandafter\endgroup\next}
-
-
-\message{cross references,}
-% @xref etc.
-
-\newwrite\auxfile
-
-\newif\ifhavexrefs    % True if xref values are known.
-\newif\ifwarnedxrefs  % True if we warned once that they aren't known.
-
-% @inforef is relatively simple.
-\def\inforef #1{\inforefzzz #1,,,,**}
-\def\inforefzzz #1,#2,#3,#4**{\putwordSee{} \putwordInfo{} \putwordfile{} \file{\ignorespaces #3{}},
-  node \samp{\ignorespaces#1{}}}
-
-% @node's job is to define \lastnode.
-\def\node{\ENVcheck\parsearg\nodezzz}
-\def\nodezzz#1{\nodexxx [#1,]}
-\def\nodexxx[#1,#2]{\gdef\lastnode{#1}}
-\let\nwnode=\node
-\let\lastnode=\relax
-
-% The sectioning commands (@chapter, etc.) call these.
-\def\donoderef{%
-  \ifx\lastnode\relax\else
-    \expandafter\expandafter\expandafter\setref{\lastnode}%
-      {Ysectionnumberandtype}%
-    \global\let\lastnode=\relax
-  \fi
-}
-\def\unnumbnoderef{%
-  \ifx\lastnode\relax\else
-    \expandafter\expandafter\expandafter\setref{\lastnode}{Ynothing}%
-    \global\let\lastnode=\relax
-  \fi
-}
-\def\appendixnoderef{%
-  \ifx\lastnode\relax\else
-    \expandafter\expandafter\expandafter\setref{\lastnode}%
-      {Yappendixletterandtype}%
-    \global\let\lastnode=\relax
-  \fi
-}
-
-
-% @anchor{NAME} -- define xref target at arbitrary point.
-%
-\newcount\savesfregister
-\gdef\savesf{\relax \ifhmode \savesfregister=\spacefactor \fi}
-\gdef\restoresf{\relax \ifhmode \spacefactor=\savesfregister \fi}
-\gdef\anchor#1{\savesf \setref{#1}{Ynothing}\restoresf \ignorespaces}
-
-% \setref{NAME}{SNT} defines a cross-reference point NAME, namely
-% NAME-title, NAME-pg, and NAME-SNT.  Called from \foonoderef.  We have
-% to set \indexdummies so commands such as @code in a section title
-% aren't expanded.  It would be nicer not to expand the titles in the
-% first place, but there's so many layers that that is hard to do.
-%
-\def\setref#1#2{{%
-  \indexdummies
-  \pdfmkdest{#1}%
-  \dosetq{#1-title}{Ytitle}%
-  \dosetq{#1-pg}{Ypagenumber}%
-  \dosetq{#1-snt}{#2}%
-}}
-
-% @xref, @pxref, and @ref generate cross-references.  For \xrefX, #1 is
-% the node name, #2 the name of the Info cross-reference, #3 the printed
-% node name, #4 the name of the Info file, #5 the name of the printed
-% manual.  All but the node name can be omitted.
-%
-\def\pxref#1{\putwordsee{} \xrefX[#1,,,,,,,]}
-\def\xref#1{\putwordSee{} \xrefX[#1,,,,,,,]}
-\def\ref#1{\xrefX[#1,,,,,,,]}
-\def\xrefX[#1,#2,#3,#4,#5,#6]{\begingroup
-  \unsepspaces
-  \def\printedmanual{\ignorespaces #5}%
-  \def\printednodename{\ignorespaces #3}%
-  \setbox1=\hbox{\printedmanual}%
-  \setbox0=\hbox{\printednodename}%
-  \ifdim \wd0 = 0pt
-    % No printed node name was explicitly given.
-    \expandafter\ifx\csname SETxref-automatic-section-title\endcsname\relax
-      % Use the node name inside the square brackets.
-      \def\printednodename{\ignorespaces #1}%
-    \else
-      % Use the actual chapter/section title appear inside
-      % the square brackets.  Use the real section title if we have it.
-      \ifdim \wd1 > 0pt
-        % It is in another manual, so we don't have it.
-        \def\printednodename{\ignorespaces #1}%
-      \else
-        \ifhavexrefs
-          % We know the real title if we have the xref values.
-          \def\printednodename{\refx{#1-title}{}}%
-        \else
-          % Otherwise just copy the Info node name.
-          \def\printednodename{\ignorespaces #1}%
-        \fi%
-      \fi
-    \fi
-  \fi
-  %
-  % If we use \unhbox0 and \unhbox1 to print the node names, TeX does not
-  % insert empty discretionaries after hyphens, which means that it will
-  % not find a line break at a hyphen in a node names.  Since some manuals
-  % are best written with fairly long node names, containing hyphens, this
-  % is a loss.  Therefore, we give the text of the node name again, so it
-  % is as if TeX is seeing it for the first time.
-  \ifpdf
-    \leavevmode
-    \getfilename{#4}%
-    \ifnum\filenamelength>0
-      \startlink attr{/Border [0 0 0]}%
-        goto file{\the\filename.pdf} name{#1@}%
-    \else
-      \startlink attr{/Border [0 0 0]}%
-        goto name{#1@}%
-    \fi
-    \linkcolor
-  \fi
-  %
-  \ifdim \wd1 > 0pt
-    \putwordsection{} ``\printednodename'' \putwordin{} \cite{\printedmanual}%
-  \else
-    % _ (for example) has to be the character _ for the purposes of the
-    % control sequence corresponding to the node, but it has to expand
-    % into the usual \leavevmode...\vrule stuff for purposes of
-    % printing. So we \turnoffactive for the \refx-snt, back on for the
-    % printing, back off for the \refx-pg.
-    {\normalturnoffactive
-     % Only output a following space if the -snt ref is nonempty; for
-     % @unnumbered and @anchor, it won't be.
-     \setbox2 = \hbox{\ignorespaces \refx{#1-snt}{}}%
-     \ifdim \wd2 > 0pt \refx{#1-snt}\space\fi
-    }%
-    % [mynode],
-    [\printednodename],\space
-    % page 3
-    \turnoffactive \putwordpage\tie\refx{#1-pg}{}%
-  \fi
-  \endlink
-\endgroup}
-
-% \dosetq is the interface for calls from other macros
-
-% Use \normalturnoffactive so that punctuation chars such as underscore
-% and backslash work in node names.  (\turnoffactive doesn't do \.)
-\def\dosetq#1#2{%
-  {\let\folio=0%
-   \normalturnoffactive
-   \edef\next{\write\auxfile{\internalsetq{#1}{#2}}}%
-   \iflinks
-     \next
-   \fi
-  }%
-}
-
-% \internalsetq {foo}{page} expands into
-% CHARACTERS 'xrdef {foo}{...expansion of \Ypage...}
-% When the aux file is read, ' is the escape character
-
-\def\internalsetq #1#2{'xrdef {#1}{\csname #2\endcsname}}
-
-% Things to be expanded by \internalsetq
-
-\def\Ypagenumber{\folio}
-
-\def\Ytitle{\thissection}
-
-\def\Ynothing{}
-
-\def\Ysectionnumberandtype{%
-\ifnum\secno=0 \putwordChapter\xreftie\the\chapno %
-\else \ifnum \subsecno=0 \putwordSection\xreftie\the\chapno.\the\secno %
-\else \ifnum \subsubsecno=0 %
-\putwordSection\xreftie\the\chapno.\the\secno.\the\subsecno %
-\else %
-\putwordSection\xreftie\the\chapno.\the\secno.\the\subsecno.\the\subsubsecno %
-\fi \fi \fi }
-
-\def\Yappendixletterandtype{%
-\ifnum\secno=0 \putwordAppendix\xreftie'char\the\appendixno{}%
-\else \ifnum \subsecno=0 \putwordSection\xreftie'char\the\appendixno.\the\secno %
-\else \ifnum \subsubsecno=0 %
-\putwordSection\xreftie'char\the\appendixno.\the\secno.\the\subsecno %
-\else %
-\putwordSection\xreftie'char\the\appendixno.\the\secno.\the\subsecno.\the\subsubsecno %
-\fi \fi \fi }
-
-\gdef\xreftie{'tie}
-
-% Use TeX 3.0's \inputlineno to get the line number, for better error
-% messages, but if we're using an old version of TeX, don't do anything.
-%
-\ifx\inputlineno\thisisundefined
-  \let\linenumber = \empty % Non-3.0.
-\else
-  \def\linenumber{\the\inputlineno:\space}
-\fi
-
-% Define \refx{NAME}{SUFFIX} to reference a cross-reference string named NAME.
-% If its value is nonempty, SUFFIX is output afterward.
-
-\def\refx#1#2{%
-  \expandafter\ifx\csname X#1\endcsname\relax
-    % If not defined, say something at least.
-    \angleleft un\-de\-fined\angleright
-    \iflinks
-      \ifhavexrefs
-        \message{\linenumber Undefined cross reference `#1'.}%
-      \else
-        \ifwarnedxrefs\else
-          \global\warnedxrefstrue
-          \message{Cross reference values unknown; you must run TeX again.}%
-        \fi
-      \fi
-    \fi
-  \else
-    % It's defined, so just use it.
-    \csname X#1\endcsname
-  \fi
-  #2% Output the suffix in any case.
-}
-
-% This is the macro invoked by entries in the aux file.
-%
-\def\xrdef#1{\begingroup
-  % Reenable \ as an escape while reading the second argument.
-  \catcode`\\ = 0
-  \afterassignment\endgroup
-  \expandafter\gdef\csname X#1\endcsname
-}
-
-% Read the last existing aux file, if any.  No error if none exists.
-\def\readauxfile{\begingroup
-  \catcode`\^^@=\other
-  \catcode`\^^A=\other
-  \catcode`\^^B=\other
-  \catcode`\^^C=\other
-  \catcode`\^^D=\other
-  \catcode`\^^E=\other
-  \catcode`\^^F=\other
-  \catcode`\^^G=\other
-  \catcode`\^^H=\other
-  \catcode`\^^K=\other
-  \catcode`\^^L=\other
-  \catcode`\^^N=\other
-  \catcode`\^^P=\other
-  \catcode`\^^Q=\other
-  \catcode`\^^R=\other
-  \catcode`\^^S=\other
-  \catcode`\^^T=\other
-  \catcode`\^^U=\other
-  \catcode`\^^V=\other
-  \catcode`\^^W=\other
-  \catcode`\^^X=\other
-  \catcode`\^^Z=\other
-  \catcode`\^^[=\other
-  \catcode`\^^\=\other
-  \catcode`\^^]=\other
-  \catcode`\^^^=\other
-  \catcode`\^^_=\other
-  \catcode`\@=\other
-  \catcode`\^=\other
-  % It was suggested to define this as 7, which would allow ^^e4 etc.
-  % in xref tags, i.e., node names.  But since ^^e4 notation isn't
-  % supported in the main text, it doesn't seem desirable.  Furthermore,
-  % that is not enough: for node names that actually contain a ^
-  % character, we would end up writing a line like this: 'xrdef {'hat
-  % b-title}{'hat b} and \xrdef does a \csname...\endcsname on the first
-  % argument, and \hat is not an expandable control sequence.  It could
-  % all be worked out, but why?  Either we support ^^ or we don't.
-  %
-  % The other change necessary for this was to define \auxhat:
-  % \def\auxhat{\def^{'hat }}% extra space so ok if followed by letter
-  % and then to call \auxhat in \setq.
-  %
-  \catcode`\~=\other
-  \catcode`\[=\other
-  \catcode`\]=\other
-  \catcode`\"=\other
-  \catcode`\_=\other
-  \catcode`\|=\other
-  \catcode`\<=\other
-  \catcode`\>=\other
-  \catcode`\$=\other
-  \catcode`\#=\other
-  \catcode`\&=\other
-  \catcode`+=\other % avoid \+ for paranoia even though we've turned it off
-  % Make the characters 128-255 be printing characters
-  {%
-    \count 1=128
-    \def\loop{%
-      \catcode\count 1=\other
-      \advance\count 1 by 1
-      \ifnum \count 1<256 \loop \fi
-    }%
-  }%
-  % The aux file uses ' as the escape (for now).
-  % Turn off \ as an escape so we do not lose on
-  % entries which were dumped with control sequences in their names.
-  % For example, 'xrdef {$\leq $-fun}{page ...} made by @defun ^^
-  % Reference to such entries still does not work the way one would wish,
-  % but at least they do not bomb out when the aux file is read in.
-  \catcode`\{=1
-  \catcode`\}=2
-  \catcode`\%=\other
-  \catcode`\'=0
-  \catcode`\\=\other
-  %
-  \openin 1 \jobname.aux
-  \ifeof 1 \else
-    \closein 1
-    \input \jobname.aux
-    \global\havexrefstrue
-    \global\warnedobstrue
-  \fi
-  % Open the new aux file.  TeX will close it automatically at exit.
-  \openout\auxfile=\jobname.aux
-\endgroup}
-
-
-% Footnotes.
-
-\newcount \footnoteno
-
-% The trailing space in the following definition for supereject is
-% vital for proper filling; pages come out unaligned when you do a
-% pagealignmacro call if that space before the closing brace is
-% removed. (Generally, numeric constants should always be followed by a
-% space to prevent strange expansion errors.)
-\def\supereject{\par\penalty -20000\footnoteno =0 }
-
-% @footnotestyle is meaningful for info output only.
-\let\footnotestyle=\comment
-
-\let\ptexfootnote=\footnote
-
-{\catcode `\@=11
-%
-% Auto-number footnotes.  Otherwise like plain.
-\gdef\footnote{%
-  \global\advance\footnoteno by \@ne
-  \edef\thisfootno{$^{\the\footnoteno}$}%
-  %
-  % In case the footnote comes at the end of a sentence, preserve the
-  % extra spacing after we do the footnote number.
-  \let\@sf\empty
-  \ifhmode\edef\@sf{\spacefactor\the\spacefactor}\/\fi
-  %
-  % Remove inadvertent blank space before typesetting the footnote number.
-  \unskip
-  \thisfootno\@sf
-  \footnotezzz
-}%
-
-% Don't bother with the trickery in plain.tex to not require the
-% footnote text as a parameter.  Our footnotes don't need to be so general.
-%
-% Oh yes, they do; otherwise, @ifset and anything else that uses
-% \parseargline fail inside footnotes because the tokens are fixed when
-% the footnote is read.  --karl, 16nov96.
-%
-\long\gdef\footnotezzz{\insert\footins\bgroup
-  % We want to typeset this text as a normal paragraph, even if the
-  % footnote reference occurs in (for example) a display environment.
-  % So reset some parameters.
-  \interlinepenalty\interfootnotelinepenalty
-  \splittopskip\ht\strutbox % top baseline for broken footnotes
-  \splitmaxdepth\dp\strutbox
-  \floatingpenalty\@MM
-  \leftskip\z at skip
-  \rightskip\z at skip
-  \spaceskip\z at skip
-  \xspaceskip\z at skip
-  \parindent\defaultparindent
-  %
-  \smallfonts \rm
-  %
-  % Hang the footnote text off the number.
-  \hang
-  \textindent{\thisfootno}%
-  %
-  % Don't crash into the line above the footnote text.  Since this
-  % expands into a box, it must come within the paragraph, lest it
-  % provide a place where TeX can split the footnote.
-  \footstrut
-  \futurelet\next\fo at t
-}
-\def\fo at t{\ifcat\bgroup\noexpand\next \let\next\f@@t
-  \else\let\next\f at t\fi \next}
-\def\f@@t{\bgroup\aftergroup\@foot\let\next}
-\def\f at t#1{#1\@foot}
-\def\@foot{\strut\par\egroup}
-
-}%end \catcode `\@=11
-
-% Set the baselineskip to #1, and the lineskip and strut size
-% correspondingly.  There is no deep meaning behind these magic numbers
-% used as factors; they just match (closely enough) what Knuth defined.
-%
-\def\lineskipfactor{.08333}
-\def\strutheightpercent{.70833}
-\def\strutdepthpercent {.29167}
-%
-\def\setleading#1{%
-  \normalbaselineskip = #1\relax
-  \normallineskip = \lineskipfactor\normalbaselineskip
-  \normalbaselines
-  \setbox\strutbox =\hbox{%
-    \vrule width0pt height\strutheightpercent\baselineskip
-                    depth \strutdepthpercent \baselineskip
-  }%
-}
-
-% @| inserts a changebar to the left of the current line.  It should
-% surround any changed text.  This approach does *not* work if the
-% change spans more than two lines of output.  To handle that, we would
-% have adopt a much more difficult approach (putting marks into the main
-% vertical list for the beginning and end of each change).
-%
-\def\|{%
-  % \vadjust can only be used in horizontal mode.
-  \leavevmode
-  %
-  % Append this vertical mode material after the current line in the output.
-  \vadjust{%
-    % We want to insert a rule with the height and depth of the current
-    % leading; that is exactly what \strutbox is supposed to record.
-    \vskip-\baselineskip
-    %
-    % \vadjust-items are inserted at the left edge of the type.  So
-    % the \llap here moves out into the left-hand margin.
-    \llap{%
-      %
-      % For a thicker or thinner bar, change the `1pt'.
-      \vrule height\baselineskip width1pt
-      %
-      % This is the space between the bar and the text.
-      \hskip 12pt
-    }%
-  }%
-}
-
-% For a final copy, take out the rectangles
-% that mark overfull boxes (in case you have decided
-% that the text looks ok even though it passes the margin).
-%
-\def\finalout{\overfullrule=0pt}
-
-% @image.  We use the macros from epsf.tex to support this.
-% If epsf.tex is not installed and @image is used, we complain.
-%
-% Check for and read epsf.tex up front.  If we read it only at @image
-% time, we might be inside a group, and then its definitions would get
-% undone and the next image would fail.
-\openin 1 = epsf.tex
-\ifeof 1 \else
-  \closein 1
-  % Do not bother showing banner with post-v2.7 epsf.tex (available in
-  % doc/epsf.tex until it shows up on ctan).
-  \def\epsfannounce{\toks0 = }%
-  \input epsf.tex
-\fi
-%
-% We will only complain once about lack of epsf.tex.
-\newif\ifwarnednoepsf
-\newhelp\noepsfhelp{epsf.tex must be installed for images to
-  work.  It is also included in the Texinfo distribution, or you can get
-  it from ftp://tug.org/tex/epsf.tex.}
-%
-\def\image#1{%
-  \ifx\epsfbox\undefined
-    \ifwarnednoepsf \else
-      \errhelp = \noepsfhelp
-      \errmessage{epsf.tex not found, images will be ignored}%
-      \global\warnednoepsftrue
-    \fi
-  \else
-    \imagexxx #1,,,\finish
-  \fi
-}
-%
-% Arguments to @image:
-% #1 is (mandatory) image filename; we tack on .eps extension.
-% #2 is (optional) width, #3 is (optional) height.
-% #4 is just the usual extra ignored arg for parsing this stuff.
-\def\imagexxx#1,#2,#3,#4\finish{%
-  \ifpdf
-    \centerline{\dopdfimage{#1}{#2}{#3}}%
-  \else
-    % \epsfbox itself resets \epsf?size at each figure.
-    \setbox0 = \hbox{\ignorespaces #2}\ifdim\wd0 > 0pt \epsfxsize=#2\relax \fi
-    \setbox0 = \hbox{\ignorespaces #3}\ifdim\wd0 > 0pt \epsfysize=#3\relax \fi
-    \begingroup
-      \catcode`\^^M = 5 % in case we're inside an example
-      % If the image is by itself, center it.
-      \ifvmode
-        \nobreak\bigskip
-        % Usually we'll have text after the image which will insert
-        % \parskip glue, so insert it here too to equalize the space
-        % above and below. 
-        \nobreak\vskip\parskip
-        \nobreak
-        \centerline{\epsfbox{#1.eps}}%
-        \bigbreak
-      \else
-        % In the middle of a paragraph, no extra space.
-        \epsfbox{#1.eps}%
-      \fi
-    \endgroup
-  \fi
-}
-
-
-\message{localization,}
-% and i18n.
-
-% @documentlanguage is usually given very early, just after
-% @setfilename.  If done too late, it may not override everything
-% properly.  Single argument is the language abbreviation.
-% It would be nice if we could set up a hyphenation file here.
-%
-\def\documentlanguage{\parsearg\dodocumentlanguage}
-\def\dodocumentlanguage#1{%
-  \tex % read txi-??.tex file in plain TeX.
-  % Read the file if it exists.
-  \openin 1 txi-#1.tex
-  \ifeof1
-    \errhelp = \nolanghelp
-    \errmessage{Cannot read language file txi-#1.tex}%
-    \let\temp = \relax
-  \else
-    \def\temp{\input txi-#1.tex }%
-  \fi
-  \temp
-  \endgroup
-}
-\newhelp\nolanghelp{The given language definition file cannot be found or
-is empty.  Maybe you need to install it?  In the current directory
-should work if nowhere else does.}
-
-
-% @documentencoding should change something in TeX eventually, most
-% likely, but for now just recognize it.
-\let\documentencoding = \comment
-
-
-% Page size parameters.
-%
-\newdimen\defaultparindent \defaultparindent = 15pt
-
-\chapheadingskip = 15pt plus 4pt minus 2pt
-\secheadingskip = 12pt plus 3pt minus 2pt
-\subsecheadingskip = 9pt plus 2pt minus 2pt
-
-% Prevent underfull vbox error messages.
-\vbadness = 10000
-
-% Don't be so finicky about underfull hboxes, either.
-\hbadness = 2000
-
-% Following George Bush, just get rid of widows and orphans.
-\widowpenalty=10000
-\clubpenalty=10000
-
-% Use TeX 3.0's \emergencystretch to help line breaking, but if we're
-% using an old version of TeX, don't do anything.  We want the amount of
-% stretch added to depend on the line length, hence the dependence on
-% \hsize.  We call this whenever the paper size is set.
-%
-\def\setemergencystretch{%
-  \ifx\emergencystretch\thisisundefined
-    % Allow us to assign to \emergencystretch anyway.
-    \def\emergencystretch{\dimen0}%
-  \else
-    \emergencystretch = .15\hsize
-  \fi
-}
-
-% Parameters in order: 1) textheight; 2) textwidth; 3) voffset;
-% 4) hoffset; 5) binding offset; 6) topskip.  Then whoever calls us can
-% set \parskip and call \setleading for \baselineskip.
-%
-\def\internalpagesizes#1#2#3#4#5#6{%
-  \voffset = #3\relax
-  \topskip = #6\relax
-  \splittopskip = \topskip
-  %
-  \vsize = #1\relax
-  \advance\vsize by \topskip
-  \outervsize = \vsize
-  \advance\outervsize by 2\topandbottommargin
-  \pageheight = \vsize
-  %
-  \hsize = #2\relax
-  \outerhsize = \hsize
-  \advance\outerhsize by 0.5in
-  \pagewidth = \hsize
-  %
-  \normaloffset = #4\relax
-  \bindingoffset = #5\relax
-  %
-  \parindent = \defaultparindent
-  \setemergencystretch
-}
-
-% @letterpaper (the default).
-\def\letterpaper{{\globaldefs = 1
-  \parskip = 3pt plus 2pt minus 1pt
-  \setleading{13.2pt}%
-  %
-  % If page is nothing but text, make it come out even.
-  \internalpagesizes{46\baselineskip}{6in}{\voffset}{.25in}{\bindingoffset}{36pt}%
-}}
-
-% Use @smallbook to reset parameters for 7x9.5 (or so) format.
-\def\smallbook{{\globaldefs = 1
-  \parskip = 2pt plus 1pt
-  \setleading{12pt}%
-  %
-  \internalpagesizes{7.5in}{5.in}{\voffset}{.25in}{\bindingoffset}{16pt}%
-  %
-  \lispnarrowing = 0.3in
-  \tolerance = 700
-  \hfuzz = 1pt
-  \contentsrightmargin = 0pt
-  \deftypemargin = 0pt
-  \defbodyindent = .5cm
-  %
-  \let\smalldisplay = \smalldisplayx
-  \let\smallexample = \smalllispx
-  \let\smallformat = \smallformatx
-  \let\smalllisp = \smalllispx
-}}
-
-% Use @afourpaper to print on European A4 paper.
-\def\afourpaper{{\globaldefs = 1
-  \setleading{12pt}%
-  \parskip = 3pt plus 2pt minus 1pt
-  %
-  \internalpagesizes{53\baselineskip}{160mm}{\voffset}{4mm}{\bindingoffset}{44pt}%
-  %
-  \tolerance = 700
-  \hfuzz = 1pt
-}}
-
-% A specific text layout, 24x15cm overall, intended for A4 paper.  Top margin
-% 29mm, hence bottom margin 28mm, nominal side margin 3cm.
-\def\afourlatex{{\globaldefs = 1
-  \setleading{13.6pt}%
-  %
-  \afourpaper
-  \internalpagesizes{237mm}{150mm}{3.6mm}{3.6mm}{3mm}{7mm}%
-  %
-  \globaldefs = 0
-}}
-
-% Use @afourwide to print on European A4 paper in wide format.
-\def\afourwide{%
-  \afourpaper
-  \internalpagesizes{6.5in}{9.5in}{\hoffset}{\normaloffset}{\bindingoffset}{7mm}%
-  %
-  \globaldefs = 0
-}
-
-% @pagesizes TEXTHEIGHT[,TEXTWIDTH]
-% Perhaps we should allow setting the margins, \topskip, \parskip,
-% and/or leading, also. Or perhaps we should compute them somehow.
-%
-\def\pagesizes{\parsearg\pagesizesxxx}
-\def\pagesizesxxx#1{\pagesizesyyy #1,,\finish}
-\def\pagesizesyyy#1,#2,#3\finish{{%
-  \setbox0 = \hbox{\ignorespaces #2}\ifdim\wd0 > 0pt \hsize=#2\relax \fi
-  \globaldefs = 1
-  %
-  \parskip = 3pt plus 2pt minus 1pt
-  \setleading{13.2pt}%
-  %
-  \internalpagesizes{#1}{\hsize}{\voffset}{\normaloffset}{\bindingoffset}{44pt}%
-}}
-
-% Set default to letter.
-%
-\letterpaper
-
-
-\message{and turning on texinfo input format.}
-
-% Define macros to output various characters with catcode for normal text.
-\catcode`\"=\other
-\catcode`\~=\other
-\catcode`\^=\other
-\catcode`\_=\other
-\catcode`\|=\other
-\catcode`\<=\other
-\catcode`\>=\other
-\catcode`\+=\other
-\catcode`\$=\other
-\def\normaldoublequote{"}
-\def\normaltilde{~}
-\def\normalcaret{^}
-\def\normalunderscore{_}
-\def\normalverticalbar{|}
-\def\normalless{<}
-\def\normalgreater{>}
-\def\normalplus{+}
-\def\normaldollar{$}
-
-% This macro is used to make a character print one way in ttfont
-% where it can probably just be output, and another way in other fonts,
-% where something hairier probably needs to be done.
-%
-% #1 is what to print if we are indeed using \tt; #2 is what to print
-% otherwise.  Since all the Computer Modern typewriter fonts have zero
-% interword stretch (and shrink), and it is reasonable to expect all
-% typewriter fonts to have this, we can check that font parameter.
-%
-\def\ifusingtt#1#2{\ifdim \fontdimen3\font=0pt #1\else #2\fi}
-
-% Same as above, but check for italic font.  Actually this also catches
-% non-italic slanted fonts since it is impossible to distinguish them from
-% italic fonts.  But since this is only used by $ and it uses \sl anyway
-% this is not a problem.
-\def\ifusingit#1#2{\ifdim \fontdimen1\font>0pt #1\else #2\fi}
-
-% Turn off all special characters except @
-% (and those which the user can use as if they were ordinary).
-% Most of these we simply print from the \tt font, but for some, we can
-% use math or other variants that look better in normal text.
-
-\catcode`\"=\active
-\def\activedoublequote{{\tt\char34}}
-\let"=\activedoublequote
-\catcode`\~=\active
-\def~{{\tt\char126}}
-\chardef\hat=`\^
-\catcode`\^=\active
-\def^{{\tt \hat}}
-
-\catcode`\_=\active
-\def_{\ifusingtt\normalunderscore\_}
-% Subroutine for the previous macro.
-\def\_{\leavevmode \kern.06em \vbox{\hrule width.3em height.1ex}}
-
-\catcode`\|=\active
-\def|{{\tt\char124}}
-\chardef \less=`\<
-\catcode`\<=\active
-\def<{{\tt \less}}
-\chardef \gtr=`\>
-\catcode`\>=\active
-\def>{{\tt \gtr}}
-\catcode`\+=\active
-\def+{{\tt \char 43}}
-\catcode`\$=\active
-\def${\ifusingit{{\sl\$}}\normaldollar}
-%\catcode 27=\active
-%\def^^[{$\diamondsuit$}
-
-% Set up an active definition for =, but don't enable it most of the time.
-{\catcode`\==\active
-\global\def={{\tt \char 61}}}
-
-\catcode`+=\active
-\catcode`\_=\active
-
-% If a .fmt file is being used, characters that might appear in a file
-% name cannot be active until we have parsed the command line.
-% So turn them off again, and have \everyjob (or @setfilename) turn them on.
-% \otherifyactive is called near the end of this file.
-\def\otherifyactive{\catcode`+=\other \catcode`\_=\other}
-
-\catcode`\@=0
-
-% \rawbackslashxx output one backslash character in current font
-\global\chardef\rawbackslashxx=`\\
-%{\catcode`\\=\other
-%@gdef at rawbackslashxx{\}}
-
-% \rawbackslash redefines \ as input to do \rawbackslashxx.
-{\catcode`\\=\active
- at gdef@rawbackslash{@let\=@rawbackslashxx }}
-
-% \normalbackslash outputs one backslash in fixed width font.
-\def\normalbackslash{{\tt\rawbackslashxx}}
-
-% \catcode 17=0   % Define control-q
-\catcode`\\=\active
-
-% Used sometimes to turn off (effectively) the active characters
-% even after parsing them.
- at def@turnoffactive{@let"=@normaldoublequote
- at let\=@realbackslash
- at let~=@normaltilde
- at let^=@normalcaret
- at let_=@normalunderscore
- at let|=@normalverticalbar
- at let<=@normalless
- at let>=@normalgreater
- at let+=@normalplus
- at let$=@normaldollar}
-
- at def@normalturnoffactive{@let"=@normaldoublequote
- at let\=@normalbackslash
- at let~=@normaltilde
- at let^=@normalcaret
- at let_=@normalunderscore
- at let|=@normalverticalbar
- at let<=@normalless
- at let>=@normalgreater
- at let+=@normalplus
- at let$=@normaldollar}
-
-% Make _ and + \other characters, temporarily.
-% This is canceled by @fixbackslash.
- at otherifyactive
-
-% If a .fmt file is being used, we don't want the `\input texinfo' to show up.
-% That is what \eatinput is for; after that, the `\' should revert to printing
-% a backslash.
-%
- at gdef@eatinput input texinfo{@fixbackslash}
- at global@let\ = @eatinput
-
-% On the other hand, perhaps the file did not have a `\input texinfo'. Then
-% the first `\{ in the file would cause an error. This macro tries to fix
-% that, assuming it is called before the first `\' could plausibly occur.
-% Also back turn on active characters that might appear in the input
-% file name, in case not using a pre-dumped format.
-%
- at gdef@fixbackslash{%
-  @ifx\@eatinput @let\ = @normalbackslash @fi
-  @catcode`+=@active
-  @catcode`@_=@active
-}
-
-% Say @foo, not \foo, in error messages.
- at escapechar = `@@
-
-% These look ok in all fonts, so just make them not special.  
- at catcode`@& = @other
- at catcode`@# = @other
- at catcode`@% = @other
-
- at c Set initial fonts.
- at textfonts
- at rm
-
-
- at c Local variables:
- at c eval: (add-hook 'write-file-hooks 'time-stamp)
- at c page-delimiter: "^\\\\message"
- at c time-stamp-start: "def\\\\texinfoversion{"
- at c time-stamp-format: "%:y-%02m-%02d.%02H"
- at c time-stamp-end: "}"
- at c End:
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/lib/Makefile.in
--- a/head/contrib/gperf/lib/Makefile.in	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/contrib/gperf/lib/Makefile.in	Tue Dec 06 20:26:16 2011 +0200
@@ -1,13 +1,14 @@
 # Makefile for gperf/lib
 
-# Copyright (C) 1989, 1992, 1993, 1998 Free Software Foundation, Inc.
-# written by Douglas C. Schmidt (schmidt at ics.uci.edu)
+# Copyright (C) 1989, 1992, 1993, 1998, 2002 Free Software Foundation, Inc.
+# Written by Douglas C. Schmidt <schmidt at ics.uci.edu>
+# and Bruno Haible <bruno at clisp.org>.
 #
 # This file is part of GNU GPERF.
 #
 # GNU GPERF 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 1, or (at your option)
+# the Free Software Foundation; either version 2, or (at your option)
 # any later version.
 #
 # GNU GPERF is distributed in the hope that it will be useful,
@@ -16,8 +17,9 @@
 # GNU General Public License for more details.
 #
 # You should have received a copy of the GNU General Public License
-# along with GNU GPERF; see the file COPYING.  If not, write to the Free
-# Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111, USA.
+# along with this program; see the file COPYING.
+# If not, write to the Free Software Foundation, Inc.,
+# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
 
 #### Start of system configuration section. ####
 
@@ -38,6 +40,8 @@
 CXX = @CXX@
 CXXFLAGS = @CXXFLAGS@
 CXXCPP = @CXXCPP@
+# Both C and C++ compiler
+OBJEXT = @OBJEXT@
 # Other
 AR = ar
 AR_FLAGS = rc
@@ -58,7 +62,7 @@
 
 VPATH = $(srcdir)
 
-OBJECTS  = getopt.o getopt1.o hash.o
+OBJECTS  = getopt.$(OBJEXT) getopt1.$(OBJEXT) getline.$(OBJEXT) hash.$(OBJEXT)
 CPPFLAGS = -I$(srcdir)
 
 TARGETLIB = libgp.a
@@ -85,6 +89,9 @@
 getopt1.o : getopt1.c getopt.h
 	$(CC) $(CFLAGS) $(CPPFLAGS) -c $(srcdir)/getopt1.c
 
+getline.o : getline.cc getline.h
+	$(CXX) $(CXXFLAGS) $(CPPFLAGS) -c $(srcdir)/getline.cc
+
 hash.o : hash.cc hash.h
 	$(CXX) $(CXXFLAGS) $(CPPFLAGS) -c $(srcdir)/hash.cc
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/lib/configure
--- a/head/contrib/gperf/lib/configure	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/contrib/gperf/lib/configure	Tue Dec 06 20:26:16 2011 +0200
@@ -1,26 +1,662 @@
 #! /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.
+# Generated by GNU Autoconf 2.61.
 #
+# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001,
+# 2002, 2003, 2004, 2005, 2006 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=
+## --------------------- ##
+## M4sh Initialization.  ##
+## --------------------- ##
+
+# Be more Bourne compatible
+DUALCASE=1; export DUALCASE # for MKS sh
+if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
+  emulate sh
+  NULLCMD=:
+  # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
+  # is contrary to our usage.  Disable this feature.
+  alias -g '${1+"$@"}'='"$@"'
+  setopt NO_GLOB_SUBST
+else
+  case `(set -o) 2>/dev/null` in
+  *posix*) set -o posix ;;
+esac
+
+fi
+
+
+
+
+# PATH needs CR
+# Avoid depending upon Character Ranges.
+as_cr_letters='abcdefghijklmnopqrstuvwxyz'
+as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
+as_cr_Letters=$as_cr_letters$as_cr_LETTERS
+as_cr_digits='0123456789'
+as_cr_alnum=$as_cr_Letters$as_cr_digits
+
+# The user is always right.
+if test "${PATH_SEPARATOR+set}" != set; then
+  echo "#! /bin/sh" >conf$$.sh
+  echo  "exit 0"   >>conf$$.sh
+  chmod +x conf$$.sh
+  if (PATH="/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then
+    PATH_SEPARATOR=';'
+  else
+    PATH_SEPARATOR=:
+  fi
+  rm -f conf$$.sh
+fi
+
+# Support unset when possible.
+if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then
+  as_unset=unset
+else
+  as_unset=false
+fi
+
+
+# IFS
+# We need space, tab and new line, in precisely that order.  Quoting is
+# there to prevent editors from complaining about space-tab.
+# (If _AS_PATH_WALK were called with IFS unset, it would disable word
+# splitting by setting IFS to empty value.)
+as_nl='
+'
+IFS=" ""	$as_nl"
+
+# Find who we are.  Look in the path if we contain no directory separator.
+case $0 in
+  *[\\/]* ) as_myself=$0 ;;
+  *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+  test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break
+done
+IFS=$as_save_IFS
+
+     ;;
+esac
+# We did not find ourselves, most probably we were run as `sh COMMAND'
+# in which case we are not to be found in the path.
+if test "x$as_myself" = x; then
+  as_myself=$0
+fi
+if test ! -f "$as_myself"; then
+  echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2
+  { (exit 1); exit 1; }
+fi
+
+# Work around bugs in pre-3.0 UWIN ksh.
+for as_var in ENV MAIL MAILPATH
+do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var
+done
+PS1='$ '
+PS2='> '
+PS4='+ '
+
+# NLS nuisances.
+for as_var in \
+  LANG LANGUAGE LC_ADDRESS LC_ALL LC_COLLATE LC_CTYPE LC_IDENTIFICATION \
+  LC_MEASUREMENT LC_MESSAGES LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER \
+  LC_TELEPHONE LC_TIME
+do
+  if (set +x; test -z "`(eval $as_var=C; export $as_var) 2>&1`"); then
+    eval $as_var=C; export $as_var
+  else
+    ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var
+  fi
+done
+
+# Required to use basename.
+if expr a : '\(a\)' >/dev/null 2>&1 &&
+   test "X`expr 00001 : '.*\(...\)'`" = X001; then
+  as_expr=expr
+else
+  as_expr=false
+fi
+
+if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then
+  as_basename=basename
+else
+  as_basename=false
+fi
+
+
+# Name of the executable.
+as_me=`$as_basename -- "$0" ||
+$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
+	 X"$0" : 'X\(//\)$' \| \
+	 X"$0" : 'X\(/\)' \| . 2>/dev/null ||
+echo X/"$0" |
+    sed '/^.*\/\([^/][^/]*\)\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\/\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\/\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+
+# CDPATH.
+$as_unset CDPATH
+
+
+if test "x$CONFIG_SHELL" = x; then
+  if (eval ":") 2>/dev/null; then
+  as_have_required=yes
+else
+  as_have_required=no
+fi
+
+  if test $as_have_required = yes && 	 (eval ":
+(as_func_return () {
+  (exit \$1)
+}
+as_func_success () {
+  as_func_return 0
+}
+as_func_failure () {
+  as_func_return 1
+}
+as_func_ret_success () {
+  return 0
+}
+as_func_ret_failure () {
+  return 1
+}
+
+exitcode=0
+if as_func_success; then
+  :
+else
+  exitcode=1
+  echo as_func_success failed.
+fi
+
+if as_func_failure; then
+  exitcode=1
+  echo as_func_failure succeeded.
+fi
+
+if as_func_ret_success; then
+  :
+else
+  exitcode=1
+  echo as_func_ret_success failed.
+fi
+
+if as_func_ret_failure; then
+  exitcode=1
+  echo as_func_ret_failure succeeded.
+fi
+
+if ( set x; as_func_ret_success y && test x = \"\$1\" ); then
+  :
+else
+  exitcode=1
+  echo positional parameters were not saved.
+fi
+
+test \$exitcode = 0) || { (exit 1); exit 1; }
+
+(
+  as_lineno_1=\$LINENO
+  as_lineno_2=\$LINENO
+  test \"x\$as_lineno_1\" != \"x\$as_lineno_2\" &&
+  test \"x\`expr \$as_lineno_1 + 1\`\" = \"x\$as_lineno_2\") || { (exit 1); exit 1; }
+") 2> /dev/null; then
+  :
+else
+  as_candidate_shells=
+    as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+  case $as_dir in
+	 /*)
+	   for as_base in sh bash ksh sh5; do
+	     as_candidate_shells="$as_candidate_shells $as_dir/$as_base"
+	   done;;
+       esac
+done
+IFS=$as_save_IFS
+
+
+      for as_shell in $as_candidate_shells $SHELL; do
+	 # Try only shells that exist, to save several forks.
+	 if { test -f "$as_shell" || test -f "$as_shell.exe"; } &&
+		{ ("$as_shell") 2> /dev/null <<\_ASEOF
+if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
+  emulate sh
+  NULLCMD=:
+  # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
+  # is contrary to our usage.  Disable this feature.
+  alias -g '${1+"$@"}'='"$@"'
+  setopt NO_GLOB_SUBST
+else
+  case `(set -o) 2>/dev/null` in
+  *posix*) set -o posix ;;
+esac
+
+fi
+
+
+:
+_ASEOF
+}; then
+  CONFIG_SHELL=$as_shell
+	       as_have_required=yes
+	       if { "$as_shell" 2> /dev/null <<\_ASEOF
+if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
+  emulate sh
+  NULLCMD=:
+  # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
+  # is contrary to our usage.  Disable this feature.
+  alias -g '${1+"$@"}'='"$@"'
+  setopt NO_GLOB_SUBST
+else
+  case `(set -o) 2>/dev/null` in
+  *posix*) set -o posix ;;
+esac
+
+fi
+
+
+:
+(as_func_return () {
+  (exit $1)
+}
+as_func_success () {
+  as_func_return 0
+}
+as_func_failure () {
+  as_func_return 1
+}
+as_func_ret_success () {
+  return 0
+}
+as_func_ret_failure () {
+  return 1
+}
+
+exitcode=0
+if as_func_success; then
+  :
+else
+  exitcode=1
+  echo as_func_success failed.
+fi
+
+if as_func_failure; then
+  exitcode=1
+  echo as_func_failure succeeded.
+fi
+
+if as_func_ret_success; then
+  :
+else
+  exitcode=1
+  echo as_func_ret_success failed.
+fi
+
+if as_func_ret_failure; then
+  exitcode=1
+  echo as_func_ret_failure succeeded.
+fi
+
+if ( set x; as_func_ret_success y && test x = "$1" ); then
+  :
+else
+  exitcode=1
+  echo positional parameters were not saved.
+fi
+
+test $exitcode = 0) || { (exit 1); exit 1; }
+
+(
+  as_lineno_1=$LINENO
+  as_lineno_2=$LINENO
+  test "x$as_lineno_1" != "x$as_lineno_2" &&
+  test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2") || { (exit 1); exit 1; }
+
+_ASEOF
+}; then
+  break
+fi
+
+fi
+
+      done
+
+      if test "x$CONFIG_SHELL" != x; then
+  for as_var in BASH_ENV ENV
+        do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var
+        done
+        export CONFIG_SHELL
+        exec "$CONFIG_SHELL" "$as_myself" ${1+"$@"}
+fi
+
+
+    if test $as_have_required = no; then
+  echo This script requires a shell more modern than all the
+      echo shells that I found on your system.  Please install a
+      echo modern shell, or manually run the script under such a
+      echo shell if you do have one.
+      { (exit 1); exit 1; }
+fi
+
+
+fi
+
+fi
+
+
+
+(eval "as_func_return () {
+  (exit \$1)
+}
+as_func_success () {
+  as_func_return 0
+}
+as_func_failure () {
+  as_func_return 1
+}
+as_func_ret_success () {
+  return 0
+}
+as_func_ret_failure () {
+  return 1
+}
+
+exitcode=0
+if as_func_success; then
+  :
+else
+  exitcode=1
+  echo as_func_success failed.
+fi
+
+if as_func_failure; then
+  exitcode=1
+  echo as_func_failure succeeded.
+fi
+
+if as_func_ret_success; then
+  :
+else
+  exitcode=1
+  echo as_func_ret_success failed.
+fi
+
+if as_func_ret_failure; then
+  exitcode=1
+  echo as_func_ret_failure succeeded.
+fi
+
+if ( set x; as_func_ret_success y && test x = \"\$1\" ); then
+  :
+else
+  exitcode=1
+  echo positional parameters were not saved.
+fi
+
+test \$exitcode = 0") || {
+  echo No shell found that supports shell functions.
+  echo Please tell autoconf at gnu.org about your system,
+  echo including any error possibly output before this
+  echo message
+}
+
+
+
+  as_lineno_1=$LINENO
+  as_lineno_2=$LINENO
+  test "x$as_lineno_1" != "x$as_lineno_2" &&
+  test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2" || {
+
+  # Create $as_me.lineno as a copy of $as_myself, but with $LINENO
+  # uniformly replaced by the line number.  The first 'sed' inserts a
+  # line-number line after each line using $LINENO; the second 'sed'
+  # does the real work.  The second script uses 'N' to pair each
+  # line-number line with the line containing $LINENO, and appends
+  # trailing '-' during substitution so that $LINENO is not a special
+  # case at line end.
+  # (Raja R Harinath suggested sed '=', and Paul Eggert wrote the
+  # scripts with optimization help from Paolo Bonzini.  Blame Lee
+  # E. McMahon (1931-1989) for sed's syntax.  :-)
+  sed -n '
+    p
+    /[$]LINENO/=
+  ' <$as_myself |
+    sed '
+      s/[$]LINENO.*/&-/
+      t lineno
+      b
+      :lineno
+      N
+      :loop
+      s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/
+      t loop
+      s/-\n.*//
+    ' >$as_me.lineno &&
+  chmod +x "$as_me.lineno" ||
+    { echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2
+   { (exit 1); exit 1; }; }
+
+  # Don't try to exec as it changes $[0], causing all sort of problems
+  # (the dirname of $[0] is not the place where we might find the
+  # original and so on.  Autoconf is especially sensitive to this).
+  . "./$as_me.lineno"
+  # Exit status is that of the last command.
+  exit
+}
+
+
+if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then
+  as_dirname=dirname
+else
+  as_dirname=false
+fi
+
+ECHO_C= ECHO_N= ECHO_T=
+case `echo -n x` in
+-n*)
+  case `echo 'x\c'` in
+  *c*) ECHO_T='	';;	# ECHO_T is single tab character.
+  *)   ECHO_C='\c';;
+  esac;;
+*)
+  ECHO_N='-n';;
+esac
+
+if expr a : '\(a\)' >/dev/null 2>&1 &&
+   test "X`expr 00001 : '.*\(...\)'`" = X001; then
+  as_expr=expr
+else
+  as_expr=false
+fi
+
+rm -f conf$$ conf$$.exe conf$$.file
+if test -d conf$$.dir; then
+  rm -f conf$$.dir/conf$$.file
+else
+  rm -f conf$$.dir
+  mkdir conf$$.dir
+fi
+echo >conf$$.file
+if ln -s conf$$.file conf$$ 2>/dev/null; then
+  as_ln_s='ln -s'
+  # ... but there are two gotchas:
+  # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail.
+  # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable.
+  # In both cases, we have to default to `cp -p'.
+  ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe ||
+    as_ln_s='cp -p'
+elif ln conf$$.file conf$$ 2>/dev/null; then
+  as_ln_s=ln
+else
+  as_ln_s='cp -p'
+fi
+rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file
+rmdir conf$$.dir 2>/dev/null
+
+if mkdir -p . 2>/dev/null; then
+  as_mkdir_p=:
+else
+  test -d ./-p && rmdir ./-p
+  as_mkdir_p=false
+fi
+
+if test -x / >/dev/null 2>&1; then
+  as_test_x='test -x'
+else
+  if ls -dL / >/dev/null 2>&1; then
+    as_ls_L_option=L
+  else
+    as_ls_L_option=
+  fi
+  as_test_x='
+    eval sh -c '\''
+      if test -d "$1"; then
+        test -d "$1/.";
+      else
+	case $1 in
+        -*)set "./$1";;
+	esac;
+	case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in
+	???[sx]*):;;*)false;;esac;fi
+    '\'' sh
+  '
+fi
+as_executable_p=$as_test_x
+
+# Sed expression to map a string onto a valid CPP name.
+as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
+
+# Sed expression to map a string onto a valid variable name.
+as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'"
+
+
+
+exec 7<&0 </dev/null 6>&1
+
+# Name of the host.
+# hostname on some systems (SVR3.2, Linux) returns a bogus exit status,
+# so uname gets run too.
+ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q`
+
+#
+# Initializations.
+#
 ac_default_prefix=/usr/local
-# Any additions from configure.in:
+ac_clean_files=
+ac_config_libobj_dir=.
+LIBOBJS=
+cross_compiling=no
+subdirs=
+MFLAGS=
+MAKEFLAGS=
+SHELL=${CONFIG_SHELL-/bin/sh}
+
+# Identity of this package.
+PACKAGE_NAME=
+PACKAGE_TARNAME=
+PACKAGE_VERSION=
+PACKAGE_STRING=
+PACKAGE_BUGREPORT=
+
+ac_unique_file="hash.cc"
+ac_subst_vars='SHELL
+PATH_SEPARATOR
+PACKAGE_NAME
+PACKAGE_TARNAME
+PACKAGE_VERSION
+PACKAGE_STRING
+PACKAGE_BUGREPORT
+exec_prefix
+prefix
+program_transform_name
+bindir
+sbindir
+libexecdir
+datarootdir
+datadir
+sysconfdir
+sharedstatedir
+localstatedir
+includedir
+oldincludedir
+docdir
+infodir
+htmldir
+dvidir
+pdfdir
+psdir
+libdir
+localedir
+mandir
+DEFS
+ECHO_C
+ECHO_N
+ECHO_T
+LIBS
+build_alias
+host_alias
+target_alias
+SET_MAKE
+CC
+CFLAGS
+LDFLAGS
+CPPFLAGS
+ac_ct_CC
+EXEEXT
+OBJEXT
+CPP
+CXX
+CXXFLAGS
+ac_ct_CXX
+CXXCPP
+RANLIB
+INSTALL
+INSTALL_PROGRAM
+INSTALL_DATA
+LIBOBJS
+LTLIBOBJS'
+ac_subst_files=''
+      ac_precious_vars='build_alias
+host_alias
+target_alias
+CC
+CFLAGS
+LDFLAGS
+LIBS
+CPPFLAGS
+CPP
+CXX
+CXXFLAGS
+CCC
+CXXCPP'
+
 
 # Initialize some variables set by options.
+ac_init_help=
+ac_init_version=false
 # The variables have the same names as the options, with
 # dashes changed to underlines.
-build=NONE
-cache_file=./config.cache
+cache_file=/dev/null
 exec_prefix=NONE
-host=NONE
 no_create=
-nonopt=NONE
 no_recursion=
 prefix=NONE
 program_prefix=NONE
@@ -29,94 +665,117 @@
 silent=
 site=
 srcdir=
-target=NONE
 verbose=
 x_includes=NONE
 x_libraries=NONE
+
+# Installation directory options.
+# These are left unexpanded so users can "make install exec_prefix=/foo"
+# and all the variables that are supposed to be based on exec_prefix
+# by default will actually change.
+# Use braces instead of parens because sh, perl, etc. also accept them.
+# (The list follows the same order as the GNU Coding Standards.)
 bindir='${exec_prefix}/bin'
 sbindir='${exec_prefix}/sbin'
 libexecdir='${exec_prefix}/libexec'
-datadir='${prefix}/share'
+datarootdir='${prefix}/share'
+datadir='${datarootdir}'
 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
+docdir='${datarootdir}/doc/${PACKAGE}'
+infodir='${datarootdir}/info'
+htmldir='${docdir}'
+dvidir='${docdir}'
+pdfdir='${docdir}'
+psdir='${docdir}'
+libdir='${exec_prefix}/lib'
+localedir='${datarootdir}/locale'
+mandir='${datarootdir}/man'
 
 ac_prev=
+ac_dashdash=
 for ac_option
 do
-
   # If the previous option needs an argument, assign it.
   if test -n "$ac_prev"; then
-    eval "$ac_prev=\$ac_option"
+    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= ;;
+  case $ac_option in
+  *=*)	ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;;
+  *)	ac_optarg=yes ;;
   esac
 
   # Accept the important Cygnus configure options, so we can diagnose typos.
 
-  case "$ac_option" in
+  case $ac_dashdash$ac_option in
+  --)
+    ac_dashdash=yes ;;
 
   -bindir | --bindir | --bindi | --bind | --bin | --bi)
     ac_prev=bindir ;;
   -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*)
-    bindir="$ac_optarg" ;;
+    bindir=$ac_optarg ;;
 
   -build | --build | --buil | --bui | --bu)
-    ac_prev=build ;;
+    ac_prev=build_alias ;;
   -build=* | --build=* | --buil=* | --bui=* | --bu=*)
-    build="$ac_optarg" ;;
+    build_alias=$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)
+    cache_file=$ac_optarg ;;
+
+  --config-cache | -C)
+    cache_file=config.cache ;;
+
+  -datadir | --datadir | --datadi | --datad)
     ac_prev=datadir ;;
-  -datadir=* | --datadir=* | --datadi=* | --datad=* | --data=* | --dat=* \
-  | --da=*)
-    datadir="$ac_optarg" ;;
+  -datadir=* | --datadir=* | --datadi=* | --datad=*)
+    datadir=$ac_optarg ;;
+
+  -datarootdir | --datarootdir | --datarootdi | --datarootd | --dataroot \
+  | --dataroo | --dataro | --datar)
+    ac_prev=datarootdir ;;
+  -datarootdir=* | --datarootdir=* | --datarootdi=* | --datarootd=* \
+  | --dataroot=* | --dataroo=* | --dataro=* | --datar=*)
+    datarootdir=$ac_optarg ;;
 
   -disable-* | --disable-*)
-    ac_feature=`echo $ac_option|sed -e 's/-*disable-//'`
+    ac_feature=`expr "x$ac_option" : 'x-*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" ;;
+    expr "x$ac_feature" : ".*[^-._$as_cr_alnum]" >/dev/null &&
+      { echo "$as_me: error: invalid feature name: $ac_feature" >&2
+   { (exit 1); exit 1; }; }
+    ac_feature=`echo $ac_feature | sed 's/[-.]/_/g'`
+    eval enable_$ac_feature=no ;;
+
+  -docdir | --docdir | --docdi | --doc | --do)
+    ac_prev=docdir ;;
+  -docdir=* | --docdir=* | --docdi=* | --doc=* | --do=*)
+    docdir=$ac_optarg ;;
+
+  -dvidir | --dvidir | --dvidi | --dvid | --dvi | --dv)
+    ac_prev=dvidir ;;
+  -dvidir=* | --dvidir=* | --dvidi=* | --dvid=* | --dvi=* | --dv=*)
+    dvidir=$ac_optarg ;;
 
   -enable-* | --enable-*)
-    ac_feature=`echo $ac_option|sed -e 's/-*enable-//' -e 's/=.*//'`
+    ac_feature=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'`
     # 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'" ;;
+    expr "x$ac_feature" : ".*[^-._$as_cr_alnum]" >/dev/null &&
+      { echo "$as_me: error: invalid feature name: $ac_feature" >&2
+   { (exit 1); exit 1; }; }
+    ac_feature=`echo $ac_feature | sed 's/[-.]/_/g'`
+    eval enable_$ac_feature=\$ac_optarg ;;
 
   -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \
   | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \
@@ -125,116 +784,77 @@
   -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \
   | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \
   | --exec=* | --exe=* | --ex=*)
-    exec_prefix="$ac_optarg" ;;
+    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 ;;
+  -help | --help | --hel | --he | -h)
+    ac_init_help=long ;;
+  -help=r* | --help=r* | --hel=r* | --he=r* | -hr*)
+    ac_init_help=recursive ;;
+  -help=s* | --help=s* | --hel=s* | --he=s* | -hs*)
+    ac_init_help=short ;;
 
   -host | --host | --hos | --ho)
-    ac_prev=host ;;
+    ac_prev=host_alias ;;
   -host=* | --host=* | --hos=* | --ho=*)
-    host="$ac_optarg" ;;
+    host_alias=$ac_optarg ;;
+
+  -htmldir | --htmldir | --htmldi | --htmld | --html | --htm | --ht)
+    ac_prev=htmldir ;;
+  -htmldir=* | --htmldir=* | --htmldi=* | --htmld=* | --html=* | --htm=* \
+  | --ht=*)
+    htmldir=$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" ;;
+    includedir=$ac_optarg ;;
 
   -infodir | --infodir | --infodi | --infod | --info | --inf)
     ac_prev=infodir ;;
   -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*)
-    infodir="$ac_optarg" ;;
+    infodir=$ac_optarg ;;
 
   -libdir | --libdir | --libdi | --libd)
     ac_prev=libdir ;;
   -libdir=* | --libdir=* | --libdi=* | --libd=*)
-    libdir="$ac_optarg" ;;
+    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" ;;
+    libexecdir=$ac_optarg ;;
+
+  -localedir | --localedir | --localedi | --localed | --locale)
+    ac_prev=localedir ;;
+  -localedir=* | --localedir=* | --localedi=* | --localed=* | --locale=*)
+    localedir=$ac_optarg ;;
 
   -localstatedir | --localstatedir | --localstatedi | --localstated \
-  | --localstate | --localstat | --localsta | --localst \
-  | --locals | --local | --loca | --loc | --lo)
+  | --localstate | --localstat | --localsta | --localst | --locals)
     ac_prev=localstatedir ;;
   -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \
-  | --localstate=* | --localstat=* | --localsta=* | --localst=* \
-  | --locals=* | --local=* | --loca=* | --loc=* | --lo=*)
-    localstatedir="$ac_optarg" ;;
+  | --localstate=* | --localstat=* | --localsta=* | --localst=* | --locals=*)
+    localstatedir=$ac_optarg ;;
 
   -mandir | --mandir | --mandi | --mand | --man | --ma | --m)
     ac_prev=mandir ;;
   -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*)
-    mandir="$ac_optarg" ;;
+    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-cr | --no-c | -n)
     no_create=yes ;;
 
   -no-recursion | --no-recursion | --no-recursio | --no-recursi \
@@ -248,26 +868,26 @@
   -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \
   | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \
   | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*)
-    oldincludedir="$ac_optarg" ;;
+    oldincludedir=$ac_optarg ;;
 
   -prefix | --prefix | --prefi | --pref | --pre | --pr | --p)
     ac_prev=prefix ;;
   -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*)
-    prefix="$ac_optarg" ;;
+    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_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_suffix=$ac_optarg ;;
 
   -program-transform-name | --program-transform-name \
   | --program-transform-nam | --program-transform-na \
@@ -284,7 +904,17 @@
   | --program-transfo=* | --program-transf=* \
   | --program-trans=* | --program-tran=* \
   | --progr-tra=* | --program-tr=* | --program-t=*)
-    program_transform_name="$ac_optarg" ;;
+    program_transform_name=$ac_optarg ;;
+
+  -pdfdir | --pdfdir | --pdfdi | --pdfd | --pdf | --pd)
+    ac_prev=pdfdir ;;
+  -pdfdir=* | --pdfdir=* | --pdfdi=* | --pdfd=* | --pdf=* | --pd=*)
+    pdfdir=$ac_optarg ;;
+
+  -psdir | --psdir | --psdi | --psd | --ps)
+    ac_prev=psdir ;;
+  -psdir=* | --psdir=* | --psdi=* | --psd=* | --ps=*)
+    psdir=$ac_optarg ;;
 
   -q | -quiet | --quiet | --quie | --qui | --qu | --q \
   | -silent | --silent | --silen | --sile | --sil)
@@ -294,7 +924,7 @@
     ac_prev=sbindir ;;
   -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \
   | --sbi=* | --sb=*)
-    sbindir="$ac_optarg" ;;
+    sbindir=$ac_optarg ;;
 
   -sharedstatedir | --sharedstatedir | --sharedstatedi \
   | --sharedstated | --sharedstate | --sharedstat | --sharedsta \
@@ -305,58 +935,53 @@
   | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \
   | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \
   | --sha=* | --sh=*)
-    sharedstatedir="$ac_optarg" ;;
+    sharedstatedir=$ac_optarg ;;
 
   -site | --site | --sit)
     ac_prev=site ;;
   -site=* | --site=* | --sit=*)
-    site="$ac_optarg" ;;
+    site=$ac_optarg ;;
 
   -srcdir | --srcdir | --srcdi | --srcd | --src | --sr)
     ac_prev=srcdir ;;
   -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*)
-    srcdir="$ac_optarg" ;;
+    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" ;;
+    sysconfdir=$ac_optarg ;;
 
   -target | --target | --targe | --targ | --tar | --ta | --t)
-    ac_prev=target ;;
+    ac_prev=target_alias ;;
   -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*)
-    target="$ac_optarg" ;;
+    target_alias=$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 ;;
+  -version | --version | --versio | --versi | --vers | -V)
+    ac_init_version=: ;;
 
   -with-* | --with-*)
-    ac_package=`echo $ac_option|sed -e 's/-*with-//' -e 's/=.*//'`
+    ac_package=`expr "x$ac_option" : 'x-*with-\([^=]*\)'`
     # 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'" ;;
+    expr "x$ac_package" : ".*[^-._$as_cr_alnum]" >/dev/null &&
+      { echo "$as_me: error: invalid package name: $ac_package" >&2
+   { (exit 1); exit 1; }; }
+    ac_package=`echo $ac_package | sed 's/[-.]/_/g'`
+    eval with_$ac_package=\$ac_optarg ;;
 
   -without-* | --without-*)
-    ac_package=`echo $ac_option|sed -e 's/-*without-//'`
+    ac_package=`expr "x$ac_option" : 'x-*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" ;;
+    expr "x$ac_package" : ".*[^-._$as_cr_alnum]" >/dev/null &&
+      { echo "$as_me: error: invalid package name: $ac_package" >&2
+   { (exit 1); exit 1; }; }
+    ac_package=`echo $ac_package | sed 's/[-.]/_/g'`
+    eval with_$ac_package=no ;;
 
   --x)
     # Obsolete; use --with-x.
@@ -367,395 +992,1476 @@
     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_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; }
+    x_libraries=$ac_optarg ;;
+
+  -*) { echo "$as_me: error: unrecognized option: $ac_option
+Try \`$0 --help' for more information." >&2
+   { (exit 1); exit 1; }; }
     ;;
 
+  *=*)
+    ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='`
+    # Reject names that are not valid shell variable names.
+    expr "x$ac_envvar" : ".*[^_$as_cr_alnum]" >/dev/null &&
+      { echo "$as_me: error: invalid variable name: $ac_envvar" >&2
+   { (exit 1); exit 1; }; }
+    eval $ac_envvar=\$ac_optarg
+    export $ac_envvar ;;
+
   *)
-    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"
+    # FIXME: should be removed in autoconf 3.0.
+    echo "$as_me: WARNING: you should use --build, --host, --target" >&2
+    expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null &&
+      echo "$as_me: WARNING: invalid host type: $ac_option" >&2
+    : ${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$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; }
+  ac_option=--`echo $ac_prev | sed 's/_/-/g'`
+  { echo "$as_me: error: missing argument to $ac_option" >&2
+   { (exit 1); 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
+# Be sure to have absolute directory names.
+for ac_var in	exec_prefix prefix bindir sbindir libexecdir datarootdir \
+		datadir sysconfdir sharedstatedir localstatedir includedir \
+		oldincludedir docdir infodir htmldir dvidir pdfdir psdir \
+		libdir localedir mandir
+do
+  eval ac_val=\$$ac_var
+  case $ac_val in
+    [\\/$]* | ?:[\\/]* )  continue;;
+    NONE | '' ) case $ac_var in *prefix ) continue;; esac;;
+  esac
+  { echo "$as_me: error: expected an absolute directory name for --$ac_var: $ac_val" >&2
+   { (exit 1); exit 1; }; }
+done
+
+# There might be people who depend on the old broken behavior: `$host'
+# used to hold the argument of --host etc.
+# FIXME: To remove some day.
+build=$build_alias
+host=$host_alias
+target=$target_alias
+
+# FIXME: To remove some day.
+if test "x$host_alias" != x; then
+  if test "x$build_alias" = x; then
+    cross_compiling=maybe
+    echo "$as_me: WARNING: If you wanted to set the --build type, don't use --host.
+    If a cross compiler is detected then cross compile mode will be used." >&2
+  elif test "x$build_alias" != "x$host_alias"; then
+    cross_compiling=yes
+  fi
 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=hash.cc
+
+ac_tool_prefix=
+test -n "$host_alias" && ac_tool_prefix=$host_alias-
+
+test "$silent" = yes && exec 6>/dev/null
+
+
+ac_pwd=`pwd` && test -n "$ac_pwd" &&
+ac_ls_di=`ls -di .` &&
+ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` ||
+  { echo "$as_me: error: Working directory cannot be determined" >&2
+   { (exit 1); exit 1; }; }
+test "X$ac_ls_di" = "X$ac_pwd_ls_di" ||
+  { echo "$as_me: error: pwd does not report name of working directory" >&2
+   { (exit 1); exit 1; }; }
+
 
 # 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=.
+  # Try the directory containing this script, then the parent directory.
+  ac_confdir=`$as_dirname -- "$0" ||
+$as_expr X"$0" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+	 X"$0" : 'X\(//\)[^/]' \| \
+	 X"$0" : 'X\(//\)$' \| \
+	 X"$0" : 'X\(/\)' \| . 2>/dev/null ||
+echo X"$0" |
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)[^/].*/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
   srcdir=$ac_confdir
-  if test ! -r $srcdir/$ac_unique_file; then
+  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
+if test ! -r "$srcdir/$ac_unique_file"; then
+  test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .."
+  { echo "$as_me: error: cannot find sources ($ac_unique_file) in $srcdir" >&2
+   { (exit 1); exit 1; }; }
 fi
-srcdir=`echo "${srcdir}" | sed 's%\([^/]\)/*$%\1%'`
-
+ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work"
+ac_abs_confdir=`(
+	cd "$srcdir" && test -r "./$ac_unique_file" || { echo "$as_me: error: $ac_msg" >&2
+   { (exit 1); exit 1; }; }
+	pwd)`
+# When building in place, set srcdir=.
+if test "$ac_abs_confdir" = "$ac_pwd"; then
+  srcdir=.
+fi
+# Remove unnecessary trailing slashes from srcdir.
+# Double slashes in file names in object file debugging info
+# mess up M-x gdb in Emacs.
+case $srcdir in
+*/) srcdir=`expr "X$srcdir" : 'X\(.*[^/]\)' \| "X$srcdir" : 'X\(.*\)'`;;
+esac
+for ac_var in $ac_precious_vars; do
+  eval ac_env_${ac_var}_set=\${${ac_var}+set}
+  eval ac_env_${ac_var}_value=\$${ac_var}
+  eval ac_cv_env_${ac_var}_set=\${${ac_var}+set}
+  eval ac_cv_env_${ac_var}_value=\$${ac_var}
+done
+
+#
+# Report the --help message.
+#
+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 this package to adapt to many kinds of systems.
+
+Usage: $0 [OPTION]... [VAR=VALUE]...
+
+To assign environment variables (e.g., CC, CFLAGS...), specify them as
+VAR=VALUE.  See below for descriptions of some of the useful variables.
+
+Defaults for the options are specified in brackets.
+
+Configuration:
+  -h, --help              display this help and exit
+      --help=short        display options specific to this package
+      --help=recursive    display the short help of all the included packages
+  -V, --version           display version information and exit
+  -q, --quiet, --silent   do not print \`checking...' messages
+      --cache-file=FILE   cache test results in FILE [disabled]
+  -C, --config-cache      alias for \`--cache-file=config.cache'
+  -n, --no-create         do not create output files
+      --srcdir=DIR        find the sources in DIR [configure dir or \`..']
+
+Installation directories:
+  --prefix=PREFIX         install architecture-independent files in PREFIX
+			  [$ac_default_prefix]
+  --exec-prefix=EPREFIX   install architecture-dependent files in EPREFIX
+			  [PREFIX]
+
+By default, \`make install' will install all the files in
+\`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc.  You can specify
+an installation prefix other than \`$ac_default_prefix' using \`--prefix',
+for instance \`--prefix=\$HOME'.
+
+For better control, use the options below.
+
+Fine tuning of the installation directories:
+  --bindir=DIR           user executables [EPREFIX/bin]
+  --sbindir=DIR          system admin executables [EPREFIX/sbin]
+  --libexecdir=DIR       program executables [EPREFIX/libexec]
+  --sysconfdir=DIR       read-only single-machine data [PREFIX/etc]
+  --sharedstatedir=DIR   modifiable architecture-independent data [PREFIX/com]
+  --localstatedir=DIR    modifiable single-machine data [PREFIX/var]
+  --libdir=DIR           object code libraries [EPREFIX/lib]
+  --includedir=DIR       C header files [PREFIX/include]
+  --oldincludedir=DIR    C header files for non-gcc [/usr/include]
+  --datarootdir=DIR      read-only arch.-independent data root [PREFIX/share]
+  --datadir=DIR          read-only architecture-independent data [DATAROOTDIR]
+  --infodir=DIR          info documentation [DATAROOTDIR/info]
+  --localedir=DIR        locale-dependent data [DATAROOTDIR/locale]
+  --mandir=DIR           man documentation [DATAROOTDIR/man]
+  --docdir=DIR           documentation root [DATAROOTDIR/doc/PACKAGE]
+  --htmldir=DIR          html documentation [DOCDIR]
+  --dvidir=DIR           dvi documentation [DOCDIR]
+  --pdfdir=DIR           pdf documentation [DOCDIR]
+  --psdir=DIR            ps documentation [DOCDIR]
+_ACEOF
+
+  cat <<\_ACEOF
+_ACEOF
+fi
+
+if test -n "$ac_init_help"; then
+
+  cat <<\_ACEOF
+
+Some influential environment variables:
+  CC          C compiler command
+  CFLAGS      C compiler flags
+  LDFLAGS     linker flags, e.g. -L<lib dir> if you have libraries in a
+              nonstandard directory <lib dir>
+  LIBS        libraries to pass to the linker, e.g. -l<library>
+  CPPFLAGS    C/C++/Objective C preprocessor flags, e.g. -I<include dir> if
+              you have headers in a nonstandard directory <include dir>
+  CPP         C preprocessor
+  CXX         C++ compiler command
+  CXXFLAGS    C++ compiler flags
+  CXXCPP      C++ preprocessor
+
+Use these variables to override the choices made by `configure' or to help
+it to find libraries and programs with nonstandard names/locations.
+
+_ACEOF
+ac_status=$?
+fi
+
+if test "$ac_init_help" = "recursive"; then
+  # If there are subdirs, report their specific --help.
+  for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue
+    test -d "$ac_dir" || continue
+    ac_builddir=.
+
+case "$ac_dir" in
+.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;
+*)
+  ac_dir_suffix=/`echo "$ac_dir" | sed 's,^\.[\\/],,'`
+  # A ".." for each directory in $ac_dir_suffix.
+  ac_top_builddir_sub=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,/..,g;s,/,,'`
+  case $ac_top_builddir_sub in
+  "") ac_top_builddir_sub=. ac_top_build_prefix= ;;
+  *)  ac_top_build_prefix=$ac_top_builddir_sub/ ;;
+  esac ;;
+esac
+ac_abs_top_builddir=$ac_pwd
+ac_abs_builddir=$ac_pwd$ac_dir_suffix
+# for backward compatibility:
+ac_top_builddir=$ac_top_build_prefix
+
+case $srcdir in
+  .)  # We are building in place.
+    ac_srcdir=.
+    ac_top_srcdir=$ac_top_builddir_sub
+    ac_abs_top_srcdir=$ac_pwd ;;
+  [\\/]* | ?:[\\/]* )  # Absolute name.
+    ac_srcdir=$srcdir$ac_dir_suffix;
+    ac_top_srcdir=$srcdir
+    ac_abs_top_srcdir=$srcdir ;;
+  *) # Relative name.
+    ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix
+    ac_top_srcdir=$ac_top_build_prefix$srcdir
+    ac_abs_top_srcdir=$ac_pwd/$srcdir ;;
+esac
+ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix
+
+    cd "$ac_dir" || { ac_status=$?; continue; }
+    # Check for guested configure.
+    if test -f "$ac_srcdir/configure.gnu"; then
+      echo &&
+      $SHELL "$ac_srcdir/configure.gnu" --help=recursive
+    elif test -f "$ac_srcdir/configure"; then
+      echo &&
+      $SHELL "$ac_srcdir/configure" --help=recursive
+    else
+      echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2
+    fi || ac_status=$?
+    cd "$ac_pwd" || { ac_status=$?; break; }
+  done
+fi
+
+test -n "$ac_init_help" && exit $ac_status
+if $ac_init_version; then
+  cat <<\_ACEOF
+configure
+generated by GNU Autoconf 2.61
+
+Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001,
+2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc.
+This configure script is free software; the Free Software Foundation
+gives unlimited permission to copy, distribute and modify it.
+_ACEOF
+  exit
+fi
+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 $as_me, which was
+generated by GNU Autoconf 2.61.  Invocation command line was
+
+  $ $0 $@
+
+_ACEOF
+exec 5>>config.log
+{
+cat <<_ASUNAME
+## --------- ##
+## Platform. ##
+## --------- ##
+
+hostname = `(hostname || uname -n) 2>/dev/null | sed 1q`
+uname -m = `(uname -m) 2>/dev/null || echo unknown`
+uname -r = `(uname -r) 2>/dev/null || echo unknown`
+uname -s = `(uname -s) 2>/dev/null || echo unknown`
+uname -v = `(uname -v) 2>/dev/null || echo unknown`
+
+/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown`
+/bin/uname -X     = `(/bin/uname -X) 2>/dev/null     || echo unknown`
+
+/bin/arch              = `(/bin/arch) 2>/dev/null              || echo unknown`
+/usr/bin/arch -k       = `(/usr/bin/arch -k) 2>/dev/null       || echo unknown`
+/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown`
+/usr/bin/hostinfo      = `(/usr/bin/hostinfo) 2>/dev/null      || echo unknown`
+/bin/machine           = `(/bin/machine) 2>/dev/null           || echo unknown`
+/usr/bin/oslevel       = `(/usr/bin/oslevel) 2>/dev/null       || echo unknown`
+/bin/universe          = `(/bin/universe) 2>/dev/null          || echo unknown`
+
+_ASUNAME
+
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+  echo "PATH: $as_dir"
+done
+IFS=$as_save_IFS
+
+} >&5
+
+cat >&5 <<_ACEOF
+
+
+## ----------- ##
+## Core tests. ##
+## ----------- ##
+
+_ACEOF
+
+
+# Keep a trace of the command line.
+# Strip out --no-create and --no-recursion so they do not pile up.
+# Strip out --silent because we don't want to record it for future runs.
+# Also quote any args containing shell meta-characters.
+# Make two passes to allow for proper duplicate-argument suppression.
+ac_configure_args=
+ac_configure_args0=
+ac_configure_args1=
+ac_must_keep_next=false
+for ac_pass in 1 2
+do
+  for ac_arg
+  do
+    case $ac_arg in
+    -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;;
+    -q | -quiet | --quiet | --quie | --qui | --qu | --q \
+    | -silent | --silent | --silen | --sile | --sil)
+      continue ;;
+    *\'*)
+      ac_arg=`echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;;
+    esac
+    case $ac_pass in
+    1) ac_configure_args0="$ac_configure_args0 '$ac_arg'" ;;
+    2)
+      ac_configure_args1="$ac_configure_args1 '$ac_arg'"
+      if test $ac_must_keep_next = true; then
+	ac_must_keep_next=false # Got value, back to normal.
+      else
+	case $ac_arg in
+	  *=* | --config-cache | -C | -disable-* | --disable-* \
+	  | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \
+	  | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \
+	  | -with-* | --with-* | -without-* | --without-* | --x)
+	    case "$ac_configure_args0 " in
+	      "$ac_configure_args1"*" '$ac_arg' "* ) continue ;;
+	    esac
+	    ;;
+	  -* ) ac_must_keep_next=true ;;
+	esac
+      fi
+      ac_configure_args="$ac_configure_args '$ac_arg'"
+      ;;
+    esac
+  done
+done
+$as_unset ac_configure_args0 || test "${ac_configure_args0+set}" != set || { ac_configure_args0=; export ac_configure_args0; }
+$as_unset ac_configure_args1 || test "${ac_configure_args1+set}" != set || { ac_configure_args1=; export ac_configure_args1; }
+
+# When interrupted or exit'd, cleanup temporary files, and complete
+# config.log.  We remove comments because anyway the quotes in there
+# would cause problems or look ugly.
+# WARNING: Use '\'' to represent an apostrophe within the trap.
+# WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug.
+trap 'exit_status=$?
+  # Save into config.log some information that might help in debugging.
+  {
+    echo
+
+    cat <<\_ASBOX
+## ---------------- ##
+## Cache variables. ##
+## ---------------- ##
+_ASBOX
+    echo
+    # The following way of writing the cache mishandles newlines in values,
+(
+  for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do
+    eval ac_val=\$$ac_var
+    case $ac_val in #(
+    *${as_nl}*)
+      case $ac_var in #(
+      *_cv_*) { echo "$as_me:$LINENO: WARNING: Cache variable $ac_var contains a newline." >&5
+echo "$as_me: WARNING: Cache variable $ac_var contains a newline." >&2;} ;;
+      esac
+      case $ac_var in #(
+      _ | IFS | as_nl) ;; #(
+      *) $as_unset $ac_var ;;
+      esac ;;
+    esac
+  done
+  (set) 2>&1 |
+    case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #(
+    *${as_nl}ac_space=\ *)
+      sed -n \
+	"s/'\''/'\''\\\\'\'''\''/g;
+	  s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p"
+      ;; #(
+    *)
+      sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p"
+      ;;
+    esac |
+    sort
+)
+    echo
+
+    cat <<\_ASBOX
+## ----------------- ##
+## Output variables. ##
+## ----------------- ##
+_ASBOX
+    echo
+    for ac_var in $ac_subst_vars
+    do
+      eval ac_val=\$$ac_var
+      case $ac_val in
+      *\'\''*) ac_val=`echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;;
+      esac
+      echo "$ac_var='\''$ac_val'\''"
+    done | sort
+    echo
+
+    if test -n "$ac_subst_files"; then
+      cat <<\_ASBOX
+## ------------------- ##
+## File substitutions. ##
+## ------------------- ##
+_ASBOX
+      echo
+      for ac_var in $ac_subst_files
+      do
+	eval ac_val=\$$ac_var
+	case $ac_val in
+	*\'\''*) ac_val=`echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;;
+	esac
+	echo "$ac_var='\''$ac_val'\''"
+      done | sort
+      echo
+    fi
+
+    if test -s confdefs.h; then
+      cat <<\_ASBOX
+## ----------- ##
+## confdefs.h. ##
+## ----------- ##
+_ASBOX
+      echo
+      cat confdefs.h
+      echo
+    fi
+    test "$ac_signal" != 0 &&
+      echo "$as_me: caught signal $ac_signal"
+    echo "$as_me: exit $exit_status"
+  } >&5
+  rm -f core *.core core.conftest.* &&
+    rm -f -r conftest* confdefs* conf$$* $ac_clean_files &&
+    exit $exit_status
+' 0
+for ac_signal in 1 2 13 15; do
+  trap 'ac_signal='$ac_signal'; { (exit 1); exit 1; }' $ac_signal
+done
+ac_signal=0
+
+# confdefs.h avoids OS command line length limits that DEFS can exceed.
+rm -f -r conftest* confdefs.h
+
+# Predefined preprocessor variables.
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_NAME "$PACKAGE_NAME"
+_ACEOF
+
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_TARNAME "$PACKAGE_TARNAME"
+_ACEOF
+
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_VERSION "$PACKAGE_VERSION"
+_ACEOF
+
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_STRING "$PACKAGE_STRING"
+_ACEOF
+
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT"
+_ACEOF
+
+
+# Let the site file select an alternate cache file if it wants to.
 # 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
+if test -n "$CONFIG_SITE"; then
+  set x "$CONFIG_SITE"
+elif test "x$prefix" != xNONE; then
+  set x "$prefix/share/config.site" "$prefix/etc/config.site"
+else
+  set x "$ac_default_prefix/share/config.site" \
+	"$ac_default_prefix/etc/config.site"
 fi
-for ac_site_file in $CONFIG_SITE; do
+shift
+for ac_site_file
+do
   if test -r "$ac_site_file"; then
-    echo "loading site script $ac_site_file"
+    { echo "$as_me:$LINENO: loading site script $ac_site_file" >&5
+echo "$as_me: loading site script $ac_site_file" >&6;}
+    sed 's/^/| /' "$ac_site_file" >&5
     . "$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 at 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=
+  # Some versions of bash will fail to source /dev/null (special
+  # files actually), so we avoid doing that.
+  if test -f "$cache_file"; then
+    { echo "$as_me:$LINENO: loading cache $cache_file" >&5
+echo "$as_me: loading cache $cache_file" >&6;}
+    case $cache_file in
+      [\\/]* | ?:[\\/]* ) . "$cache_file";;
+      *)                      . "./$cache_file";;
+    esac
   fi
 else
-  ac_n= ac_c='\c' ac_t=
+  { echo "$as_me:$LINENO: creating cache $cache_file" >&5
+echo "$as_me: creating cache $cache_file" >&6;}
+  >$cache_file
 fi
 
-
-echo $ac_n "checking whether ${MAKE-make} sets \${MAKE}""... $ac_c" 1>&6
-echo "configure:526: 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
+# Check that the precious variables saved in the cache have kept the same
+# value.
+ac_cache_corrupted=false
+for ac_var in $ac_precious_vars; do
+  eval ac_old_set=\$ac_cv_env_${ac_var}_set
+  eval ac_new_set=\$ac_env_${ac_var}_set
+  eval ac_old_val=\$ac_cv_env_${ac_var}_value
+  eval ac_new_val=\$ac_env_${ac_var}_value
+  case $ac_old_set,$ac_new_set in
+    set,)
+      { echo "$as_me:$LINENO: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5
+echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;}
+      ac_cache_corrupted=: ;;
+    ,set)
+      { echo "$as_me:$LINENO: error: \`$ac_var' was not set in the previous run" >&5
+echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;}
+      ac_cache_corrupted=: ;;
+    ,);;
+    *)
+      if test "x$ac_old_val" != "x$ac_new_val"; then
+	{ echo "$as_me:$LINENO: error: \`$ac_var' has changed since the previous run:" >&5
+echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;}
+	{ echo "$as_me:$LINENO:   former value:  $ac_old_val" >&5
+echo "$as_me:   former value:  $ac_old_val" >&2;}
+	{ echo "$as_me:$LINENO:   current value: $ac_new_val" >&5
+echo "$as_me:   current value: $ac_new_val" >&2;}
+	ac_cache_corrupted=:
+      fi;;
+  esac
+  # Pass precious variables to config.status.
+  if test "$ac_new_set" = set; then
+    case $ac_new_val in
+    *\'*) ac_arg=$ac_var=`echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;;
+    *) ac_arg=$ac_var=$ac_new_val ;;
+    esac
+    case " $ac_configure_args " in
+      *" '$ac_arg' "*) ;; # Avoid dups.  Use of quotes ensures accuracy.
+      *) ac_configure_args="$ac_configure_args '$ac_arg'" ;;
+    esac
+  fi
+done
+if $ac_cache_corrupted; then
+  { echo "$as_me:$LINENO: error: changes in the environment can compromise the build" >&5
+echo "$as_me: error: changes in the environment can compromise the build" >&2;}
+  { { echo "$as_me:$LINENO: error: run \`make distclean' and/or \`rm $cache_file' and start over" >&5
+echo "$as_me: error: run \`make distclean' and/or \`rm $cache_file' and start over" >&2;}
+   { (exit 1); exit 1; }; }
+fi
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+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: checking whether ${MAKE-make} sets \$(MAKE)" >&5
+echo $ECHO_N "checking whether ${MAKE-make} sets \$(MAKE)... $ECHO_C" >&6; }
+set x ${MAKE-make}; ac_make=`echo "$2" | sed 's/+/p/g; s/[^a-zA-Z0-9_]/_/g'`
+if { as_var=ac_cv_prog_make_${ac_make}_set; eval "test \"\${$as_var+set}\" = set"; }; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
 else
-  cat > conftestmake <<\EOF
+  cat >conftest.make <<\_ACEOF
+SHELL = /bin/sh
 all:
-	@echo 'ac_maketemp="${MAKE}"'
-EOF
+	@echo '@@@%%%=$(MAKE)=@@@%%%'
+_ACEOF
 # 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
+case `${MAKE-make} -f conftest.make 2>/dev/null` in
+  *@@@%%%=?*=@@@%%%*)
+    eval ac_cv_prog_make_${ac_make}_set=yes;;
+  *)
+    eval ac_cv_prog_make_${ac_make}_set=no;;
+esac
+rm -f conftest.make
 fi
-rm -f conftestmake
-fi
-if eval "test \"`echo '$ac_cv_prog_make_'${ac_make}_set`\" = yes"; then
-  echo "$ac_t""yes" 1>&6
+if eval test \$ac_cv_prog_make_${ac_make}_set = yes; then
+  { echo "$as_me:$LINENO: result: yes" >&5
+echo "${ECHO_T}yes" >&6; }
   SET_MAKE=
 else
-  echo "$ac_t""no" 1>&6
+  { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
   SET_MAKE="MAKE=${MAKE-make}"
 fi
 
-# 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:555: checking for $ac_word" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_CC'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
+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
+if test -n "$ac_tool_prefix"; then
+  # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args.
+set dummy ${ac_tool_prefix}gcc; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_prog_CC+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&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"
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+  for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_CC="${ac_tool_prefix}gcc"
+    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+done
+IFS=$as_save_IFS
+
 fi
 fi
-CC="$ac_cv_prog_CC"
+CC=$ac_cv_prog_CC
 if test -n "$CC"; then
-  echo "$ac_t""$CC" 1>&6
+  { echo "$as_me:$LINENO: result: $CC" >&5
+echo "${ECHO_T}$CC" >&6; }
 else
-  echo "$ac_t""no" 1>&6
+  { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
 fi
 
+
+fi
+if test -z "$ac_cv_prog_CC"; then
+  ac_ct_CC=$CC
+  # Extract the first word of "gcc", so it can be a program name with args.
+set dummy gcc; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_prog_ac_ct_CC+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+  if test -n "$ac_ct_CC"; then
+  ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+  for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_ac_ct_CC="gcc"
+    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+done
+IFS=$as_save_IFS
+
+fi
+fi
+ac_ct_CC=$ac_cv_prog_ac_ct_CC
+if test -n "$ac_ct_CC"; then
+  { echo "$as_me:$LINENO: result: $ac_ct_CC" >&5
+echo "${ECHO_T}$ac_ct_CC" >&6; }
+else
+  { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+  if test "x$ac_ct_CC" = x; then
+    CC=""
+  else
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools
+whose name does not start with the host triplet.  If you think this
+configuration is useful to you, please write to autoconf at gnu.org." >&5
+echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools
+whose name does not start with the host triplet.  If you think this
+configuration is useful to you, please write to autoconf at gnu.org." >&2;}
+ac_tool_warned=yes ;;
+esac
+    CC=$ac_ct_CC
+  fi
+else
+  CC="$ac_cv_prog_CC"
+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:585: checking for $ac_word" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_CC'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
+          if test -n "$ac_tool_prefix"; then
+    # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args.
+set dummy ${ac_tool_prefix}cc; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_prog_CC+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&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=":"
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+  for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_CC="${ac_tool_prefix}cc"
+    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+done
+IFS=$as_save_IFS
+
+fi
+fi
+CC=$ac_cv_prog_CC
+if test -n "$CC"; then
+  { echo "$as_me:$LINENO: result: $CC" >&5
+echo "${ECHO_T}$CC" >&6; }
+else
+  { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+  fi
+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 "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_prog_CC+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+  if test -n "$CC"; then
+  ac_cv_prog_CC="$CC" # Let the user override the test.
+else
   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"
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+  for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then
+       ac_prog_rejected=yes
+       continue
+     fi
+    ac_cv_prog_CC="cc"
+    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+done
+IFS=$as_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
+  if test $# != 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="$@"
+    ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@"
   fi
 fi
 fi
 fi
-CC="$ac_cv_prog_CC"
+CC=$ac_cv_prog_CC
 if test -n "$CC"; then
-  echo "$ac_t""$CC" 1>&6
+  { echo "$as_me:$LINENO: result: $CC" >&5
+echo "${ECHO_T}$CC" >&6; }
 else
-  echo "$ac_t""no" 1>&6
+  { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&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:636: checking for $ac_word" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_CC'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
+
+fi
+if test -z "$CC"; then
+  if test -n "$ac_tool_prefix"; then
+  for ac_prog in cl.exe
+  do
+    # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args.
+set dummy $ac_tool_prefix$ac_prog; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_prog_CC+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&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
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+  for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_CC="$ac_tool_prefix$ac_prog"
+    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+done
+IFS=$as_save_IFS
+
+fi
+fi
+CC=$ac_cv_prog_CC
+if test -n "$CC"; then
+  { echo "$as_me:$LINENO: result: $CC" >&5
+echo "${ECHO_T}$CC" >&6; }
+else
+  { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+    test -n "$CC" && break
+  done
+fi
+if test -z "$CC"; then
+  ac_ct_CC=$CC
+  for ac_prog in cl.exe
+do
+  # Extract the first word of "$ac_prog", so it can be a program name with args.
+set dummy $ac_prog; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_prog_ac_ct_CC+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+  if test -n "$ac_ct_CC"; then
+  ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+  for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_ac_ct_CC="$ac_prog"
+    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+done
+IFS=$as_save_IFS
+
+fi
+fi
+ac_ct_CC=$ac_cv_prog_ac_ct_CC
+if test -n "$ac_ct_CC"; then
+  { echo "$as_me:$LINENO: result: $ac_ct_CC" >&5
+echo "${ECHO_T}$ac_ct_CC" >&6; }
+else
+  { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+  test -n "$ac_ct_CC" && break
+done
+
+  if test "x$ac_ct_CC" = x; then
+    CC=""
+  else
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools
+whose name does not start with the host triplet.  If you think this
+configuration is useful to you, please write to autoconf at gnu.org." >&5
+echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools
+whose name does not start with the host triplet.  If you think this
+configuration is useful to you, please write to autoconf at gnu.org." >&2;}
+ac_tool_warned=yes ;;
+esac
+    CC=$ac_ct_CC
+  fi
+fi
+
+fi
+
+
+test -z "$CC" && { { echo "$as_me:$LINENO: error: no acceptable C compiler found in \$PATH
+See \`config.log' for more details." >&5
+echo "$as_me: error: no acceptable C compiler found in \$PATH
+See \`config.log' for more details." >&2;}
+   { (exit 1); exit 1; }; }
+
+# Provide some information about the compiler.
+echo "$as_me:$LINENO: checking for C compiler version" >&5
+ac_compiler=`set X $ac_compile; echo $2`
+{ (ac_try="$ac_compiler --version >&5"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compiler --version >&5") 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }
+{ (ac_try="$ac_compiler -v >&5"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compiler -v >&5") 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }
+{ (ac_try="$ac_compiler -V >&5"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compiler -V >&5") 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }
+
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+ac_clean_files_save=$ac_clean_files
+ac_clean_files="$ac_clean_files a.out a.exe b.out"
+# Try to create an executable without -o first, disregard a.out.
+# It will help us diagnose broken compilers, and finding out an intuition
+# of exeext.
+{ echo "$as_me:$LINENO: checking for C compiler default output file name" >&5
+echo $ECHO_N "checking for C compiler default output file name... $ECHO_C" >&6; }
+ac_link_default=`echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'`
+#
+# List of possible output files, starting from the most likely.
+# The algorithm is not robust to junk in `.', hence go to wildcards (a.*)
+# only as a last resort.  b.out is created by i960 compilers.
+ac_files='a_out.exe a.exe conftest.exe a.out conftest a.* conftest.* b.out'
+#
+# The IRIX 6 linker writes into existing files which may not be
+# executable, retaining their permissions.  Remove them first so a
+# subsequent execution test works.
+ac_rmfiles=
+for ac_file in $ac_files
+do
+  case $ac_file in
+    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.o | *.obj ) ;;
+    * ) ac_rmfiles="$ac_rmfiles $ac_file";;
+  esac
+done
+rm -f $ac_rmfiles
+
+if { (ac_try="$ac_link_default"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_link_default") 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; then
+  # Autoconf-2.13 could set the ac_cv_exeext variable to `no'.
+# So ignore a value of `no', otherwise this would lead to `EXEEXT = no'
+# in a Makefile.  We should not override ac_cv_exeext if it was cached,
+# so that the user can short-circuit this test for compilers unknown to
+# Autoconf.
+for ac_file in $ac_files ''
+do
+  test -f "$ac_file" || continue
+  case $ac_file in
+    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.o | *.obj )
+	;;
+    [ab].out )
+	# We found the default executable, but exeext='' is most
+	# certainly right.
+	break;;
+    *.* )
+        if test "${ac_cv_exeext+set}" = set && test "$ac_cv_exeext" != no;
+	then :; else
+	   ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'`
+	fi
+	# We set ac_cv_exeext here because the later test for it is not
+	# safe: cross compilers may not add the suffix if given an `-o'
+	# argument, so we may need to know it at that point already.
+	# Even if this section looks crufty: it has the advantage of
+	# actually working.
+	break;;
+    * )
+	break;;
+  esac
+done
+test "$ac_cv_exeext" = no && ac_cv_exeext=
+
+else
+  ac_file=''
+fi
+
+{ echo "$as_me:$LINENO: result: $ac_file" >&5
+echo "${ECHO_T}$ac_file" >&6; }
+if test -z "$ac_file"; then
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+{ { echo "$as_me:$LINENO: error: C compiler cannot create executables
+See \`config.log' for more details." >&5
+echo "$as_me: error: C compiler cannot create executables
+See \`config.log' for more details." >&2;}
+   { (exit 77); exit 77; }; }
+fi
+
+ac_exeext=$ac_cv_exeext
+
+# Check that the compiler produces executables we can run.  If not, either
+# the compiler is broken, or we cross compile.
+{ echo "$as_me:$LINENO: checking whether the C compiler works" >&5
+echo $ECHO_N "checking whether the C compiler works... $ECHO_C" >&6; }
+# FIXME: These cross compiler hacks should be removed for Autoconf 3.0
+# If not cross compiling, check that we can run a simple program.
+if test "$cross_compiling" != yes; then
+  if { ac_try='./$ac_file'
+  { (case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_try") 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
+    cross_compiling=no
+  else
+    if test "$cross_compiling" = maybe; then
+	cross_compiling=yes
+    else
+	{ { echo "$as_me:$LINENO: error: cannot run C compiled programs.
+If you meant to cross compile, use \`--host'.
+See \`config.log' for more details." >&5
+echo "$as_me: error: cannot run C compiled programs.
+If you meant to cross compile, use \`--host'.
+See \`config.log' for more details." >&2;}
+   { (exit 1); exit 1; }; }
     fi
-  done
-  IFS="$ac_save_ifs"
+  fi
 fi
+{ echo "$as_me:$LINENO: result: yes" >&5
+echo "${ECHO_T}yes" >&6; }
+
+rm -f a.out a.exe conftest$ac_cv_exeext b.out
+ac_clean_files=$ac_clean_files_save
+# Check that the compiler produces executables we can run.  If not, either
+# the compiler is broken, or we cross compile.
+{ echo "$as_me:$LINENO: checking whether we are cross compiling" >&5
+echo $ECHO_N "checking whether we are cross compiling... $ECHO_C" >&6; }
+{ echo "$as_me:$LINENO: result: $cross_compiling" >&5
+echo "${ECHO_T}$cross_compiling" >&6; }
+
+{ echo "$as_me:$LINENO: checking for suffix of executables" >&5
+echo $ECHO_N "checking for suffix of executables... $ECHO_C" >&6; }
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_link") 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; then
+  # If both `conftest.exe' and `conftest' are `present' (well, observable)
+# catch `conftest.exe'.  For instance with Cygwin, `ls conftest' will
+# work properly (i.e., refer to `conftest.exe'), while it won't with
+# `rm'.
+for ac_file in conftest.exe conftest conftest.*; do
+  test -f "$ac_file" || continue
+  case $ac_file in
+    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.o | *.obj ) ;;
+    *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'`
+	  break;;
+    * ) break;;
+  esac
+done
+else
+  { { echo "$as_me:$LINENO: error: cannot compute suffix of executables: cannot compile and link
+See \`config.log' for more details." >&5
+echo "$as_me: error: cannot compute suffix of executables: cannot compile and link
+See \`config.log' for more details." >&2;}
+   { (exit 1); exit 1; }; }
 fi
-CC="$ac_cv_prog_CC"
-if test -n "$CC"; then
-  echo "$ac_t""$CC" 1>&6
+
+rm -f conftest$ac_cv_exeext
+{ echo "$as_me:$LINENO: result: $ac_cv_exeext" >&5
+echo "${ECHO_T}$ac_cv_exeext" >&6; }
+
+rm -f conftest.$ac_ext
+EXEEXT=$ac_cv_exeext
+ac_exeext=$EXEEXT
+{ echo "$as_me:$LINENO: checking for suffix of object files" >&5
+echo $ECHO_N "checking for suffix of object files... $ECHO_C" >&6; }
+if test "${ac_cv_objext+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
 else
-  echo "$ac_t""no" 1>&6
+  cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.o conftest.obj
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compile") 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; then
+  for ac_file in conftest.o conftest.obj conftest.*; do
+  test -f "$ac_file" || continue;
+  case $ac_file in
+    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf ) ;;
+    *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'`
+       break;;
+  esac
+done
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+{ { echo "$as_me:$LINENO: error: cannot compute suffix of object files: cannot compile
+See \`config.log' for more details." >&5
+echo "$as_me: error: cannot compute suffix of object files: cannot compile
+See \`config.log' for more details." >&2;}
+   { (exit 1); exit 1; }; }
 fi
- ;;
-    esac
-  fi
-  test -z "$CC" && { echo "configure: error: no acceptable cc found in \$PATH" 1>&2; exit 1; }
+
+rm -f conftest.$ac_cv_objext conftest.$ac_ext
 fi
-
-echo $ac_n "checking whether the C compiler ($CC $CFLAGS $LDFLAGS) works""... $ac_c" 1>&6
-echo "configure:668: checking whether the C compiler ($CC $CFLAGS $LDFLAGS) works" >&5
-
-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 << EOF
-
-#line 679 "configure"
-#include "confdefs.h"
-
-main(){return(0);}
-EOF
-if { (eval echo configure:684: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
-  ac_cv_prog_cc_works=yes
-  # If we can't run a trivial program, we are probably using a cross compiler.
-  if (./conftest; exit) 2>/dev/null; then
-    ac_cv_prog_cc_cross=no
-  else
-    ac_cv_prog_cc_cross=yes
-  fi
+{ echo "$as_me:$LINENO: result: $ac_cv_objext" >&5
+echo "${ECHO_T}$ac_cv_objext" >&6; }
+OBJEXT=$ac_cv_objext
+ac_objext=$OBJEXT
+{ echo "$as_me:$LINENO: checking whether we are using the GNU C compiler" >&5
+echo $ECHO_N "checking whether we are using the GNU C compiler... $ECHO_C" >&6; }
+if test "${ac_cv_c_compiler_gnu+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
 else
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  ac_cv_prog_cc_works=no
+  cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+
+int
+main ()
+{
+#ifndef __GNUC__
+       choke me
+#endif
+
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compile") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } && {
+	 test -z "$ac_c_werror_flag" ||
+	 test ! -s conftest.err
+       } && test -s conftest.$ac_objext; then
+  ac_compiler_gnu=yes
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+	ac_compiler_gnu=no
 fi
-rm -fr 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
-
-echo "$ac_t""$ac_cv_prog_cc_works" 1>&6
-if test $ac_cv_prog_cc_works = no; then
-  { echo "configure: error: installation or configuration problem: C compiler cannot create executables." 1>&2; exit 1; }
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+ac_cv_c_compiler_gnu=$ac_compiler_gnu
+
 fi
-echo $ac_n "checking whether the C compiler ($CC $CFLAGS $LDFLAGS) is a cross-compiler""... $ac_c" 1>&6
-echo "configure:710: checking whether the C compiler ($CC $CFLAGS $LDFLAGS) is a cross-compiler" >&5
-echo "$ac_t""$ac_cv_prog_cc_cross" 1>&6
-cross_compiling=$ac_cv_prog_cc_cross
-
-echo $ac_n "checking whether we are using GNU C""... $ac_c" 1>&6
-echo "configure:715: 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
+{ echo "$as_me:$LINENO: result: $ac_cv_c_compiler_gnu" >&5
+echo "${ECHO_T}$ac_cv_c_compiler_gnu" >&6; }
+GCC=`test $ac_compiler_gnu = yes && echo yes`
+ac_test_CFLAGS=${CFLAGS+set}
+ac_save_CFLAGS=$CFLAGS
+{ echo "$as_me:$LINENO: checking whether $CC accepts -g" >&5
+echo $ECHO_N "checking whether $CC accepts -g... $ECHO_C" >&6; }
+if test "${ac_cv_prog_cc_g+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
 else
-  cat > conftest.c <<EOF
-#ifdef __GNUC__
-  yes;
-#endif
-EOF
-if { ac_try='${CC-cc} -E conftest.c'; { (eval echo configure:724: \"$ac_try\") 1>&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:743: 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_save_c_werror_flag=$ac_c_werror_flag
+   ac_c_werror_flag=yes
+   ac_cv_prog_cc_g=no
+   CFLAGS="-g"
+   cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compile") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } && {
+	 test -z "$ac_c_werror_flag" ||
+	 test ! -s conftest.err
+       } && test -s conftest.$ac_objext; then
   ac_cv_prog_cc_g=yes
 else
-  ac_cv_prog_cc_g=no
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+	CFLAGS=""
+      cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compile") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } && {
+	 test -z "$ac_c_werror_flag" ||
+	 test ! -s conftest.err
+       } && test -s conftest.$ac_objext; then
+  :
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+	ac_c_werror_flag=$ac_save_c_werror_flag
+	 CFLAGS="-g"
+	 cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compile") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } && {
+	 test -z "$ac_c_werror_flag" ||
+	 test ! -s conftest.err
+       } && test -s conftest.$ac_objext; then
+  ac_cv_prog_cc_g=yes
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+
 fi
-rm -f conftest*
-
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
 fi
 
-echo "$ac_t""$ac_cv_prog_cc_g" 1>&6
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+   ac_c_werror_flag=$ac_save_c_werror_flag
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_prog_cc_g" >&5
+echo "${ECHO_T}$ac_cv_prog_cc_g" >&6; }
 if test "$ac_test_CFLAGS" = set; then
-  CFLAGS="$ac_save_CFLAGS"
+  CFLAGS=$ac_save_CFLAGS
 elif test $ac_cv_prog_cc_g = yes; then
   if test "$GCC" = yes; then
     CFLAGS="-g -O2"
@@ -769,216 +2475,702 @@
     CFLAGS=
   fi
 fi
-
-                      echo $ac_n "checking how to run the C preprocessor""... $ac_c" 1>&6
-echo "configure:775: checking how to run the C preprocessor" >&5
+{ echo "$as_me:$LINENO: checking for $CC option to accept ISO C89" >&5
+echo $ECHO_N "checking for $CC option to accept ISO C89... $ECHO_C" >&6; }
+if test "${ac_cv_prog_cc_c89+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+  ac_cv_prog_cc_c89=no
+ac_save_CC=$CC
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+#include <stdarg.h>
+#include <stdio.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+/* Most of the following tests are stolen from RCS 5.7's src/conf.sh.  */
+struct buf { int x; };
+FILE * (*rcsopen) (struct buf *, struct stat *, int);
+static char *e (p, i)
+     char **p;
+     int i;
+{
+  return p[i];
+}
+static char *f (char * (*g) (char **, int), char **p, ...)
+{
+  char *s;
+  va_list v;
+  va_start (v,p);
+  s = g (p, va_arg (v,int));
+  va_end (v);
+  return s;
+}
+
+/* OSF 4.0 Compaq cc is some sort of almost-ANSI by default.  It has
+   function prototypes and stuff, but not '\xHH' hex character constants.
+   These don't provoke an error unfortunately, instead are silently treated
+   as 'x'.  The following induces an error, until -std is added to get
+   proper ANSI mode.  Curiously '\x00'!='x' always comes out true, for an
+   array size at least.  It's necessary to write '\x00'==0 to get something
+   that's true only with -std.  */
+int osf4_cc_array ['\x00' == 0 ? 1 : -1];
+
+/* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters
+   inside strings and character constants.  */
+#define FOO(x) 'x'
+int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1];
+
+int test (int i, double x);
+struct s1 {int (*f) (int a);};
+struct s2 {int (*f) (double a);};
+int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int);
+int argc;
+char **argv;
+int
+main ()
+{
+return f (e, argv, 0) != argv[0]  ||  f (e, argv, 1) != argv[1];
+  ;
+  return 0;
+}
+_ACEOF
+for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \
+	-Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__"
+do
+  CC="$ac_save_CC $ac_arg"
+  rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compile") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } && {
+	 test -z "$ac_c_werror_flag" ||
+	 test ! -s conftest.err
+       } && test -s conftest.$ac_objext; then
+  ac_cv_prog_cc_c89=$ac_arg
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+
+fi
+
+rm -f core conftest.err conftest.$ac_objext
+  test "x$ac_cv_prog_cc_c89" != "xno" && break
+done
+rm -f conftest.$ac_ext
+CC=$ac_save_CC
+
+fi
+# AC_CACHE_VAL
+case "x$ac_cv_prog_cc_c89" in
+  x)
+    { echo "$as_me:$LINENO: result: none needed" >&5
+echo "${ECHO_T}none needed" >&6; } ;;
+  xno)
+    { echo "$as_me:$LINENO: result: unsupported" >&5
+echo "${ECHO_T}unsupported" >&6; } ;;
+  *)
+    CC="$CC $ac_cv_prog_cc_c89"
+    { echo "$as_me:$LINENO: result: $ac_cv_prog_cc_c89" >&5
+echo "${ECHO_T}$ac_cv_prog_cc_c89" >&6; } ;;
+esac
+
+
+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
+
+                      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: checking how to run the C preprocessor" >&5
+echo $ECHO_N "checking how to run the C preprocessor... $ECHO_C" >&6; }
 # 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
+  if test "${ac_cv_prog_CPP+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&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"
+      # Double quotes because CPP needs to be expanded
+    for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp"
+    do
+      ac_preproc_ok=false
+for ac_c_preproc_warn_flag in '' yes
+do
+  # Use a header file that comes with gcc, so configuring glibc
+  # with a fresh cross-compiler works.
+  # Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+  # <limits.h> exists even on freestanding compilers.
   # On the NeXT, cc -E runs the code through the compiler's parser,
-  # not just through cpp.
-  cat > conftest.$ac_ext <<EOF
-#line 790 "configure"
-#include "confdefs.h"
-#include <assert.h>
-Syntax Error
-EOF
-ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
-{ (eval echo configure:796: \"$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
+  # not just through cpp. "Syntax error" is here to catch this case.
+  cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+		     Syntax error
+_ACEOF
+if { (ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } >/dev/null && {
+	 test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
+	 test ! -s conftest.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 <<EOF
-#line 807 "configure"
-#include "confdefs.h"
-#include <assert.h>
-Syntax Error
-EOF
-ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
-{ (eval echo configure:813: \"$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
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+  # Broken: fails on valid input.
+continue
+fi
+
+rm -f conftest.err conftest.$ac_ext
+
+  # OK, works on sane cases.  Now check whether nonexistent headers
+  # can be detected and how.
+  cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+#include <ac_nonexistent.h>
+_ACEOF
+if { (ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } >/dev/null && {
+	 test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
+	 test ! -s conftest.err
+       }; then
+  # Broken: success on invalid input.
+continue
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+  # Passes both tests.
+ac_preproc_ok=:
+break
+fi
+
+rm -f conftest.err conftest.$ac_ext
+
+done
+# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
+rm -f conftest.err conftest.$ac_ext
+if $ac_preproc_ok; then
+  break
+fi
+
+    done
+    ac_cv_prog_CPP=$CPP
+
+fi
+  CPP=$ac_cv_prog_CPP
+else
+  ac_cv_prog_CPP=$CPP
+fi
+{ echo "$as_me:$LINENO: result: $CPP" >&5
+echo "${ECHO_T}$CPP" >&6; }
+ac_preproc_ok=false
+for ac_c_preproc_warn_flag in '' yes
+do
+  # Use a header file that comes with gcc, so configuring glibc
+  # with a fresh cross-compiler works.
+  # Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+  # <limits.h> exists even on freestanding compilers.
+  # On the NeXT, cc -E runs the code through the compiler's parser,
+  # not just through cpp. "Syntax error" is here to catch this case.
+  cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+		     Syntax error
+_ACEOF
+if { (ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } >/dev/null && {
+	 test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
+	 test ! -s conftest.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 <<EOF
-#line 824 "configure"
-#include "confdefs.h"
-#include <assert.h>
-Syntax Error
-EOF
-ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
-{ (eval echo configure:830: \"$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
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+  # Broken: fails on valid input.
+continue
+fi
+
+rm -f conftest.err conftest.$ac_ext
+
+  # OK, works on sane cases.  Now check whether nonexistent headers
+  # can be detected and how.
+  cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+#include <ac_nonexistent.h>
+_ACEOF
+if { (ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } >/dev/null && {
+	 test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
+	 test ! -s conftest.err
+       }; then
+  # Broken: success on invalid input.
+continue
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+  # Passes both tests.
+ac_preproc_ok=:
+break
+fi
+
+rm -f conftest.err conftest.$ac_ext
+
+done
+# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
+rm -f conftest.err conftest.$ac_ext
+if $ac_preproc_ok; then
   :
 else
-  echo "$ac_err" >&5
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  CPP=/lib/cpp
+  { { echo "$as_me:$LINENO: error: C preprocessor \"$CPP\" fails sanity check
+See \`config.log' for more details." >&5
+echo "$as_me: error: C preprocessor \"$CPP\" fails sanity check
+See \`config.log' for more details." >&2;}
+   { (exit 1); exit 1; }; }
 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
-
-                      for ac_prog in $CCC c++ g++ gcc CC cxx cc++ cl
-do
-# Extract the first word of "$ac_prog", so it can be a program name with args.
-set dummy $ac_prog; ac_word=$2
-echo $ac_n "checking for $ac_word""... $ac_c" 1>&6
-echo "configure:859: checking for $ac_word" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_CXX'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
+
+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
+
+                      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
+if test -z "$CXX"; then
+  if test -n "$CCC"; then
+    CXX=$CCC
+  else
+    if test -n "$ac_tool_prefix"; then
+  for ac_prog in g++ c++ gpp aCC CC cxx cc++ cl.exe FCC KCC RCC xlC_r xlC
+  do
+    # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args.
+set dummy $ac_tool_prefix$ac_prog; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_prog_CXX+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
 else
   if test -n "$CXX"; then
   ac_cv_prog_CXX="$CXX" # 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_CXX="$ac_prog"
-      break
-    fi
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+  for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_CXX="$ac_tool_prefix$ac_prog"
+    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+done
+IFS=$as_save_IFS
+
+fi
+fi
+CXX=$ac_cv_prog_CXX
+if test -n "$CXX"; then
+  { echo "$as_me:$LINENO: result: $CXX" >&5
+echo "${ECHO_T}$CXX" >&6; }
+else
+  { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+    test -n "$CXX" && break
   done
-  IFS="$ac_save_ifs"
 fi
+if test -z "$CXX"; then
+  ac_ct_CXX=$CXX
+  for ac_prog in g++ c++ gpp aCC CC cxx cc++ cl.exe FCC KCC RCC xlC_r xlC
+do
+  # Extract the first word of "$ac_prog", so it can be a program name with args.
+set dummy $ac_prog; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_prog_ac_ct_CXX+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+  if test -n "$ac_ct_CXX"; then
+  ac_cv_prog_ac_ct_CXX="$ac_ct_CXX" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+  for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_ac_ct_CXX="$ac_prog"
+    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+done
+IFS=$as_save_IFS
+
 fi
-CXX="$ac_cv_prog_CXX"
-if test -n "$CXX"; then
-  echo "$ac_t""$CXX" 1>&6
+fi
+ac_ct_CXX=$ac_cv_prog_ac_ct_CXX
+if test -n "$ac_ct_CXX"; then
+  { echo "$as_me:$LINENO: result: $ac_ct_CXX" >&5
+echo "${ECHO_T}$ac_ct_CXX" >&6; }
 else
-  echo "$ac_t""no" 1>&6
+  { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
 fi
 
-test -n "$CXX" && break
+
+  test -n "$ac_ct_CXX" && break
 done
-test -n "$CXX" || CXX="gcc"
-
-
-echo $ac_n "checking whether the C++ compiler ($CXX $CXXFLAGS $LDFLAGS) works""... $ac_c" 1>&6
-echo "configure:891: checking whether the C++ compiler ($CXX $CXXFLAGS $LDFLAGS) works" >&5
-
-ac_ext=C
-# CXXFLAGS is not in ac_cpp because -g, -O, etc. are not valid cpp options.
-ac_cpp='$CXXCPP $CPPFLAGS'
-ac_compile='${CXX-g++} -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext 1>&5'
-ac_link='${CXX-g++} -o conftest${ac_exeext} $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS 1>&5'
-cross_compiling=$ac_cv_prog_cxx_cross
-
-cat > conftest.$ac_ext << EOF
-
-#line 902 "configure"
-#include "confdefs.h"
-
-int main(){return(0);}
-EOF
-if { (eval echo configure:907: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
-  ac_cv_prog_cxx_works=yes
-  # If we can't run a trivial program, we are probably using a cross compiler.
-  if (./conftest; exit) 2>/dev/null; then
-    ac_cv_prog_cxx_cross=no
+
+  if test "x$ac_ct_CXX" = x; then
+    CXX="g++"
   else
-    ac_cv_prog_cxx_cross=yes
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools
+whose name does not start with the host triplet.  If you think this
+configuration is useful to you, please write to autoconf at gnu.org." >&5
+echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools
+whose name does not start with the host triplet.  If you think this
+configuration is useful to you, please write to autoconf at gnu.org." >&2;}
+ac_tool_warned=yes ;;
+esac
+    CXX=$ac_ct_CXX
   fi
+fi
+
+  fi
+fi
+# Provide some information about the compiler.
+echo "$as_me:$LINENO: checking for C++ compiler version" >&5
+ac_compiler=`set X $ac_compile; echo $2`
+{ (ac_try="$ac_compiler --version >&5"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compiler --version >&5") 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }
+{ (ac_try="$ac_compiler -v >&5"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compiler -v >&5") 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }
+{ (ac_try="$ac_compiler -V >&5"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compiler -V >&5") 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }
+
+{ echo "$as_me:$LINENO: checking whether we are using the GNU C++ compiler" >&5
+echo $ECHO_N "checking whether we are using the GNU C++ compiler... $ECHO_C" >&6; }
+if test "${ac_cv_cxx_compiler_gnu+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
 else
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  ac_cv_prog_cxx_works=no
+  cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+
+int
+main ()
+{
+#ifndef __GNUC__
+       choke me
+#endif
+
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compile") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } && {
+	 test -z "$ac_cxx_werror_flag" ||
+	 test ! -s conftest.err
+       } && test -s conftest.$ac_objext; then
+  ac_compiler_gnu=yes
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+	ac_compiler_gnu=no
 fi
-rm -fr 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
-
-echo "$ac_t""$ac_cv_prog_cxx_works" 1>&6
-if test $ac_cv_prog_cxx_works = no; then
-  { echo "configure: error: installation or configuration problem: C++ compiler cannot create executables." 1>&2; exit 1; }
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+ac_cv_cxx_compiler_gnu=$ac_compiler_gnu
+
 fi
-echo $ac_n "checking whether the C++ compiler ($CXX $CXXFLAGS $LDFLAGS) is a cross-compiler""... $ac_c" 1>&6
-echo "configure:933: checking whether the C++ compiler ($CXX $CXXFLAGS $LDFLAGS) is a cross-compiler" >&5
-echo "$ac_t""$ac_cv_prog_cxx_cross" 1>&6
-cross_compiling=$ac_cv_prog_cxx_cross
-
-echo $ac_n "checking whether we are using GNU C++""... $ac_c" 1>&6
-echo "configure:938: checking whether we are using GNU C++" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_gxx'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
+{ echo "$as_me:$LINENO: result: $ac_cv_cxx_compiler_gnu" >&5
+echo "${ECHO_T}$ac_cv_cxx_compiler_gnu" >&6; }
+GXX=`test $ac_compiler_gnu = yes && echo yes`
+ac_test_CXXFLAGS=${CXXFLAGS+set}
+ac_save_CXXFLAGS=$CXXFLAGS
+{ echo "$as_me:$LINENO: checking whether $CXX accepts -g" >&5
+echo $ECHO_N "checking whether $CXX accepts -g... $ECHO_C" >&6; }
+if test "${ac_cv_prog_cxx_g+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
 else
-  cat > conftest.C <<EOF
-#ifdef __GNUC__
-  yes;
-#endif
-EOF
-if { ac_try='${CXX-g++} -E conftest.C'; { (eval echo configure:947: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }; } | egrep yes >/dev/null 2>&1; then
-  ac_cv_prog_gxx=yes
-else
-  ac_cv_prog_gxx=no
-fi
-fi
-
-echo "$ac_t""$ac_cv_prog_gxx" 1>&6
-
-if test $ac_cv_prog_gxx = yes; then
-  GXX=yes
-else
-  GXX=
-fi
-
-ac_test_CXXFLAGS="${CXXFLAGS+set}"
-ac_save_CXXFLAGS="$CXXFLAGS"
-CXXFLAGS=
-echo $ac_n "checking whether ${CXX-g++} accepts -g""... $ac_c" 1>&6
-echo "configure:966: checking whether ${CXX-g++} accepts -g" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_cxx_g'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  echo 'void f(){}' > conftest.cc
-if test -z "`${CXX-g++} -g -c conftest.cc 2>&1`"; then
+  ac_save_cxx_werror_flag=$ac_cxx_werror_flag
+   ac_cxx_werror_flag=yes
+   ac_cv_prog_cxx_g=no
+   CXXFLAGS="-g"
+   cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compile") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } && {
+	 test -z "$ac_cxx_werror_flag" ||
+	 test ! -s conftest.err
+       } && test -s conftest.$ac_objext; then
   ac_cv_prog_cxx_g=yes
 else
-  ac_cv_prog_cxx_g=no
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+	CXXFLAGS=""
+      cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compile") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } && {
+	 test -z "$ac_cxx_werror_flag" ||
+	 test ! -s conftest.err
+       } && test -s conftest.$ac_objext; then
+  :
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+	ac_cxx_werror_flag=$ac_save_cxx_werror_flag
+	 CXXFLAGS="-g"
+	 cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compile") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } && {
+	 test -z "$ac_cxx_werror_flag" ||
+	 test ! -s conftest.err
+       } && test -s conftest.$ac_objext; then
+  ac_cv_prog_cxx_g=yes
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+
 fi
-rm -f conftest*
-
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
 fi
 
-echo "$ac_t""$ac_cv_prog_cxx_g" 1>&6
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+   ac_cxx_werror_flag=$ac_save_cxx_werror_flag
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_prog_cxx_g" >&5
+echo "${ECHO_T}$ac_cv_prog_cxx_g" >&6; }
 if test "$ac_test_CXXFLAGS" = set; then
-  CXXFLAGS="$ac_save_CXXFLAGS"
+  CXXFLAGS=$ac_save_CXXFLAGS
 elif test $ac_cv_prog_cxx_g = yes; then
   if test "$GXX" = yes; then
     CXXFLAGS="-g -O2"
@@ -992,78 +3184,332 @@
     CXXFLAGS=
   fi
 fi
-
-                      echo $ac_n "checking how to run the C++ preprocessor""... $ac_c" 1>&6
-echo "configure:998: checking how to run the C++ preprocessor" >&5
+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
+
+                      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
+{ echo "$as_me:$LINENO: checking how to run the C++ preprocessor" >&5
+echo $ECHO_N "checking how to run the C++ preprocessor... $ECHO_C" >&6; }
 if test -z "$CXXCPP"; then
-if eval "test \"`echo '$''{'ac_cv_prog_CXXCPP'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
+  if test "${ac_cv_prog_CXXCPP+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
 else
-  ac_ext=C
-# CXXFLAGS is not in ac_cpp because -g, -O, etc. are not valid cpp options.
-ac_cpp='$CXXCPP $CPPFLAGS'
-ac_compile='${CXX-g++} -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext 1>&5'
-ac_link='${CXX-g++} -o conftest${ac_exeext} $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS 1>&5'
-cross_compiling=$ac_cv_prog_cxx_cross
-  CXXCPP="${CXX-g++} -E"
-  cat > conftest.$ac_ext <<EOF
-#line 1011 "configure"
-#include "confdefs.h"
-#include <stdlib.h>
-EOF
-ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
-{ (eval echo configure:1016: \"$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
+      # Double quotes because CXXCPP needs to be expanded
+    for CXXCPP in "$CXX -E" "/lib/cpp"
+    do
+      ac_preproc_ok=false
+for ac_cxx_preproc_warn_flag in '' yes
+do
+  # Use a header file that comes with gcc, so configuring glibc
+  # with a fresh cross-compiler works.
+  # Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+  # <limits.h> exists even on freestanding compilers.
+  # On the NeXT, cc -E runs the code through the compiler's parser,
+  # not just through cpp. "Syntax error" is here to catch this case.
+  cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+		     Syntax error
+_ACEOF
+if { (ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } >/dev/null && {
+	 test -z "$ac_cxx_preproc_warn_flag$ac_cxx_werror_flag" ||
+	 test ! -s conftest.err
+       }; then
   :
 else
-  echo "$ac_err" >&5
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  CXXCPP=/lib/cpp
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+  # Broken: fails on valid input.
+continue
 fi
-rm -f conftest*
-  ac_cv_prog_CXXCPP="$CXXCPP"
+
+rm -f conftest.err conftest.$ac_ext
+
+  # OK, works on sane cases.  Now check whether nonexistent headers
+  # can be detected and how.
+  cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+#include <ac_nonexistent.h>
+_ACEOF
+if { (ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } >/dev/null && {
+	 test -z "$ac_cxx_preproc_warn_flag$ac_cxx_werror_flag" ||
+	 test ! -s conftest.err
+       }; then
+  # Broken: success on invalid input.
+continue
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+  # Passes both tests.
+ac_preproc_ok=:
+break
+fi
+
+rm -f conftest.err conftest.$ac_ext
+
+done
+# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
+rm -f conftest.err conftest.$ac_ext
+if $ac_preproc_ok; then
+  break
+fi
+
+    done
+    ac_cv_prog_CXXCPP=$CXXCPP
+
+fi
+  CXXCPP=$ac_cv_prog_CXXCPP
+else
+  ac_cv_prog_CXXCPP=$CXXCPP
+fi
+{ echo "$as_me:$LINENO: result: $CXXCPP" >&5
+echo "${ECHO_T}$CXXCPP" >&6; }
+ac_preproc_ok=false
+for ac_cxx_preproc_warn_flag in '' yes
+do
+  # Use a header file that comes with gcc, so configuring glibc
+  # with a fresh cross-compiler works.
+  # Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+  # <limits.h> exists even on freestanding compilers.
+  # On the NeXT, cc -E runs the code through the compiler's parser,
+  # not just through cpp. "Syntax error" is here to catch this case.
+  cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+		     Syntax error
+_ACEOF
+if { (ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } >/dev/null && {
+	 test -z "$ac_cxx_preproc_warn_flag$ac_cxx_werror_flag" ||
+	 test ! -s conftest.err
+       }; then
+  :
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+  # Broken: fails on valid input.
+continue
+fi
+
+rm -f conftest.err conftest.$ac_ext
+
+  # OK, works on sane cases.  Now check whether nonexistent headers
+  # can be detected and how.
+  cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+#include <ac_nonexistent.h>
+_ACEOF
+if { (ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } >/dev/null && {
+	 test -z "$ac_cxx_preproc_warn_flag$ac_cxx_werror_flag" ||
+	 test ! -s conftest.err
+       }; then
+  # Broken: success on invalid input.
+continue
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+  # Passes both tests.
+ac_preproc_ok=:
+break
+fi
+
+rm -f conftest.err conftest.$ac_ext
+
+done
+# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
+rm -f conftest.err conftest.$ac_ext
+if $ac_preproc_ok; then
+  :
+else
+  { { echo "$as_me:$LINENO: error: C++ preprocessor \"$CXXCPP\" fails sanity check
+See \`config.log' for more details." >&5
+echo "$as_me: error: C++ preprocessor \"$CXXCPP\" fails sanity check
+See \`config.log' for more details." >&2;}
+   { (exit 1); exit 1; }; }
+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
-fi
-fi
-CXXCPP="$ac_cv_prog_CXXCPP"
-echo "$ac_t""$CXXCPP" 1>&6
-
-                      # 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:1043: checking for $ac_word" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_RANLIB'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
+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
+
+                      if test -n "$ac_tool_prefix"; then
+  # 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 "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_prog_RANLIB+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&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="true"
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+  for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_RANLIB="${ac_tool_prefix}ranlib"
+    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+done
+IFS=$as_save_IFS
+
 fi
 fi
-RANLIB="$ac_cv_prog_RANLIB"
+RANLIB=$ac_cv_prog_RANLIB
 if test -n "$RANLIB"; then
-  echo "$ac_t""$RANLIB" 1>&6
+  { echo "$as_me:$LINENO: result: $RANLIB" >&5
+echo "${ECHO_T}$RANLIB" >&6; }
 else
-  echo "$ac_t""no" 1>&6
+  { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+fi
+if test -z "$ac_cv_prog_RANLIB"; then
+  ac_ct_RANLIB=$RANLIB
+  # Extract the first word of "ranlib", so it can be a program name with args.
+set dummy ranlib; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_prog_ac_ct_RANLIB+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+  if test -n "$ac_ct_RANLIB"; then
+  ac_cv_prog_ac_ct_RANLIB="$ac_ct_RANLIB" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+  for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_ac_ct_RANLIB="ranlib"
+    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+done
+IFS=$as_save_IFS
+
+fi
+fi
+ac_ct_RANLIB=$ac_cv_prog_ac_ct_RANLIB
+if test -n "$ac_ct_RANLIB"; then
+  { echo "$as_me:$LINENO: result: $ac_ct_RANLIB" >&5
+echo "${ECHO_T}$ac_ct_RANLIB" >&6; }
+else
+  { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+  if test "x$ac_ct_RANLIB" = x; then
+    RANLIB=":"
+  else
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools
+whose name does not start with the host triplet.  If you think this
+configuration is useful to you, please write to autoconf at gnu.org." >&5
+echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools
+whose name does not start with the host triplet.  If you think this
+configuration is useful to you, please write to autoconf at gnu.org." >&2;}
+ac_tool_warned=yes ;;
+esac
+    RANLIB=$ac_ct_RANLIB
+  fi
+else
+  RANLIB="$ac_cv_prog_RANLIB"
 fi
 
                       # Find a good install program.  We prefer a C program (faster),
@@ -1076,11 +3522,11 @@
 # 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:1081: checking for a BSD compatible install" >&5
+{ echo "$as_me:$LINENO: checking for a BSD compatible install" >&5
+echo $ECHO_N "checking for a BSD compatible install... $ECHO_C" >&6; }
 if test -z "$INSTALL"; then
-if eval "test \"`echo '$''{'cl_cv_path_install'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
+if test "${cl_cv_path_install+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
 else
     IFS="${IFS= 	}"; ac_save_ifs="$IFS"; IFS="${IFS}:"
   for ac_dir in $PATH; do
@@ -1118,7 +3564,8 @@
 fi
   INSTALL="$cl_cv_path_install"
 fi
-echo "$ac_t""$INSTALL" 1>&6
+{ echo "$as_me:$LINENO: result: $INSTALL" >&5
+echo "${ECHO_T}$INSTALL" >&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)'
@@ -1129,263 +3576,1018 @@
   esac
 fi
 
-                      trap '' 1 2 15
-cat > confcache <<\EOF
+                      ac_config_files="$ac_config_files Makefile"
+
+cat >confcache <<\_ACEOF
 # 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.
+# scripts and configure runs, see configure's option --config-cache.
+# 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.
+# config.status only pays attention to the cache file if you give it
+# the --recheck option to rerun configure.
 #
-EOF
+# `ac_cv_env_foo' variables (set or unset) will be overridden when
+# loading this file, other *unset* `ac_cv_foo' will be assigned the
+# following values.
+
+_ACEOF
+
 # 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.
+# So, we kill variables containing newlines.
 # 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
+(
+  for ac_var in `(set) 2>&1 | sed -n 's/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'`; do
+    eval ac_val=\$$ac_var
+    case $ac_val in #(
+    *${as_nl}*)
+      case $ac_var in #(
+      *_cv_*) { echo "$as_me:$LINENO: WARNING: Cache variable $ac_var contains a newline." >&5
+echo "$as_me: WARNING: Cache variable $ac_var contains a newline." >&2;} ;;
+      esac
+      case $ac_var in #(
+      _ | IFS | as_nl) ;; #(
+      *) $as_unset $ac_var ;;
+      esac ;;
+    esac
+  done
+
+  (set) 2>&1 |
+    case $as_nl`(ac_space=' '; set) 2>&1` in #(
+    *${as_nl}ac_space=\ *)
+      # `set' does not quote correctly, so add quotes (double-quote
+      # substitution turns \\\\ into \\, and sed turns \\ into \).
+      sed -n \
+	"s/'/'\\\\''/g;
+	  s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p"
+      ;; #(
+    *)
+      # `set' quotes correctly as required by POSIX, so do not add quotes.
+      sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p"
+      ;;
+    esac |
+    sort
+) |
+  sed '
+     /^ac_cv_env_/b end
+     t clear
+     :clear
+     s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/
+     t end
+     s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/
+     :end' >>confcache
+if diff "$cache_file" confcache >/dev/null 2>&1; then :; else
+  if test -w "$cache_file"; then
+    test "x$cache_file" != "x/dev/null" &&
+      { echo "$as_me:$LINENO: updating cache $cache_file" >&5
+echo "$as_me: updating cache $cache_file" >&6;}
+    cat confcache >$cache_file
   else
-    echo "not updating unwritable cache $cache_file"
+    { echo "$as_me:$LINENO: not updating unwritable cache $cache_file" >&5
+echo "$as_me: not updating unwritable cache $cache_file" >&6;}
   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.
+#
+# If the first sed substitution is executed (which looks for macros that
+# take arguments), then branch to the quote section.  Otherwise,
+# look for a macro that doesn't take arguments.
+ac_script='
+t clear
+:clear
+s/^[	 ]*#[	 ]*define[	 ][	 ]*\([^	 (][^	 (]*([^)]*)\)[	 ]*\(.*\)/-D\1=\2/g
+t quote
+s/^[	 ]*#[	 ]*define[	 ][	 ]*\([^	 ][^	 ]*\)[	 ]*\(.*\)/-D\1=\2/g
+t quote
+b any
+:quote
+s/[	 `~#$^&*(){}\\|;'\''"<>?]/\\&/g
+s/\[/\\&/g
+s/\]/\\&/g
+s/\$/$$/g
+H
+:any
+${
+	g
+	s/^\n//
+	s/\n/ /g
+	p
+}
+'
+DEFS=`sed -n "$ac_script" confdefs.h`
+
+
+ac_libobjs=
+ac_ltlibobjs=
+for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue
+  # 1. Remove the extension, and $U if already installed.
+  ac_script='s/\$U\././;s/\.o$//;s/\.obj$//'
+  ac_i=`echo "$ac_i" | sed "$ac_script"`
+  # 2. Prepend LIBOBJDIR.  When used with automake>=1.10 LIBOBJDIR
+  #    will be set to the directory where LIBOBJS objects are built.
+  ac_libobjs="$ac_libobjs \${LIBOBJDIR}$ac_i\$U.$ac_objext"
+  ac_ltlibobjs="$ac_ltlibobjs \${LIBOBJDIR}$ac_i"'$U.lo'
+done
+LIBOBJS=$ac_libobjs
+
+LTLIBOBJS=$ac_ltlibobjs
+
+
+
 : ${CONFIG_STATUS=./config.status}
-
-echo creating $CONFIG_STATUS
-rm -f $CONFIG_STATUS
-cat > $CONFIG_STATUS <<EOF
-#! /bin/sh
-# Generated automatically by configure.
+ac_clean_files_save=$ac_clean_files
+ac_clean_files="$ac_clean_files $CONFIG_STATUS"
+{ echo "$as_me:$LINENO: creating $CONFIG_STATUS" >&5
+echo "$as_me: creating $CONFIG_STATUS" >&6;}
+cat >$CONFIG_STATUS <<_ACEOF
+#! $SHELL
+# Generated by $as_me.
 # Run this file to recreate the current configuration.
-# This directory was configured as follows,
-# on host `(hostname || uname -n) 2>/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
+# configure, is in config.log if it exists.
+
+debug=false
+ac_cs_recheck=false
+ac_cs_silent=false
+SHELL=\${CONFIG_SHELL-$SHELL}
+_ACEOF
+
+cat >>$CONFIG_STATUS <<\_ACEOF
+## --------------------- ##
+## M4sh Initialization.  ##
+## --------------------- ##
+
+# Be more Bourne compatible
+DUALCASE=1; export DUALCASE # for MKS sh
+if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
+  emulate sh
+  NULLCMD=:
+  # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
+  # is contrary to our usage.  Disable this feature.
+  alias -g '${1+"$@"}'='"$@"'
+  setopt NO_GLOB_SUBST
+else
+  case `(set -o) 2>/dev/null` in
+  *posix*) set -o posix ;;
+esac
+
+fi
+
+
+
+
+# PATH needs CR
+# Avoid depending upon Character Ranges.
+as_cr_letters='abcdefghijklmnopqrstuvwxyz'
+as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
+as_cr_Letters=$as_cr_letters$as_cr_LETTERS
+as_cr_digits='0123456789'
+as_cr_alnum=$as_cr_Letters$as_cr_digits
+
+# The user is always right.
+if test "${PATH_SEPARATOR+set}" != set; then
+  echo "#! /bin/sh" >conf$$.sh
+  echo  "exit 0"   >>conf$$.sh
+  chmod +x conf$$.sh
+  if (PATH="/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then
+    PATH_SEPARATOR=';'
+  else
+    PATH_SEPARATOR=:
+  fi
+  rm -f conf$$.sh
+fi
+
+# Support unset when possible.
+if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then
+  as_unset=unset
+else
+  as_unset=false
+fi
+
+
+# IFS
+# We need space, tab and new line, in precisely that order.  Quoting is
+# there to prevent editors from complaining about space-tab.
+# (If _AS_PATH_WALK were called with IFS unset, it would disable word
+# splitting by setting IFS to empty value.)
+as_nl='
+'
+IFS=" ""	$as_nl"
+
+# Find who we are.  Look in the path if we contain no directory separator.
+case $0 in
+  *[\\/]* ) as_myself=$0 ;;
+  *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
 do
-  case "\$ac_option" in
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+  test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break
+done
+IFS=$as_save_IFS
+
+     ;;
+esac
+# We did not find ourselves, most probably we were run as `sh COMMAND'
+# in which case we are not to be found in the path.
+if test "x$as_myself" = x; then
+  as_myself=$0
+fi
+if test ! -f "$as_myself"; then
+  echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2
+  { (exit 1); exit 1; }
+fi
+
+# Work around bugs in pre-3.0 UWIN ksh.
+for as_var in ENV MAIL MAILPATH
+do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var
+done
+PS1='$ '
+PS2='> '
+PS4='+ '
+
+# NLS nuisances.
+for as_var in \
+  LANG LANGUAGE LC_ADDRESS LC_ALL LC_COLLATE LC_CTYPE LC_IDENTIFICATION \
+  LC_MEASUREMENT LC_MESSAGES LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER \
+  LC_TELEPHONE LC_TIME
+do
+  if (set +x; test -z "`(eval $as_var=C; export $as_var) 2>&1`"); then
+    eval $as_var=C; export $as_var
+  else
+    ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var
+  fi
+done
+
+# Required to use basename.
+if expr a : '\(a\)' >/dev/null 2>&1 &&
+   test "X`expr 00001 : '.*\(...\)'`" = X001; then
+  as_expr=expr
+else
+  as_expr=false
+fi
+
+if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then
+  as_basename=basename
+else
+  as_basename=false
+fi
+
+
+# Name of the executable.
+as_me=`$as_basename -- "$0" ||
+$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
+	 X"$0" : 'X\(//\)$' \| \
+	 X"$0" : 'X\(/\)' \| . 2>/dev/null ||
+echo X/"$0" |
+    sed '/^.*\/\([^/][^/]*\)\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\/\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\/\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+
+# CDPATH.
+$as_unset CDPATH
+
+
+
+  as_lineno_1=$LINENO
+  as_lineno_2=$LINENO
+  test "x$as_lineno_1" != "x$as_lineno_2" &&
+  test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2" || {
+
+  # Create $as_me.lineno as a copy of $as_myself, but with $LINENO
+  # uniformly replaced by the line number.  The first 'sed' inserts a
+  # line-number line after each line using $LINENO; the second 'sed'
+  # does the real work.  The second script uses 'N' to pair each
+  # line-number line with the line containing $LINENO, and appends
+  # trailing '-' during substitution so that $LINENO is not a special
+  # case at line end.
+  # (Raja R Harinath suggested sed '=', and Paul Eggert wrote the
+  # scripts with optimization help from Paolo Bonzini.  Blame Lee
+  # E. McMahon (1931-1989) for sed's syntax.  :-)
+  sed -n '
+    p
+    /[$]LINENO/=
+  ' <$as_myself |
+    sed '
+      s/[$]LINENO.*/&-/
+      t lineno
+      b
+      :lineno
+      N
+      :loop
+      s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/
+      t loop
+      s/-\n.*//
+    ' >$as_me.lineno &&
+  chmod +x "$as_me.lineno" ||
+    { echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2
+   { (exit 1); exit 1; }; }
+
+  # Don't try to exec as it changes $[0], causing all sort of problems
+  # (the dirname of $[0] is not the place where we might find the
+  # original and so on.  Autoconf is especially sensitive to this).
+  . "./$as_me.lineno"
+  # Exit status is that of the last command.
+  exit
+}
+
+
+if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then
+  as_dirname=dirname
+else
+  as_dirname=false
+fi
+
+ECHO_C= ECHO_N= ECHO_T=
+case `echo -n x` in
+-n*)
+  case `echo 'x\c'` in
+  *c*) ECHO_T='	';;	# ECHO_T is single tab character.
+  *)   ECHO_C='\c';;
+  esac;;
+*)
+  ECHO_N='-n';;
+esac
+
+if expr a : '\(a\)' >/dev/null 2>&1 &&
+   test "X`expr 00001 : '.*\(...\)'`" = X001; then
+  as_expr=expr
+else
+  as_expr=false
+fi
+
+rm -f conf$$ conf$$.exe conf$$.file
+if test -d conf$$.dir; then
+  rm -f conf$$.dir/conf$$.file
+else
+  rm -f conf$$.dir
+  mkdir conf$$.dir
+fi
+echo >conf$$.file
+if ln -s conf$$.file conf$$ 2>/dev/null; then
+  as_ln_s='ln -s'
+  # ... but there are two gotchas:
+  # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail.
+  # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable.
+  # In both cases, we have to default to `cp -p'.
+  ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe ||
+    as_ln_s='cp -p'
+elif ln conf$$.file conf$$ 2>/dev/null; then
+  as_ln_s=ln
+else
+  as_ln_s='cp -p'
+fi
+rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file
+rmdir conf$$.dir 2>/dev/null
+
+if mkdir -p . 2>/dev/null; then
+  as_mkdir_p=:
+else
+  test -d ./-p && rmdir ./-p
+  as_mkdir_p=false
+fi
+
+if test -x / >/dev/null 2>&1; then
+  as_test_x='test -x'
+else
+  if ls -dL / >/dev/null 2>&1; then
+    as_ls_L_option=L
+  else
+    as_ls_L_option=
+  fi
+  as_test_x='
+    eval sh -c '\''
+      if test -d "$1"; then
+        test -d "$1/.";
+      else
+	case $1 in
+        -*)set "./$1";;
+	esac;
+	case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in
+	???[sx]*):;;*)false;;esac;fi
+    '\'' sh
+  '
+fi
+as_executable_p=$as_test_x
+
+# Sed expression to map a string onto a valid CPP name.
+as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
+
+# Sed expression to map a string onto a valid variable name.
+as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'"
+
+
+exec 6>&1
+
+# Save the log message, to keep $[0] and so on meaningful, and to
+# report actual input values of CONFIG_FILES etc. instead of their
+# values after options handling.
+ac_log="
+This file was extended by $as_me, which was
+generated by GNU Autoconf 2.61.  Invocation command line was
+
+  CONFIG_FILES    = $CONFIG_FILES
+  CONFIG_HEADERS  = $CONFIG_HEADERS
+  CONFIG_LINKS    = $CONFIG_LINKS
+  CONFIG_COMMANDS = $CONFIG_COMMANDS
+  $ $0 $@
+
+on `(hostname || uname -n) 2>/dev/null | sed 1q`
+"
+
+_ACEOF
+
+cat >>$CONFIG_STATUS <<_ACEOF
+# Files that config.status was made for.
+config_files="$ac_config_files"
+
+_ACEOF
+
+cat >>$CONFIG_STATUS <<\_ACEOF
+ac_cs_usage="\
+\`$as_me' instantiates files from templates according to the
+current configuration.
+
+Usage: $0 [OPTIONS] [FILE]...
+
+  -h, --help       print this help, then exit
+  -V, --version    print version number and configuration settings, then exit
+  -q, --quiet      do not print progress messages
+  -d, --debug      don't remove temporary files
+      --recheck    update $as_me by reconfiguring in the same conditions
+  --file=FILE[:TEMPLATE]
+		   instantiate the configuration file FILE
+
+Configuration files:
+$config_files
+
+Report bugs to <bug-autoconf at gnu.org>."
+
+_ACEOF
+cat >>$CONFIG_STATUS <<_ACEOF
+ac_cs_version="\\
+config.status
+configured by $0, generated by GNU Autoconf 2.61,
+  with options \\"`echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`\\"
+
+Copyright (C) 2006 Free Software Foundation, Inc.
+This config.status script is free software; the Free Software Foundation
+gives unlimited permission to copy, distribute and modify it."
+
+ac_pwd='$ac_pwd'
+srcdir='$srcdir'
+_ACEOF
+
+cat >>$CONFIG_STATUS <<\_ACEOF
+# If no file are specified by the user, then we need to provide default
+# value.  By we need to know if files were specified by the user.
+ac_need_defaults=:
+while test $# != 0
+do
+  case $1 in
+  --*=*)
+    ac_option=`expr "X$1" : 'X\([^=]*\)='`
+    ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'`
+    ac_shift=:
+    ;;
+  *)
+    ac_option=$1
+    ac_optarg=$2
+    ac_shift=shift
+    ;;
+  esac
+
+  case $ac_option in
+  # Handling of the options.
   -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 ;;
+    ac_cs_recheck=: ;;
+  --version | --versio | --versi | --vers | --ver | --ve | --v | -V )
+    echo "$ac_cs_version"; exit ;;
+  --debug | --debu | --deb | --de | --d | -d )
+    debug=: ;;
+  --file | --fil | --fi | --f )
+    $ac_shift
+    CONFIG_FILES="$CONFIG_FILES $ac_optarg"
+    ac_need_defaults=false;;
+  --he | --h |  --help | --hel | -h )
+    echo "$ac_cs_usage"; exit ;;
+  -q | -quiet | --quiet | --quie | --qui | --qu | --q \
+  | -silent | --silent | --silen | --sile | --sil | --si | --s)
+    ac_cs_silent=: ;;
+
+  # This is an error.
+  -*) { echo "$as_me: error: unrecognized option: $1
+Try \`$0 --help' for more information." >&2
+   { (exit 1); exit 1; }; } ;;
+
+  *) ac_config_targets="$ac_config_targets $1"
+     ac_need_defaults=false ;;
+
+  esac
+  shift
+done
+
+ac_configure_extra_args=
+
+if $ac_cs_silent; then
+  exec 6>/dev/null
+  ac_configure_extra_args="$ac_configure_extra_args --silent"
+fi
+
+_ACEOF
+cat >>$CONFIG_STATUS <<_ACEOF
+if \$ac_cs_recheck; then
+  echo "running CONFIG_SHELL=$SHELL $SHELL $0 "$ac_configure_args \$ac_configure_extra_args " --no-create --no-recursion" >&6
+  CONFIG_SHELL=$SHELL
+  export CONFIG_SHELL
+  exec $SHELL "$0"$ac_configure_args \$ac_configure_extra_args --no-create --no-recursion
+fi
+
+_ACEOF
+cat >>$CONFIG_STATUS <<\_ACEOF
+exec 5>>config.log
+{
+  echo
+  sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX
+## Running $as_me. ##
+_ASBOX
+  echo "$ac_log"
+} >&5
+
+_ACEOF
+cat >>$CONFIG_STATUS <<_ACEOF
+_ACEOF
+
+cat >>$CONFIG_STATUS <<\_ACEOF
+
+# Handling of arguments.
+for ac_config_target in $ac_config_targets
+do
+  case $ac_config_target in
+    "Makefile") CONFIG_FILES="$CONFIG_FILES Makefile" ;;
+
+  *) { { echo "$as_me:$LINENO: error: invalid argument: $ac_config_target" >&5
+echo "$as_me: error: invalid argument: $ac_config_target" >&2;}
+   { (exit 1); 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 <<EOF
-
-# Protect against being on the right side of a sed subst in config.status.
-sed 's/%@/@@/; s/@%/@@/; s/%g\$/@g/; /@g\$/s/[\\\\&%]/\\\\&/g;
- s/@@/%@/; s/@@/@%/; s/@g\$/%g/' > 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%@SET_MAKE@%$SET_MAKE%g
-s%@CC@%$CC%g
-s%@CPP@%$CPP%g
-s%@CXX@%$CXX%g
-s%@CXXCPP@%$CXXCPP%g
-s%@RANLIB@%$RANLIB%g
-s%@INSTALL@%$INSTALL%g
-s%@INSTALL_PROGRAM@%$INSTALL_PROGRAM%g
-s%@INSTALL_DATA@%$INSTALL_DATA%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
+
+# If the user did not use the arguments to specify the items to instantiate,
+# then the envvar interface is used.  Set only those that are not.
+# We use the long form for the default assignment because of an extremely
+# bizarre bug on SunOS 4.1.3.
+if $ac_need_defaults; then
+  test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files
+fi
+
+# Have a temporary directory for convenience.  Make it in the build tree
+# simply because there is no reason against having it here, and in addition,
+# creating and moving files from /tmp can sometimes cause problems.
+# Hook for its removal unless debugging.
+# Note that there is a small window in which the directory will not be cleaned:
+# after its creation but before its name has been assigned to `$tmp'.
+$debug ||
+{
+  tmp=
+  trap 'exit_status=$?
+  { test -z "$tmp" || test ! -d "$tmp" || rm -fr "$tmp"; } && exit $exit_status
+' 0
+  trap '{ (exit 1); exit 1; }' 1 2 13 15
+}
+# Create a (secure) tmp directory for tmp files.
+
+{
+  tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` &&
+  test -n "$tmp" && test -d "$tmp"
+}  ||
+{
+  tmp=./conf$$-$RANDOM
+  (umask 077 && mkdir "$tmp")
+} ||
+{
+   echo "$me: cannot create a temporary directory in ." >&2
+   { (exit 1); exit 1; }
+}
+
+#
+# Set up the sed scripts for CONFIG_FILES section.
+#
+
+# No need to generate the scripts if there are no CONFIG_FILES.
+# This happens for instance when ./config.status config.h
+if test -n "$CONFIG_FILES"; then
+
+_ACEOF
+
+
+
+ac_delim='%!_!# '
+for ac_last_try in false false false false false :; do
+  cat >conf$$subs.sed <<_ACEOF
+SHELL!$SHELL$ac_delim
+PATH_SEPARATOR!$PATH_SEPARATOR$ac_delim
+PACKAGE_NAME!$PACKAGE_NAME$ac_delim
+PACKAGE_TARNAME!$PACKAGE_TARNAME$ac_delim
+PACKAGE_VERSION!$PACKAGE_VERSION$ac_delim
+PACKAGE_STRING!$PACKAGE_STRING$ac_delim
+PACKAGE_BUGREPORT!$PACKAGE_BUGREPORT$ac_delim
+exec_prefix!$exec_prefix$ac_delim
+prefix!$prefix$ac_delim
+program_transform_name!$program_transform_name$ac_delim
+bindir!$bindir$ac_delim
+sbindir!$sbindir$ac_delim
+libexecdir!$libexecdir$ac_delim
+datarootdir!$datarootdir$ac_delim
+datadir!$datadir$ac_delim
+sysconfdir!$sysconfdir$ac_delim
+sharedstatedir!$sharedstatedir$ac_delim
+localstatedir!$localstatedir$ac_delim
+includedir!$includedir$ac_delim
+oldincludedir!$oldincludedir$ac_delim
+docdir!$docdir$ac_delim
+infodir!$infodir$ac_delim
+htmldir!$htmldir$ac_delim
+dvidir!$dvidir$ac_delim
+pdfdir!$pdfdir$ac_delim
+psdir!$psdir$ac_delim
+libdir!$libdir$ac_delim
+localedir!$localedir$ac_delim
+mandir!$mandir$ac_delim
+DEFS!$DEFS$ac_delim
+ECHO_C!$ECHO_C$ac_delim
+ECHO_N!$ECHO_N$ac_delim
+ECHO_T!$ECHO_T$ac_delim
+LIBS!$LIBS$ac_delim
+build_alias!$build_alias$ac_delim
+host_alias!$host_alias$ac_delim
+target_alias!$target_alias$ac_delim
+SET_MAKE!$SET_MAKE$ac_delim
+CC!$CC$ac_delim
+CFLAGS!$CFLAGS$ac_delim
+LDFLAGS!$LDFLAGS$ac_delim
+CPPFLAGS!$CPPFLAGS$ac_delim
+ac_ct_CC!$ac_ct_CC$ac_delim
+EXEEXT!$EXEEXT$ac_delim
+OBJEXT!$OBJEXT$ac_delim
+CPP!$CPP$ac_delim
+CXX!$CXX$ac_delim
+CXXFLAGS!$CXXFLAGS$ac_delim
+ac_ct_CXX!$ac_ct_CXX$ac_delim
+CXXCPP!$CXXCPP$ac_delim
+RANLIB!$RANLIB$ac_delim
+INSTALL!$INSTALL$ac_delim
+INSTALL_PROGRAM!$INSTALL_PROGRAM$ac_delim
+INSTALL_DATA!$INSTALL_DATA$ac_delim
+LIBOBJS!$LIBOBJS$ac_delim
+LTLIBOBJS!$LTLIBOBJS$ac_delim
+_ACEOF
+
+  if test `sed -n "s/.*$ac_delim\$/X/p" conf$$subs.sed | grep -c X` = 56; then
+    break
+  elif $ac_last_try; then
+    { { echo "$as_me:$LINENO: error: could not make $CONFIG_STATUS" >&5
+echo "$as_me: error: could not make $CONFIG_STATUS" >&2;}
+   { (exit 1); exit 1; }; }
   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`
+    ac_delim="$ac_delim!$ac_delim _$ac_delim!! "
   fi
 done
-if test -z "$ac_sed_cmds"; then
-  ac_sed_cmds=cat
+
+ac_eof=`sed -n '/^CEOF[0-9]*$/s/CEOF/0/p' conf$$subs.sed`
+if test -n "$ac_eof"; then
+  ac_eof=`echo "$ac_eof" | sort -nru | sed 1q`
+  ac_eof=`expr $ac_eof + 1`
 fi
-EOF
-
-cat >> $CONFIG_STATUS <<EOF
-
-CONFIG_FILES=\${CONFIG_FILES-"Makefile"}
-EOF
-cat >> $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" ;;
+
+cat >>$CONFIG_STATUS <<_ACEOF
+cat >"\$tmp/subs-1.sed" <<\CEOF$ac_eof
+/@[a-zA-Z_][a-zA-Z_0-9]*@/!b end
+_ACEOF
+sed '
+s/[,\\&]/\\&/g; s/@/@|#_!!_#|/g
+s/^/s,@/; s/!/@,|#_!!_#|/
+:n
+t n
+s/'"$ac_delim"'$/,g/; t
+s/$/\\/; p
+N; s/^.*\n//; s/[,\\&]/\\&/g; s/@/@|#_!!_#|/g; b n
+' >>$CONFIG_STATUS <conf$$subs.sed
+rm -f conf$$subs.sed
+cat >>$CONFIG_STATUS <<_ACEOF
+:end
+s/|#_!!_#|//g
+CEOF$ac_eof
+_ACEOF
+
+
+# VPATH may cause trouble with some makes, so we remove $(srcdir),
+# ${srcdir} and @srcdir@ from VPATH if srcdir is ".", strip leading and
+# trailing colons and then remove the whole line if VPATH becomes empty
+# (actually we leave an empty line to preserve line numbers).
+if test "x$srcdir" = x.; then
+  ac_vpsub='/^[	 ]*VPATH[	 ]*=/{
+s/:*\$(srcdir):*/:/
+s/:*\${srcdir}:*/:/
+s/:*@srcdir@:*/:/
+s/^\([^=]*=[	 ]*\):*/\1/
+s/:*$//
+s/^[^=]*=[	 ]*$//
+}'
+fi
+
+cat >>$CONFIG_STATUS <<\_ACEOF
+fi # test -n "$CONFIG_FILES"
+
+
+for ac_tag in  :F $CONFIG_FILES
+do
+  case $ac_tag in
+  :[FHLC]) ac_mode=$ac_tag; continue;;
   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" ;;
+  case $ac_mode$ac_tag in
+  :[FHL]*:*);;
+  :L* | :C*:*) { { echo "$as_me:$LINENO: error: Invalid tag $ac_tag." >&5
+echo "$as_me: error: Invalid tag $ac_tag." >&2;}
+   { (exit 1); exit 1; }; };;
+  :[FH]-) ac_tag=-:-;;
+  :[FH]*) ac_tag=$ac_tag:$ac_tag.in;;
   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= ;;
+  ac_save_IFS=$IFS
+  IFS=:
+  set x $ac_tag
+  IFS=$ac_save_IFS
+  shift
+  ac_file=$1
+  shift
+
+  case $ac_mode in
+  :L) ac_source=$1;;
+  :[FH])
+    ac_file_inputs=
+    for ac_f
+    do
+      case $ac_f in
+      -) ac_f="$tmp/stdin";;
+      *) # Look for the file first in the build tree, then in the source tree
+	 # (if the path is not absolute).  The absolute path cannot be DOS-style,
+	 # because $ac_f cannot contain `:'.
+	 test -f "$ac_f" ||
+	   case $ac_f in
+	   [\\/$]*) false;;
+	   *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";;
+	   esac ||
+	   { { echo "$as_me:$LINENO: error: cannot find input file: $ac_f" >&5
+echo "$as_me: error: cannot find input file: $ac_f" >&2;}
+   { (exit 1); exit 1; }; };;
+      esac
+      ac_file_inputs="$ac_file_inputs $ac_f"
+    done
+
+    # Let's still pretend it is `configure' which instantiates (i.e., don't
+    # use $as_me), people would be surprised to read:
+    #    /* config.h.  Generated by config.status.  */
+    configure_input="Generated from "`IFS=:
+	  echo $* | sed 's|^[^:]*/||;s|:[^:]*/|, |g'`" by configure."
+    if test x"$ac_file" != x-; then
+      configure_input="$ac_file.  $configure_input"
+      { echo "$as_me:$LINENO: creating $ac_file" >&5
+echo "$as_me: creating $ac_file" >&6;}
+    fi
+
+    case $ac_tag in
+    *:-:* | *:-) cat >"$tmp/stdin";;
+    esac
+    ;;
   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 <<EOF
-
-EOF
-cat >> $CONFIG_STATUS <<\EOF
-
-exit 0
-EOF
+  ac_dir=`$as_dirname -- "$ac_file" ||
+$as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+	 X"$ac_file" : 'X\(//\)[^/]' \| \
+	 X"$ac_file" : 'X\(//\)$' \| \
+	 X"$ac_file" : 'X\(/\)' \| . 2>/dev/null ||
+echo X"$ac_file" |
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)[^/].*/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+  { as_dir="$ac_dir"
+  case $as_dir in #(
+  -*) as_dir=./$as_dir;;
+  esac
+  test -d "$as_dir" || { $as_mkdir_p && mkdir -p "$as_dir"; } || {
+    as_dirs=
+    while :; do
+      case $as_dir in #(
+      *\'*) as_qdir=`echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #(
+      *) as_qdir=$as_dir;;
+      esac
+      as_dirs="'$as_qdir' $as_dirs"
+      as_dir=`$as_dirname -- "$as_dir" ||
+$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+	 X"$as_dir" : 'X\(//\)[^/]' \| \
+	 X"$as_dir" : 'X\(//\)$' \| \
+	 X"$as_dir" : 'X\(/\)' \| . 2>/dev/null ||
+echo X"$as_dir" |
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)[^/].*/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+      test -d "$as_dir" && break
+    done
+    test -z "$as_dirs" || eval "mkdir $as_dirs"
+  } || test -d "$as_dir" || { { echo "$as_me:$LINENO: error: cannot create directory $as_dir" >&5
+echo "$as_me: error: cannot create directory $as_dir" >&2;}
+   { (exit 1); exit 1; }; }; }
+  ac_builddir=.
+
+case "$ac_dir" in
+.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;
+*)
+  ac_dir_suffix=/`echo "$ac_dir" | sed 's,^\.[\\/],,'`
+  # A ".." for each directory in $ac_dir_suffix.
+  ac_top_builddir_sub=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,/..,g;s,/,,'`
+  case $ac_top_builddir_sub in
+  "") ac_top_builddir_sub=. ac_top_build_prefix= ;;
+  *)  ac_top_build_prefix=$ac_top_builddir_sub/ ;;
+  esac ;;
+esac
+ac_abs_top_builddir=$ac_pwd
+ac_abs_builddir=$ac_pwd$ac_dir_suffix
+# for backward compatibility:
+ac_top_builddir=$ac_top_build_prefix
+
+case $srcdir in
+  .)  # We are building in place.
+    ac_srcdir=.
+    ac_top_srcdir=$ac_top_builddir_sub
+    ac_abs_top_srcdir=$ac_pwd ;;
+  [\\/]* | ?:[\\/]* )  # Absolute name.
+    ac_srcdir=$srcdir$ac_dir_suffix;
+    ac_top_srcdir=$srcdir
+    ac_abs_top_srcdir=$srcdir ;;
+  *) # Relative name.
+    ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix
+    ac_top_srcdir=$ac_top_build_prefix$srcdir
+    ac_abs_top_srcdir=$ac_pwd/$srcdir ;;
+esac
+ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix
+
+
+  case $ac_mode in
+  :F)
+  #
+  # CONFIG_FILE
+  #
+
+_ACEOF
+
+cat >>$CONFIG_STATUS <<\_ACEOF
+# If the template does not know about datarootdir, expand it.
+# FIXME: This hack should be removed a few years after 2.60.
+ac_datarootdir_hack=; ac_datarootdir_seen=
+
+case `sed -n '/datarootdir/ {
+  p
+  q
+}
+/@datadir@/p
+/@docdir@/p
+/@infodir@/p
+/@localedir@/p
+/@mandir@/p
+' $ac_file_inputs` in
+*datarootdir*) ac_datarootdir_seen=yes;;
+*@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*)
+  { echo "$as_me:$LINENO: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5
+echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;}
+_ACEOF
+cat >>$CONFIG_STATUS <<_ACEOF
+  ac_datarootdir_hack='
+  s&@datadir@&$datadir&g
+  s&@docdir@&$docdir&g
+  s&@infodir@&$infodir&g
+  s&@localedir@&$localedir&g
+  s&@mandir@&$mandir&g
+    s&\\\${datarootdir}&$datarootdir&g' ;;
+esac
+_ACEOF
+
+# Neutralize VPATH when `$srcdir' = `.'.
+# Shell code in configure.ac might set extrasub.
+# FIXME: do we really want to maintain this feature?
+cat >>$CONFIG_STATUS <<_ACEOF
+  sed "$ac_vpsub
+$extrasub
+_ACEOF
+cat >>$CONFIG_STATUS <<\_ACEOF
+:t
+/@[a-zA-Z_][a-zA-Z_0-9]*@/!b
+s&@configure_input@&$configure_input&;t t
+s&@top_builddir@&$ac_top_builddir_sub&;t t
+s&@srcdir@&$ac_srcdir&;t t
+s&@abs_srcdir@&$ac_abs_srcdir&;t t
+s&@top_srcdir@&$ac_top_srcdir&;t t
+s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t
+s&@builddir@&$ac_builddir&;t t
+s&@abs_builddir@&$ac_abs_builddir&;t t
+s&@abs_top_builddir@&$ac_abs_top_builddir&;t t
+$ac_datarootdir_hack
+" $ac_file_inputs | sed -f "$tmp/subs-1.sed" >$tmp/out
+
+test -z "$ac_datarootdir_hack$ac_datarootdir_seen" &&
+  { ac_out=`sed -n '/\${datarootdir}/p' "$tmp/out"`; test -n "$ac_out"; } &&
+  { ac_out=`sed -n '/^[	 ]*datarootdir[	 ]*:*=/p' "$tmp/out"`; test -z "$ac_out"; } &&
+  { echo "$as_me:$LINENO: WARNING: $ac_file contains a reference to the variable \`datarootdir'
+which seems to be undefined.  Please make sure it is defined." >&5
+echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir'
+which seems to be undefined.  Please make sure it is defined." >&2;}
+
+  rm -f "$tmp/stdin"
+  case $ac_file in
+  -) cat "$tmp/out"; rm -f "$tmp/out";;
+  *) rm -f "$ac_file"; mv "$tmp/out" $ac_file;;
+  esac
+ ;;
+
+
+
+  esac
+
+done # for ac_tag
+
+
+{ (exit 0); exit 0; }
+_ACEOF
 chmod +x $CONFIG_STATUS
-rm -fr confdefs* $ac_clean_files
-test "$no_create" = yes || ${CONFIG_SHELL-/bin/sh} $CONFIG_STATUS || exit 1
-
+ac_clean_files=$ac_clean_files_save
+
+
+# configure is writing to config.log, and then calls config.status.
+# config.status does its own redirection, appending to config.log.
+# Unfortunately, on DOS this fails, as config.log is still kept open
+# by configure, so config.status won't be able to write to it; its
+# output is simply discarded.  So we exec the FD to /dev/null,
+# effectively closing config.log, so it can be properly (re)opened and
+# appended to by config.status.  When coming back to configure, we
+# need to make the FD available again.
+if test "$no_create" != yes; then
+  ac_cs_success=:
+  ac_config_status_args=
+  test "$silent" = yes &&
+    ac_config_status_args="$ac_config_status_args --quiet"
+  exec 5>/dev/null
+  $SHELL $CONFIG_STATUS $ac_config_status_args || ac_cs_success=false
+  exec 5>>config.log
+  # Use ||, not &&, to avoid exiting from the if with $? = 1, which
+  # would make configure fail if this is the last instruction.
+  $ac_cs_success || { (exit 1); exit 1; }
+fi
+
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/lib/configure.ac
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/contrib/gperf/lib/configure.ac	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,45 @@
+dnl autoconf configuration for gperf/lib
+
+dnl Copyright (C) 1998, 2002, 2005, 2007 Free Software Foundation, Inc.
+dnl Written by Douglas C. Schmidt <schmidt at ics.uci.edu>
+dnl and Bruno Haible <bruno at clisp.org>.
+dnl
+dnl This file is part of GNU GPERF.
+dnl
+dnl GNU GPERF is free software; you can redistribute it and/or modify
+dnl it under the terms of the GNU General Public License as published by
+dnl the Free Software Foundation; either version 2, or (at your option)
+dnl any later version.
+dnl
+dnl GNU GPERF is distributed in the hope that it will be useful,
+dnl but WITHOUT ANY WARRANTY; without even the implied warranty of
+dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+dnl GNU General Public License for more details.
+dnl
+dnl You should have received a copy of the GNU General Public License
+dnl along with this program; see the file COPYING.
+dnl If not, write to the Free Software Foundation, Inc.,
+dnl 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
+
+AC_PREREQ([2.60])
+AC_INIT(hash.cc)
+AC_PROG_MAKE_SET
+dnl
+dnl           checks for programs
+dnl
+AC_PROG_CC
+                      dnl sets variable CC
+AC_PROG_CPP
+                      dnl sets variable CPP
+AC_PROG_CXX
+                      dnl sets variable CXX
+AC_PROG_CXXCPP
+                      dnl sets variable CXXCPP
+AC_PROG_RANLIB
+                      dnl sets variable RANLIB
+CL_PROG_INSTALL
+                      dnl sets variables INSTALL, INSTALL_DATA, INSTALL_PROGRAM
+dnl
+dnl           That's it.
+dnl
+AC_OUTPUT(Makefile)
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/lib/configure.in
--- a/head/contrib/gperf/lib/configure.in	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,43 +0,0 @@
-dnl autoconf configuration for gperf/lib
-
-dnl Copyright (C) 1998 Free Software Foundation, Inc.
-dnl written by Douglas C. Schmidt (schmidt at ics.uci.edu)
-dnl
-dnl This file is part of GNU GPERF.
-dnl
-dnl GNU GPERF is free software; you can redistribute it and/or modify
-dnl it under the terms of the GNU General Public License as published by
-dnl the Free Software Foundation; either version 1, or (at your option)
-dnl any later version.
-dnl
-dnl GNU GPERF is distributed in the hope that it will be useful,
-dnl but WITHOUT ANY WARRANTY; without even the implied warranty of
-dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-dnl GNU General Public License for more details.
-dnl
-dnl You should have received a copy of the GNU General Public License
-dnl along with GNU GPERF; see the file COPYING.  If not, write to the
-dnl Free Software Foundation, 59 Temple Place - Suite 330, Boston,
-dnl MA 02111-1307, USA.
-
-AC_INIT(hash.cc)
-AC_PROG_MAKE_SET
-dnl
-dnl           checks for programs
-dnl
-AC_PROG_CC
-                      dnl sets variable CC
-AC_PROG_CPP
-                      dnl sets variable CPP
-AC_PROG_CXX
-                      dnl sets variable CXX
-AC_PROG_CXXCPP
-                      dnl sets variable CXXCPP
-CL_PROG_RANLIB
-                      dnl sets variable RANLIB
-CL_PROG_INSTALL
-                      dnl sets variables INSTALL, INSTALL_DATA, INSTALL_PROGRAM
-dnl
-dnl           That's it.
-dnl
-AC_OUTPUT(Makefile)
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/lib/getline.cc
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/contrib/gperf/lib/getline.cc	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,119 @@
+/* getline.c -- Replacement for GNU C library function getline
+
+Copyright (C) 1993, 1996, 2001-2002 Free Software Foundation, Inc.
+
+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. */
+
+/* Written by Jan Brittenson, bson at gnu.ai.mit.edu.  */
+
+/* Specification.  */
+#include "getline.h"
+
+#include <stddef.h>
+#include <stdio.h>
+#include <string.h>
+#include <assert.h>
+
+/* Always add at least this many bytes when extending the buffer.  */
+#define MIN_CHUNK 64
+
+/* Reads up to (and including) a TERMINATOR from STREAM into *LINEPTR + OFFSET
+   (and null-terminate it). *LINEPTR is a pointer returned from new [] (or
+   NULL), pointing to *N characters of space.  It is realloc'd as
+   necessary.  Returns the number of characters read (not including the
+   null terminator), or -1 on error or immediate EOF.
+   NOTE: There is another getstr() function declared in <curses.h>.  */
+
+static int
+getstr (char **lineptr, size_t *n, FILE *stream, char terminator, size_t offset)
+{
+  size_t nchars_avail;          /* Allocated but unused chars in *LINEPTR.  */
+  char *read_pos;               /* Where we're reading into *LINEPTR. */
+
+  if (!lineptr || !n || !stream)
+    return -1;
+
+  if (!*lineptr)
+    {
+      *n = MIN_CHUNK;
+      *lineptr = new char[*n];
+    }
+
+  nchars_avail = *n - offset;
+  read_pos = *lineptr + offset;
+
+  for (;;)
+    {
+      register int c = getc (stream);
+
+      /* We always want at least one char left in the buffer, since we
+         always (unless we get an error while reading the first char)
+         NUL-terminate the line buffer.  */
+
+      assert (*n - nchars_avail == (size_t) (read_pos - *lineptr));
+      if (nchars_avail < 2)
+        {
+          if (*n > MIN_CHUNK)
+            *n *= 2;
+          else
+            *n += MIN_CHUNK;
+
+          nchars_avail = *n + *lineptr - read_pos;
+          char *new_line = new char[*n];
+          if (*lineptr)
+            {
+              memcpy (new_line, *lineptr, read_pos - *lineptr);
+              delete[] *lineptr;
+            }
+          *lineptr = new_line;
+          read_pos = *n - nchars_avail + *lineptr;
+          assert (*n - nchars_avail == (size_t) (read_pos - *lineptr));
+        }
+
+      if (c == EOF || ferror (stream))
+        {
+          /* Return partial line, if any.  */
+          if (read_pos == *lineptr)
+            return -1;
+          else
+            break;
+        }
+
+      *read_pos++ = c;
+      nchars_avail--;
+
+      if (c == terminator)
+        /* Return the line.  */
+        break;
+    }
+
+  /* Done - NUL terminate and return the number of chars read.  */
+  *read_pos = '\0';
+
+  return read_pos - (*lineptr + offset);
+}
+
+int
+get_line (char **lineptr, size_t *n, FILE *stream)
+{
+  return getstr (lineptr, n, stream, '\n', 0);
+}
+
+int
+get_delim (char **lineptr, size_t *n, int delimiter, FILE *stream)
+{
+  return getstr (lineptr, n, stream, delimiter, 0);
+}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/lib/getline.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/contrib/gperf/lib/getline.h	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,41 @@
+/*  Copyright (C) 1995, 2000-2002 Free Software Foundation, Inc.
+
+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, 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.  */
+
+#ifndef GETLINE_H_
+# define GETLINE_H_ 1
+
+# include <stddef.h>
+# include <stdio.h>
+
+/* Like the glibc functions get_line and get_delim, except that the result
+   must be freed using delete[], not free().  */
+
+/* Reads up to (and including) a newline from STREAM into *LINEPTR
+   (and null-terminate it). *LINEPTR is a pointer returned from new [] (or
+   NULL), pointing to *N characters of space.  It is realloc'd as
+   necessary.  Returns the number of characters read (not including the
+   null terminator), or -1 on error or immediate EOF.  */
+extern int get_line (char **lineptr, size_t *n, FILE *stream);
+
+/* Reads up to (and including) a DELIMITER from STREAM into *LINEPTR
+   (and null-terminate it). *LINEPTR is a pointer returned from new [] (or
+   NULL), pointing to *N characters of space.  It is realloc'd as
+   necessary.  Returns the number of characters read (not including the
+   null terminator), or -1 on error or immediate EOF.  */
+extern int get_delim (char **lineptr, size_t *n, int delimiter, FILE *stream);
+
+#endif /* not GETLINE_H_ */
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/lib/hash.cc
--- a/head/contrib/gperf/lib/hash.cc	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/contrib/gperf/lib/hash.cc	Tue Dec 06 20:26:16 2011 +0200
@@ -1,6 +1,6 @@
 /* 
-Copyright (C) 1990, 2000 Free Software Foundation
-    written by Doug Lea (dl at rocky.oswego.edu)
+Copyright (C) 1990, 2000, 2002 Free Software Foundation
+    written by Doug Lea <dl at rocky.oswego.edu>
 */
 
 #include <hash.h>
@@ -12,14 +12,14 @@
 */
 
 unsigned int
-hashpjw (const char *x, unsigned int len) // From Dragon book, p436
+hashpjw (const unsigned char *x, unsigned int len) // From Dragon book, p436
 {
   unsigned int h = 0;
   unsigned int g;
 
   for (; len > 0; len--)
     {
-      h = (h << 4) + (unsigned char) *x++;
+      h = (h << 4) + *x++;
       if ((g = h & 0xf0000000) != 0)
         h = (h ^ (g >> 24)) ^ g;
     }
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/lib/hash.h
--- a/head/contrib/gperf/lib/hash.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/contrib/gperf/lib/hash.h	Tue Dec 06 20:26:16 2011 +0200
@@ -1,8 +1,8 @@
 // This may look like C code, but it is really -*- C++ -*-
 
 /* 
-Copyright (C) 1988, 1992, 2000 Free Software Foundation
-    written by Doug Lea (dl at rocky.oswego.edu)
+Copyright (C) 1988, 1992, 2000, 2002 Free Software Foundation
+    written by Doug Lea <dl at rocky.oswego.edu>
 */
 
 #ifndef _hash_h
@@ -10,6 +10,6 @@
 
 /* a hash function for char[] arrays using the
    method described in Aho, Sethi, & Ullman, p 436. */
-extern unsigned int hashpjw (const char *string, unsigned int len);
+extern unsigned int hashpjw (const unsigned char *string, unsigned int len);
 
 #endif
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/src/Makefile.in
--- a/head/contrib/gperf/src/Makefile.in	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/contrib/gperf/src/Makefile.in	Tue Dec 06 20:26:16 2011 +0200
@@ -1,13 +1,14 @@
 # Makefile for gperf/src
 
-# Copyright (C) 1989, 1992, 1993, 1998, 2000 Free Software Foundation, Inc.
-# written by Douglas C. Schmidt (schmidt at ics.uci.edu)
+# Copyright (C) 1989, 1992, 1993, 1998, 2000, 2002, 2006 Free Software Foundation, Inc.
+# Written by Douglas C. Schmidt <schmidt at ics.uci.edu>
+# and Bruno Haible <bruno at clisp.org>.
 #
 # This file is part of GNU GPERF.
 #
 # GNU GPERF 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 1, or (at your option)
+# the Free Software Foundation; either version 2, or (at your option)
 # any later version.
 #
 # GNU GPERF is distributed in the hope that it will be useful,
@@ -16,8 +17,9 @@
 # GNU General Public License for more details.
 #
 # You should have received a copy of the GNU General Public License
-# along with GNU GPERF; see the file COPYING.  If not, write to the Free
-# Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111, USA.
+# along with this program; see the file COPYING.
+# If not, write to the Free Software Foundation, Inc.,
+# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 
 #### Start of system configuration section. ####
 
@@ -41,6 +43,8 @@
 CXXCPP = @CXXCPP@
 # Both C and C++ compiler
 LDFLAGS = @LDFLAGS@
+OBJEXT = @OBJEXT@
+EXEEXT = @EXEEXT@
 # Other
 MV = mv
 LN = ln
@@ -59,12 +63,12 @@
 
 VPATH = $(srcdir)
 
-OBJECTS  = new.o options.o iterator.o main.o gen-perf.o key-list.o list-node.o \
-           hash-table.o bool-array.o read-line.o trace.o vectors.o version.o
-LIBS     = ../lib/libgp.a -lm
+OBJECTS  = version.$(OBJEXT) positions.$(OBJEXT) options.$(OBJEXT) keyword.$(OBJEXT) keyword-list.$(OBJEXT) \
+           input.$(OBJEXT) bool-array.$(OBJEXT) hash-table.$(OBJEXT) search.$(OBJEXT) output.$(OBJEXT) main.$(OBJEXT)
+LIBS     = ../lib/libgp.a @GPERF_LIBM@
 CPPFLAGS = -I. -I$(srcdir)/../lib
 
-TARGETPROG = gperf
+TARGETPROG = gperf$(EXEEXT)
 
 all : $(TARGETPROG)
 
@@ -83,43 +87,38 @@
 # Dependencies.
 CONFIG_H = config.h
 VERSION_H = version.h
-VECTORS_H = vectors.h
-TRACE_H = trace.h
-READ_LINE_H = read-line.h read-line.icc $(TRACE_H)
-OPTIONS_H = options.h options.icc $(TRACE_H)
-LIST_NODE_H = list-node.h $(VECTORS_H)
-KEY_LIST_H = key-list.h $(LIST_NODE_H) $(VECTORS_H) $(READ_LINE_H)
-ITERATOR_H = iterator.h
-HASH_TABLE_H = hash-table.h $(LIST_NODE_H)
-BOOL_ARRAY_H = bool-array.h bool-array.icc $(TRACE_H) $(OPTIONS_H)
-GEN_PERF_H = gen-perf.h $(KEY_LIST_H) $(BOOL_ARRAY_H)
+POSITIONS_H = positions.h positions.icc
+OPTIONS_H = options.h options.icc $(POSITIONS_H)
+KEYWORD_H = keyword.h keyword.icc
+KEYWORD_LIST_H = keyword-list.h keyword-list.icc $(KEYWORD_H)
+INPUT_H = input.h $(KEYWORD_LIST_H)
+BOOL_ARRAY_H = bool-array.h bool-array.icc $(OPTIONS_H)
+HASH_TABLE_H = hash-table.h $(KEYWORD_H)
+SEARCH_H = search.h $(KEYWORD_LIST_H) $(POSITIONS_H) $(BOOL_ARRAY_H)
+OUTPUT_H = output.h $(KEYWORD_LIST_H) $(POSITIONS_H)
 
-bool-array.o : bool-array.cc $(BOOL_ARRAY_H) $(OPTIONS_H) $(TRACE_H)
+version.$(OBJEXT): version.cc $(VERSION_H)
+	$(CXX) $(CXXFLAGS) $(CPPFLAGS) -c $(srcdir)/version.cc
+positions.$(OBJEXT): positions.cc $(POSITIONS_H)
+	$(CXX) $(CXXFLAGS) $(CPPFLAGS) -c $(srcdir)/positions.cc
+options.$(OBJEXT): options.cc $(OPTIONS_H) $(VERSION_H)
+	$(CXX) $(CXXFLAGS) $(CPPFLAGS) -c $(srcdir)/options.cc
+keyword.$(OBJEXT): keyword.cc $(KEYWORD_H) $(POSITIONS_H)
+	$(CXX) $(CXXFLAGS) $(CPPFLAGS) -c $(srcdir)/keyword.cc
+keyword-list.$(OBJEXT): keyword-list.cc $(KEYWORD_LIST_H)
+	$(CXX) $(CXXFLAGS) $(CPPFLAGS) -c $(srcdir)/keyword-list.cc
+input.$(OBJEXT): input.cc $(INPUT_H) $(OPTIONS_H)
+	$(CXX) $(CXXFLAGS) $(CPPFLAGS) -c $(srcdir)/input.cc
+bool-array.$(OBJEXT): bool-array.cc $(BOOL_ARRAY_H) $(OPTIONS_H)
 	$(CXX) $(CXXFLAGS) $(CPPFLAGS) -c $(srcdir)/bool-array.cc
-gen-perf.o : gen-perf.cc $(GEN_PERF_H) $(OPTIONS_H) $(TRACE_H)
-	$(CXX) $(CXXFLAGS) $(CPPFLAGS) -c $(srcdir)/gen-perf.cc
-hash-table.o : hash-table.cc $(HASH_TABLE_H) $(OPTIONS_H) $(TRACE_H)
+hash-table.$(OBJEXT): hash-table.cc $(HASH_TABLE_H) $(OPTIONS_H)
 	$(CXX) $(CXXFLAGS) $(CPPFLAGS) -c $(srcdir)/hash-table.cc
-iterator.o : iterator.cc $(ITERATOR_H) $(TRACE_H)
-	$(CXX) $(CXXFLAGS) $(CPPFLAGS) -c $(srcdir)/iterator.cc
-key-list.o : key-list.cc $(KEY_LIST_H) $(OPTIONS_H) $(READ_LINE_H) $(HASH_TABLE_H) $(TRACE_H) $(VERSION_H)
-	$(CXX) $(CXXFLAGS) $(CPPFLAGS) -c $(srcdir)/key-list.cc
-list-node.o : list-node.cc $(LIST_NODE_H) $(OPTIONS_H) $(TRACE_H)
-	$(CXX) $(CXXFLAGS) $(CPPFLAGS) -c $(srcdir)/list-node.cc
-main.o : main.cc $(OPTIONS_H) $(GEN_PERF_H) $(TRACE_H) $(CONFIG_H)
+search.$(OBJEXT): search.cc $(SEARCH_H) $(OPTIONS_H) $(HASH_TABLE_H) $(CONFIG_H)
+	$(CXX) $(CXXFLAGS) $(CPPFLAGS) -c $(srcdir)/search.cc
+output.$(OBJEXT): output.cc $(OUTPUT_H) $(OPTIONS_H) $(VERSION_H)
+	$(CXX) $(CXXFLAGS) $(CPPFLAGS) -c $(srcdir)/output.cc
+main.$(OBJEXT): main.cc $(OPTIONS_H) $(INPUT_H) $(SEARCH_H) $(OUTPUT_H)
 	$(CXX) $(CXXFLAGS) $(CPPFLAGS) -c $(srcdir)/main.cc
-new.o : new.cc $(TRACE_H) $(CONFIG_H)
-	$(CXX) $(CXXFLAGS) $(CPPFLAGS) -c $(srcdir)/new.cc
-options.o : options.cc $(OPTIONS_H) $(ITERATOR_H) $(TRACE_H) $(VECTORS_H) $(VERSION_H)
-	$(CXX) $(CXXFLAGS) $(CPPFLAGS) -c $(srcdir)/options.cc
-read-line.o : read-line.cc $(READ_LINE_H) $(OPTIONS_H) $(TRACE_H)
-	$(CXX) $(CXXFLAGS) $(CPPFLAGS) -c $(srcdir)/read-line.cc
-trace.o : trace.cc $(TRACE_H)
-	$(CXX) $(CXXFLAGS) $(CPPFLAGS) -c $(srcdir)/trace.cc
-vectors.o : vectors.cc $(VECTORS_H)
-	$(CXX) $(CXXFLAGS) $(CPPFLAGS) -c $(srcdir)/vectors.cc
-version.o : version.cc $(VERSION_H)
-	$(CXX) $(CXXFLAGS) $(CPPFLAGS) -c $(srcdir)/version.cc
 
 install : all force
 	$(MKINSTALLDIRS) $(DESTDIR)$(bindir)
@@ -136,7 +135,7 @@
 mostlyclean : clean
 
 clean : force
-	$(RM) *~ *.s *.o *.a $(TARGETPROG) core
+	$(RM) *~ *.s *.$(OBJEXT) *.a $(TARGETPROG) core
 
 distclean : clean
 	$(RM) config.status config.log config.cache Makefile config.h
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/src/bool-array.cc
--- a/head/contrib/gperf/src/bool-array.cc	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/contrib/gperf/src/bool-array.cc	Tue Dec 06 20:26:16 2011 +0200
@@ -1,43 +1,41 @@
 /* Fast lookup table abstraction implemented as an Iteration Number Array
-   Copyright (C) 1989-1998 Free Software Foundation, Inc.
-   written by Douglas C. Schmidt (schmidt at ics.uci.edu)
+   Copyright (C) 1989-1998, 2002 Free Software Foundation, Inc.
+   Written by Douglas C. Schmidt <schmidt at ics.uci.edu>
+   and Bruno Haible <bruno at clisp.org>.
 
-This file is part of GNU GPERF.
+   This file is part of GNU GPERF.
 
-GNU GPERF 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 1, or (at your option)
-any later version.
+   GNU GPERF 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 GPERF 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.
+   GNU GPERF 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 GPERF; see the file COPYING.  If not, write to the Free
-Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111, USA.  */
+   You should have received a copy of the GNU General Public License
+   along with this program; see the file COPYING.
+   If not, write to the Free Software Foundation, Inc.,
+   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
 
+/* Specification. */
 #include "bool-array.h"
 
 #include <stdio.h>
 #include <string.h>
 #include "options.h"
-#include "trace.h"
 
-STORAGE_TYPE * Bool_Array::storage_array;
-STORAGE_TYPE Bool_Array::iteration_number;
-unsigned int Bool_Array::size;
-
-/* Prints out debugging diagnostics. */
-
-Bool_Array::~Bool_Array (void)
+/* Frees this object.  */
+Bool_Array::~Bool_Array ()
 {
-  T (Trace t ("Bool_Array::~Bool_Array");)
+  /* Print out debugging diagnostics. */
   if (option[DEBUG])
     fprintf (stderr, "\ndumping boolean array information\n"
              "size = %d\niteration number = %d\nend of array dump\n",
-             size, iteration_number);
+             _size, _iteration_number);
+  delete[] const_cast<unsigned int *>(_storage_array);
 }
 
 #ifndef __OPTIMIZE__
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/src/bool-array.h
--- a/head/contrib/gperf/src/bool-array.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/contrib/gperf/src/bool-array.h	Tue Dec 06 20:26:16 2011 +0200
@@ -2,54 +2,67 @@
 
 /* Simple lookup table abstraction implemented as an Iteration Number Array.
 
-   Copyright (C) 1989-1998 Free Software Foundation, Inc.
-   written by Douglas C. Schmidt (schmidt at ics.uci.edu)
+   Copyright (C) 1989-1998, 2002 Free Software Foundation, Inc.
+   Written by Douglas C. Schmidt <schmidt at ics.uci.edu>
+   and Bruno Haible <bruno at clisp.org>.
 
-This file is part of GNU GPERF.
+   This file is part of GNU GPERF.
 
-GNU GPERF 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 1, or (at your option)
-any later version.
+   GNU GPERF 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 GPERF 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.
+   GNU GPERF 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 GPERF; see the file COPYING.  If not, write to the Free
-Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
-
-/* Define and implement a simple boolean array abstraction,
-   uses an Iteration Numbering implementation to save on initialization time. */
+   You should have received a copy of the GNU General Public License
+   along with this program; see the file COPYING.
+   If not, write to the Free Software Foundation, Inc.,
+   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
 
 #ifndef bool_array_h
 #define bool_array_h 1
 
-#include "trace.h"
-
-#ifdef LO_CAL
-/* If we are on a memory diet then we'll only make these use a limited
-   amount of storage space. */
-typedef unsigned short STORAGE_TYPE;
-#else
-typedef unsigned int STORAGE_TYPE;
-#endif
+/* A Bool_Array instance is a bit array of fixed size, optimized for being
+   filled sparsely and cleared frequently.  For example, when processing
+   tests/chill.gperf, the array will be:
+     - of size 15391,
+     - clear will be called 3509 times,
+     - set_bit will be called 300394 times.
+   With a conventional bit array implementation, clear would be too slow.
+   With a tree/hash based bit array implementation, set_bit would be slower. */
 
 class Bool_Array
 {
+public:
+  /* Initializes the bit array with room for SIZE bits, numbered from
+     0 to SIZE-1. */
+                        Bool_Array (unsigned int size);
+
+  /* Frees this object.  */
+                        ~Bool_Array ();
+
+  /* Resets all bits to zero.  */
+  void                  clear ();
+
+  /* Sets the specified bit to true.
+     Returns its previous value (false or true).  */
+  bool                  set_bit (unsigned int index);
+
 private:
-  static STORAGE_TYPE *storage_array;    /* Initialization of the index space. */
-  static STORAGE_TYPE  iteration_number; /* Keep track of the current iteration. */
-  static unsigned int  size;             /* Keep track of array size. */
+  /* Size of array.  */
+  unsigned int const    _size;
 
-public:
-       Bool_Array (void);
-      ~Bool_Array (void);
-  static void init (STORAGE_TYPE *buffer, unsigned int s);
-  static int  find (int hash_value);
-  static void reset (void);
+  /* Current iteration number.  Always nonzero.  Starts out as 1, and is
+     incremented each time clear() is called.  */
+  unsigned int          _iteration_number;
+
+  /* For each index, we store in storage_array[index] the iteration_number at
+     the time set_bit(index) was last called.  */
+  unsigned int * const  _storage_array;
 };
 
 #ifdef __OPTIMIZE__  /* efficiency hack! */
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/src/bool-array.icc
--- a/head/contrib/gperf/src/bool-array.icc	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/contrib/gperf/src/bool-array.icc	Tue Dec 06 20:26:16 2011 +0200
@@ -1,84 +1,77 @@
 /* Inline Functions for bool-array.{h,cc}.
 
-   Copyright (C) 1989-1998 Free Software Foundation, Inc.
-   written by Douglas C. Schmidt (schmidt at ics.uci.edu)
+   Copyright (C) 1989-1998, 2002 Free Software Foundation, Inc.
+   Written by Douglas C. Schmidt <schmidt at ics.uci.edu>
+   and Bruno Haible <bruno at clisp.org>.
 
-This file is part of GNU GPERF.
+   This file is part of GNU GPERF.
 
-GNU GPERF 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 1, or (at your option)
-any later version.
+   GNU GPERF 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 GPERF 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.
+   GNU GPERF 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 GPERF; see the file COPYING.  If not, write to the Free
-Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
+   You should have received a copy of the GNU General Public License
+   along with this program; see the file COPYING.
+   If not, write to the Free Software Foundation, Inc.,
+   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
 
 // This needs:
 //#include <stdio.h>
 //#include <string.h>
 //#include "options.h"
-//#include "trace.h"
 
+/* Initializes the bit array with room for SIZE bits, numbered from
+   0 to SIZE-1. */
 INLINE
-Bool_Array::Bool_Array (void)
+Bool_Array::Bool_Array (unsigned int size)
+  : _size (size),
+    _iteration_number (1),
+    _storage_array (new unsigned int [size])
 {
-  T (Trace t ("Bool_Array::Bool_Array");)
-  storage_array = 0;
-  iteration_number = size = 0;
+  memset (_storage_array, 0, size * sizeof (_storage_array[0]));
+  if (option[DEBUG])
+    fprintf (stderr, "\nbool array size = %d, total bytes = %d\n",
+             _size,
+             static_cast<unsigned int> (_size * sizeof (_storage_array[0])));
 }
 
-INLINE void
-Bool_Array::init (STORAGE_TYPE *buffer, unsigned int s)
+/* Sets the specified bit to true.
+   Returns its previous value (false or true).  */
+INLINE bool
+Bool_Array::set_bit (unsigned int index)
 {
-  T (Trace t ("Bool_Array::init");)
-  size             = s;
-  iteration_number = 1;
-  storage_array    = buffer;
-  memset (storage_array, 0, s * sizeof (*storage_array));
-  if (option[DEBUG])
-    fprintf (stderr, "\nbool array size = %d, total bytes = %d\n",
-             size, (unsigned int) (size * sizeof (*storage_array)));
-}
-
-INLINE int
-Bool_Array::find (int index)
-{
-  T (Trace t ("Bool_Array::find");)
-  if (storage_array[index] == iteration_number)
-    return 1;
+  if (_storage_array[index] == _iteration_number)
+    /* The bit was set since the last clear() call.  */
+    return true;
   else
     {
-      storage_array[index] = iteration_number;
-      return 0;
+      /* The last operation on this bit was clear().  Set it now.  */
+      _storage_array[index] = _iteration_number;
+      return false;
     }
 }
 
+/* Resets all bits to zero.  */
 INLINE void
-Bool_Array::reset (void)
+Bool_Array::clear ()
 {
-  T (Trace t ("Bool_Array::reset");)
   /* If we wrap around it's time to zero things out again!  However, this only
-     occurs once about every 2^31 or 2^15 iterations, so it should probably
-     never happen! */
+     occurs once about every 2^32 iterations, so it will not happen more
+     frequently than once per second.  */
 
-  if (++iteration_number == 0)
+  if (++_iteration_number == 0)
     {
+      _iteration_number = 1;
+      memset (_storage_array, 0, _size * sizeof (_storage_array[0]));
       if (option[DEBUG])
         {
-          fprintf (stderr, "(re-initializing bool_array)...");
-          fflush (stderr);
-        }
-      iteration_number = 1;
-      memset (storage_array, 0, size * sizeof (*storage_array));
-      if (option[DEBUG])
-        {
-          fprintf (stderr, "done\n");
+          fprintf (stderr, "(re-initialized bool_array)\n");
           fflush (stderr);
         }
     }
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/src/config.h.in
--- a/head/contrib/gperf/src/config.h.in	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/contrib/gperf/src/config.h.in	Tue Dec 06 20:26:16 2011 +0200
@@ -1,19 +1,20 @@
-/* config.h.in.  Generated automatically from configure.in by autoheader.  */
+/* config.h.in.  Generated from configure.ac by autoheader.  */
 
-/* Define if the C++ compiler supports "throw ()" declarations.  */
-#undef HAVE_THROW_DECL
+/* Define if the C++ compiler supports stack-allocated variable-size arrays.
+   */
+#undef HAVE_DYNAMIC_ARRAY
 
-/* Define if you have the getrlimit function.  */
-#undef HAVE_GETRLIMIT
+/* Define to the address where bug reports for this package should be sent. */
+#undef PACKAGE_BUGREPORT
 
-/* Define if you have the setrlimit function.  */
-#undef HAVE_SETRLIMIT
+/* Define to the full name of this package. */
+#undef PACKAGE_NAME
 
-/* Define if you have the <sys/resource.h> header file.  */
-#undef HAVE_SYS_RESOURCE_H
+/* Define to the full name and version of this package. */
+#undef PACKAGE_STRING
 
-/* Define if you have the <sys/time.h> header file.  */
-#undef HAVE_SYS_TIME_H
+/* Define to the one symbol short name of this package. */
+#undef PACKAGE_TARNAME
 
-/* Define if you have the <unistd.h> header file.  */
-#undef HAVE_UNISTD_H
+/* Define to the version of this package. */
+#undef PACKAGE_VERSION
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/src/config.h_vms
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/contrib/gperf/src/config.h_vms	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,20 @@
+/* config.h.in.  Generated from configure.ac by autoheader.  */
+
+/* Define if the C++ compiler supports stack-allocated variable-size arrays.
+   */
+#undef HAVE_DYNAMIC_ARRAY
+
+/* Define to the address where bug reports for this package should be sent. */
+#undef PACKAGE_BUGREPORT
+
+/* Define to the full name of this package. */
+#undef PACKAGE_NAME
+
+/* Define to the full name and version of this package. */
+#undef PACKAGE_STRING
+
+/* Define to the one symbol short name of this package. */
+#undef PACKAGE_TARNAME
+
+/* Define to the version of this package. */
+#undef PACKAGE_VERSION
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/src/configure
--- a/head/contrib/gperf/src/configure	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/contrib/gperf/src/configure	Tue Dec 06 20:26:16 2011 +0200
@@ -1,26 +1,662 @@
 #! /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.
+# Generated by GNU Autoconf 2.61.
 #
+# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001,
+# 2002, 2003, 2004, 2005, 2006 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=
+## --------------------- ##
+## M4sh Initialization.  ##
+## --------------------- ##
+
+# Be more Bourne compatible
+DUALCASE=1; export DUALCASE # for MKS sh
+if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
+  emulate sh
+  NULLCMD=:
+  # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
+  # is contrary to our usage.  Disable this feature.
+  alias -g '${1+"$@"}'='"$@"'
+  setopt NO_GLOB_SUBST
+else
+  case `(set -o) 2>/dev/null` in
+  *posix*) set -o posix ;;
+esac
+
+fi
+
+
+
+
+# PATH needs CR
+# Avoid depending upon Character Ranges.
+as_cr_letters='abcdefghijklmnopqrstuvwxyz'
+as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
+as_cr_Letters=$as_cr_letters$as_cr_LETTERS
+as_cr_digits='0123456789'
+as_cr_alnum=$as_cr_Letters$as_cr_digits
+
+# The user is always right.
+if test "${PATH_SEPARATOR+set}" != set; then
+  echo "#! /bin/sh" >conf$$.sh
+  echo  "exit 0"   >>conf$$.sh
+  chmod +x conf$$.sh
+  if (PATH="/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then
+    PATH_SEPARATOR=';'
+  else
+    PATH_SEPARATOR=:
+  fi
+  rm -f conf$$.sh
+fi
+
+# Support unset when possible.
+if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then
+  as_unset=unset
+else
+  as_unset=false
+fi
+
+
+# IFS
+# We need space, tab and new line, in precisely that order.  Quoting is
+# there to prevent editors from complaining about space-tab.
+# (If _AS_PATH_WALK were called with IFS unset, it would disable word
+# splitting by setting IFS to empty value.)
+as_nl='
+'
+IFS=" ""	$as_nl"
+
+# Find who we are.  Look in the path if we contain no directory separator.
+case $0 in
+  *[\\/]* ) as_myself=$0 ;;
+  *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+  test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break
+done
+IFS=$as_save_IFS
+
+     ;;
+esac
+# We did not find ourselves, most probably we were run as `sh COMMAND'
+# in which case we are not to be found in the path.
+if test "x$as_myself" = x; then
+  as_myself=$0
+fi
+if test ! -f "$as_myself"; then
+  echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2
+  { (exit 1); exit 1; }
+fi
+
+# Work around bugs in pre-3.0 UWIN ksh.
+for as_var in ENV MAIL MAILPATH
+do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var
+done
+PS1='$ '
+PS2='> '
+PS4='+ '
+
+# NLS nuisances.
+for as_var in \
+  LANG LANGUAGE LC_ADDRESS LC_ALL LC_COLLATE LC_CTYPE LC_IDENTIFICATION \
+  LC_MEASUREMENT LC_MESSAGES LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER \
+  LC_TELEPHONE LC_TIME
+do
+  if (set +x; test -z "`(eval $as_var=C; export $as_var) 2>&1`"); then
+    eval $as_var=C; export $as_var
+  else
+    ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var
+  fi
+done
+
+# Required to use basename.
+if expr a : '\(a\)' >/dev/null 2>&1 &&
+   test "X`expr 00001 : '.*\(...\)'`" = X001; then
+  as_expr=expr
+else
+  as_expr=false
+fi
+
+if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then
+  as_basename=basename
+else
+  as_basename=false
+fi
+
+
+# Name of the executable.
+as_me=`$as_basename -- "$0" ||
+$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
+	 X"$0" : 'X\(//\)$' \| \
+	 X"$0" : 'X\(/\)' \| . 2>/dev/null ||
+echo X/"$0" |
+    sed '/^.*\/\([^/][^/]*\)\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\/\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\/\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+
+# CDPATH.
+$as_unset CDPATH
+
+
+if test "x$CONFIG_SHELL" = x; then
+  if (eval ":") 2>/dev/null; then
+  as_have_required=yes
+else
+  as_have_required=no
+fi
+
+  if test $as_have_required = yes && 	 (eval ":
+(as_func_return () {
+  (exit \$1)
+}
+as_func_success () {
+  as_func_return 0
+}
+as_func_failure () {
+  as_func_return 1
+}
+as_func_ret_success () {
+  return 0
+}
+as_func_ret_failure () {
+  return 1
+}
+
+exitcode=0
+if as_func_success; then
+  :
+else
+  exitcode=1
+  echo as_func_success failed.
+fi
+
+if as_func_failure; then
+  exitcode=1
+  echo as_func_failure succeeded.
+fi
+
+if as_func_ret_success; then
+  :
+else
+  exitcode=1
+  echo as_func_ret_success failed.
+fi
+
+if as_func_ret_failure; then
+  exitcode=1
+  echo as_func_ret_failure succeeded.
+fi
+
+if ( set x; as_func_ret_success y && test x = \"\$1\" ); then
+  :
+else
+  exitcode=1
+  echo positional parameters were not saved.
+fi
+
+test \$exitcode = 0) || { (exit 1); exit 1; }
+
+(
+  as_lineno_1=\$LINENO
+  as_lineno_2=\$LINENO
+  test \"x\$as_lineno_1\" != \"x\$as_lineno_2\" &&
+  test \"x\`expr \$as_lineno_1 + 1\`\" = \"x\$as_lineno_2\") || { (exit 1); exit 1; }
+") 2> /dev/null; then
+  :
+else
+  as_candidate_shells=
+    as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+  case $as_dir in
+	 /*)
+	   for as_base in sh bash ksh sh5; do
+	     as_candidate_shells="$as_candidate_shells $as_dir/$as_base"
+	   done;;
+       esac
+done
+IFS=$as_save_IFS
+
+
+      for as_shell in $as_candidate_shells $SHELL; do
+	 # Try only shells that exist, to save several forks.
+	 if { test -f "$as_shell" || test -f "$as_shell.exe"; } &&
+		{ ("$as_shell") 2> /dev/null <<\_ASEOF
+if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
+  emulate sh
+  NULLCMD=:
+  # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
+  # is contrary to our usage.  Disable this feature.
+  alias -g '${1+"$@"}'='"$@"'
+  setopt NO_GLOB_SUBST
+else
+  case `(set -o) 2>/dev/null` in
+  *posix*) set -o posix ;;
+esac
+
+fi
+
+
+:
+_ASEOF
+}; then
+  CONFIG_SHELL=$as_shell
+	       as_have_required=yes
+	       if { "$as_shell" 2> /dev/null <<\_ASEOF
+if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
+  emulate sh
+  NULLCMD=:
+  # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
+  # is contrary to our usage.  Disable this feature.
+  alias -g '${1+"$@"}'='"$@"'
+  setopt NO_GLOB_SUBST
+else
+  case `(set -o) 2>/dev/null` in
+  *posix*) set -o posix ;;
+esac
+
+fi
+
+
+:
+(as_func_return () {
+  (exit $1)
+}
+as_func_success () {
+  as_func_return 0
+}
+as_func_failure () {
+  as_func_return 1
+}
+as_func_ret_success () {
+  return 0
+}
+as_func_ret_failure () {
+  return 1
+}
+
+exitcode=0
+if as_func_success; then
+  :
+else
+  exitcode=1
+  echo as_func_success failed.
+fi
+
+if as_func_failure; then
+  exitcode=1
+  echo as_func_failure succeeded.
+fi
+
+if as_func_ret_success; then
+  :
+else
+  exitcode=1
+  echo as_func_ret_success failed.
+fi
+
+if as_func_ret_failure; then
+  exitcode=1
+  echo as_func_ret_failure succeeded.
+fi
+
+if ( set x; as_func_ret_success y && test x = "$1" ); then
+  :
+else
+  exitcode=1
+  echo positional parameters were not saved.
+fi
+
+test $exitcode = 0) || { (exit 1); exit 1; }
+
+(
+  as_lineno_1=$LINENO
+  as_lineno_2=$LINENO
+  test "x$as_lineno_1" != "x$as_lineno_2" &&
+  test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2") || { (exit 1); exit 1; }
+
+_ASEOF
+}; then
+  break
+fi
+
+fi
+
+      done
+
+      if test "x$CONFIG_SHELL" != x; then
+  for as_var in BASH_ENV ENV
+        do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var
+        done
+        export CONFIG_SHELL
+        exec "$CONFIG_SHELL" "$as_myself" ${1+"$@"}
+fi
+
+
+    if test $as_have_required = no; then
+  echo This script requires a shell more modern than all the
+      echo shells that I found on your system.  Please install a
+      echo modern shell, or manually run the script under such a
+      echo shell if you do have one.
+      { (exit 1); exit 1; }
+fi
+
+
+fi
+
+fi
+
+
+
+(eval "as_func_return () {
+  (exit \$1)
+}
+as_func_success () {
+  as_func_return 0
+}
+as_func_failure () {
+  as_func_return 1
+}
+as_func_ret_success () {
+  return 0
+}
+as_func_ret_failure () {
+  return 1
+}
+
+exitcode=0
+if as_func_success; then
+  :
+else
+  exitcode=1
+  echo as_func_success failed.
+fi
+
+if as_func_failure; then
+  exitcode=1
+  echo as_func_failure succeeded.
+fi
+
+if as_func_ret_success; then
+  :
+else
+  exitcode=1
+  echo as_func_ret_success failed.
+fi
+
+if as_func_ret_failure; then
+  exitcode=1
+  echo as_func_ret_failure succeeded.
+fi
+
+if ( set x; as_func_ret_success y && test x = \"\$1\" ); then
+  :
+else
+  exitcode=1
+  echo positional parameters were not saved.
+fi
+
+test \$exitcode = 0") || {
+  echo No shell found that supports shell functions.
+  echo Please tell autoconf at gnu.org about your system,
+  echo including any error possibly output before this
+  echo message
+}
+
+
+
+  as_lineno_1=$LINENO
+  as_lineno_2=$LINENO
+  test "x$as_lineno_1" != "x$as_lineno_2" &&
+  test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2" || {
+
+  # Create $as_me.lineno as a copy of $as_myself, but with $LINENO
+  # uniformly replaced by the line number.  The first 'sed' inserts a
+  # line-number line after each line using $LINENO; the second 'sed'
+  # does the real work.  The second script uses 'N' to pair each
+  # line-number line with the line containing $LINENO, and appends
+  # trailing '-' during substitution so that $LINENO is not a special
+  # case at line end.
+  # (Raja R Harinath suggested sed '=', and Paul Eggert wrote the
+  # scripts with optimization help from Paolo Bonzini.  Blame Lee
+  # E. McMahon (1931-1989) for sed's syntax.  :-)
+  sed -n '
+    p
+    /[$]LINENO/=
+  ' <$as_myself |
+    sed '
+      s/[$]LINENO.*/&-/
+      t lineno
+      b
+      :lineno
+      N
+      :loop
+      s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/
+      t loop
+      s/-\n.*//
+    ' >$as_me.lineno &&
+  chmod +x "$as_me.lineno" ||
+    { echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2
+   { (exit 1); exit 1; }; }
+
+  # Don't try to exec as it changes $[0], causing all sort of problems
+  # (the dirname of $[0] is not the place where we might find the
+  # original and so on.  Autoconf is especially sensitive to this).
+  . "./$as_me.lineno"
+  # Exit status is that of the last command.
+  exit
+}
+
+
+if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then
+  as_dirname=dirname
+else
+  as_dirname=false
+fi
+
+ECHO_C= ECHO_N= ECHO_T=
+case `echo -n x` in
+-n*)
+  case `echo 'x\c'` in
+  *c*) ECHO_T='	';;	# ECHO_T is single tab character.
+  *)   ECHO_C='\c';;
+  esac;;
+*)
+  ECHO_N='-n';;
+esac
+
+if expr a : '\(a\)' >/dev/null 2>&1 &&
+   test "X`expr 00001 : '.*\(...\)'`" = X001; then
+  as_expr=expr
+else
+  as_expr=false
+fi
+
+rm -f conf$$ conf$$.exe conf$$.file
+if test -d conf$$.dir; then
+  rm -f conf$$.dir/conf$$.file
+else
+  rm -f conf$$.dir
+  mkdir conf$$.dir
+fi
+echo >conf$$.file
+if ln -s conf$$.file conf$$ 2>/dev/null; then
+  as_ln_s='ln -s'
+  # ... but there are two gotchas:
+  # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail.
+  # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable.
+  # In both cases, we have to default to `cp -p'.
+  ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe ||
+    as_ln_s='cp -p'
+elif ln conf$$.file conf$$ 2>/dev/null; then
+  as_ln_s=ln
+else
+  as_ln_s='cp -p'
+fi
+rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file
+rmdir conf$$.dir 2>/dev/null
+
+if mkdir -p . 2>/dev/null; then
+  as_mkdir_p=:
+else
+  test -d ./-p && rmdir ./-p
+  as_mkdir_p=false
+fi
+
+if test -x / >/dev/null 2>&1; then
+  as_test_x='test -x'
+else
+  if ls -dL / >/dev/null 2>&1; then
+    as_ls_L_option=L
+  else
+    as_ls_L_option=
+  fi
+  as_test_x='
+    eval sh -c '\''
+      if test -d "$1"; then
+        test -d "$1/.";
+      else
+	case $1 in
+        -*)set "./$1";;
+	esac;
+	case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in
+	???[sx]*):;;*)false;;esac;fi
+    '\'' sh
+  '
+fi
+as_executable_p=$as_test_x
+
+# Sed expression to map a string onto a valid CPP name.
+as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
+
+# Sed expression to map a string onto a valid variable name.
+as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'"
+
+
+
+exec 7<&0 </dev/null 6>&1
+
+# Name of the host.
+# hostname on some systems (SVR3.2, Linux) returns a bogus exit status,
+# so uname gets run too.
+ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q`
+
+#
+# Initializations.
+#
 ac_default_prefix=/usr/local
-# Any additions from configure.in:
+ac_clean_files=
+ac_config_libobj_dir=.
+LIBOBJS=
+cross_compiling=no
+subdirs=
+MFLAGS=
+MAKEFLAGS=
+SHELL=${CONFIG_SHELL-/bin/sh}
+
+# Identity of this package.
+PACKAGE_NAME=
+PACKAGE_TARNAME=
+PACKAGE_VERSION=
+PACKAGE_STRING=
+PACKAGE_BUGREPORT=
+
+ac_unique_file="main.cc"
+ac_subst_vars='SHELL
+PATH_SEPARATOR
+PACKAGE_NAME
+PACKAGE_TARNAME
+PACKAGE_VERSION
+PACKAGE_STRING
+PACKAGE_BUGREPORT
+exec_prefix
+prefix
+program_transform_name
+bindir
+sbindir
+libexecdir
+datarootdir
+datadir
+sysconfdir
+sharedstatedir
+localstatedir
+includedir
+oldincludedir
+docdir
+infodir
+htmldir
+dvidir
+pdfdir
+psdir
+libdir
+localedir
+mandir
+DEFS
+ECHO_C
+ECHO_N
+ECHO_T
+LIBS
+build_alias
+host_alias
+target_alias
+SET_MAKE
+CC
+CFLAGS
+LDFLAGS
+CPPFLAGS
+ac_ct_CC
+EXEEXT
+OBJEXT
+CPP
+CXX
+CXXFLAGS
+ac_ct_CXX
+CXXCPP
+INSTALL
+INSTALL_PROGRAM
+INSTALL_DATA
+GPERF_LIBM
+LIBOBJS
+LTLIBOBJS'
+ac_subst_files=''
+      ac_precious_vars='build_alias
+host_alias
+target_alias
+CC
+CFLAGS
+LDFLAGS
+LIBS
+CPPFLAGS
+CPP
+CXX
+CXXFLAGS
+CCC
+CXXCPP'
+
 
 # Initialize some variables set by options.
+ac_init_help=
+ac_init_version=false
 # The variables have the same names as the options, with
 # dashes changed to underlines.
-build=NONE
-cache_file=./config.cache
+cache_file=/dev/null
 exec_prefix=NONE
-host=NONE
 no_create=
-nonopt=NONE
 no_recursion=
 prefix=NONE
 program_prefix=NONE
@@ -29,94 +665,117 @@
 silent=
 site=
 srcdir=
-target=NONE
 verbose=
 x_includes=NONE
 x_libraries=NONE
+
+# Installation directory options.
+# These are left unexpanded so users can "make install exec_prefix=/foo"
+# and all the variables that are supposed to be based on exec_prefix
+# by default will actually change.
+# Use braces instead of parens because sh, perl, etc. also accept them.
+# (The list follows the same order as the GNU Coding Standards.)
 bindir='${exec_prefix}/bin'
 sbindir='${exec_prefix}/sbin'
 libexecdir='${exec_prefix}/libexec'
-datadir='${prefix}/share'
+datarootdir='${prefix}/share'
+datadir='${datarootdir}'
 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
+docdir='${datarootdir}/doc/${PACKAGE}'
+infodir='${datarootdir}/info'
+htmldir='${docdir}'
+dvidir='${docdir}'
+pdfdir='${docdir}'
+psdir='${docdir}'
+libdir='${exec_prefix}/lib'
+localedir='${datarootdir}/locale'
+mandir='${datarootdir}/man'
 
 ac_prev=
+ac_dashdash=
 for ac_option
 do
-
   # If the previous option needs an argument, assign it.
   if test -n "$ac_prev"; then
-    eval "$ac_prev=\$ac_option"
+    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= ;;
+  case $ac_option in
+  *=*)	ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;;
+  *)	ac_optarg=yes ;;
   esac
 
   # Accept the important Cygnus configure options, so we can diagnose typos.
 
-  case "$ac_option" in
+  case $ac_dashdash$ac_option in
+  --)
+    ac_dashdash=yes ;;
 
   -bindir | --bindir | --bindi | --bind | --bin | --bi)
     ac_prev=bindir ;;
   -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*)
-    bindir="$ac_optarg" ;;
+    bindir=$ac_optarg ;;
 
   -build | --build | --buil | --bui | --bu)
-    ac_prev=build ;;
+    ac_prev=build_alias ;;
   -build=* | --build=* | --buil=* | --bui=* | --bu=*)
-    build="$ac_optarg" ;;
+    build_alias=$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)
+    cache_file=$ac_optarg ;;
+
+  --config-cache | -C)
+    cache_file=config.cache ;;
+
+  -datadir | --datadir | --datadi | --datad)
     ac_prev=datadir ;;
-  -datadir=* | --datadir=* | --datadi=* | --datad=* | --data=* | --dat=* \
-  | --da=*)
-    datadir="$ac_optarg" ;;
+  -datadir=* | --datadir=* | --datadi=* | --datad=*)
+    datadir=$ac_optarg ;;
+
+  -datarootdir | --datarootdir | --datarootdi | --datarootd | --dataroot \
+  | --dataroo | --dataro | --datar)
+    ac_prev=datarootdir ;;
+  -datarootdir=* | --datarootdir=* | --datarootdi=* | --datarootd=* \
+  | --dataroot=* | --dataroo=* | --dataro=* | --datar=*)
+    datarootdir=$ac_optarg ;;
 
   -disable-* | --disable-*)
-    ac_feature=`echo $ac_option|sed -e 's/-*disable-//'`
+    ac_feature=`expr "x$ac_option" : 'x-*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" ;;
+    expr "x$ac_feature" : ".*[^-._$as_cr_alnum]" >/dev/null &&
+      { echo "$as_me: error: invalid feature name: $ac_feature" >&2
+   { (exit 1); exit 1; }; }
+    ac_feature=`echo $ac_feature | sed 's/[-.]/_/g'`
+    eval enable_$ac_feature=no ;;
+
+  -docdir | --docdir | --docdi | --doc | --do)
+    ac_prev=docdir ;;
+  -docdir=* | --docdir=* | --docdi=* | --doc=* | --do=*)
+    docdir=$ac_optarg ;;
+
+  -dvidir | --dvidir | --dvidi | --dvid | --dvi | --dv)
+    ac_prev=dvidir ;;
+  -dvidir=* | --dvidir=* | --dvidi=* | --dvid=* | --dvi=* | --dv=*)
+    dvidir=$ac_optarg ;;
 
   -enable-* | --enable-*)
-    ac_feature=`echo $ac_option|sed -e 's/-*enable-//' -e 's/=.*//'`
+    ac_feature=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'`
     # 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'" ;;
+    expr "x$ac_feature" : ".*[^-._$as_cr_alnum]" >/dev/null &&
+      { echo "$as_me: error: invalid feature name: $ac_feature" >&2
+   { (exit 1); exit 1; }; }
+    ac_feature=`echo $ac_feature | sed 's/[-.]/_/g'`
+    eval enable_$ac_feature=\$ac_optarg ;;
 
   -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \
   | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \
@@ -125,116 +784,77 @@
   -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \
   | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \
   | --exec=* | --exe=* | --ex=*)
-    exec_prefix="$ac_optarg" ;;
+    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 ;;
+  -help | --help | --hel | --he | -h)
+    ac_init_help=long ;;
+  -help=r* | --help=r* | --hel=r* | --he=r* | -hr*)
+    ac_init_help=recursive ;;
+  -help=s* | --help=s* | --hel=s* | --he=s* | -hs*)
+    ac_init_help=short ;;
 
   -host | --host | --hos | --ho)
-    ac_prev=host ;;
+    ac_prev=host_alias ;;
   -host=* | --host=* | --hos=* | --ho=*)
-    host="$ac_optarg" ;;
+    host_alias=$ac_optarg ;;
+
+  -htmldir | --htmldir | --htmldi | --htmld | --html | --htm | --ht)
+    ac_prev=htmldir ;;
+  -htmldir=* | --htmldir=* | --htmldi=* | --htmld=* | --html=* | --htm=* \
+  | --ht=*)
+    htmldir=$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" ;;
+    includedir=$ac_optarg ;;
 
   -infodir | --infodir | --infodi | --infod | --info | --inf)
     ac_prev=infodir ;;
   -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*)
-    infodir="$ac_optarg" ;;
+    infodir=$ac_optarg ;;
 
   -libdir | --libdir | --libdi | --libd)
     ac_prev=libdir ;;
   -libdir=* | --libdir=* | --libdi=* | --libd=*)
-    libdir="$ac_optarg" ;;
+    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" ;;
+    libexecdir=$ac_optarg ;;
+
+  -localedir | --localedir | --localedi | --localed | --locale)
+    ac_prev=localedir ;;
+  -localedir=* | --localedir=* | --localedi=* | --localed=* | --locale=*)
+    localedir=$ac_optarg ;;
 
   -localstatedir | --localstatedir | --localstatedi | --localstated \
-  | --localstate | --localstat | --localsta | --localst \
-  | --locals | --local | --loca | --loc | --lo)
+  | --localstate | --localstat | --localsta | --localst | --locals)
     ac_prev=localstatedir ;;
   -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \
-  | --localstate=* | --localstat=* | --localsta=* | --localst=* \
-  | --locals=* | --local=* | --loca=* | --loc=* | --lo=*)
-    localstatedir="$ac_optarg" ;;
+  | --localstate=* | --localstat=* | --localsta=* | --localst=* | --locals=*)
+    localstatedir=$ac_optarg ;;
 
   -mandir | --mandir | --mandi | --mand | --man | --ma | --m)
     ac_prev=mandir ;;
   -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*)
-    mandir="$ac_optarg" ;;
+    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-cr | --no-c | -n)
     no_create=yes ;;
 
   -no-recursion | --no-recursion | --no-recursio | --no-recursi \
@@ -248,26 +868,26 @@
   -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \
   | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \
   | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*)
-    oldincludedir="$ac_optarg" ;;
+    oldincludedir=$ac_optarg ;;
 
   -prefix | --prefix | --prefi | --pref | --pre | --pr | --p)
     ac_prev=prefix ;;
   -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*)
-    prefix="$ac_optarg" ;;
+    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_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_suffix=$ac_optarg ;;
 
   -program-transform-name | --program-transform-name \
   | --program-transform-nam | --program-transform-na \
@@ -284,7 +904,17 @@
   | --program-transfo=* | --program-transf=* \
   | --program-trans=* | --program-tran=* \
   | --progr-tra=* | --program-tr=* | --program-t=*)
-    program_transform_name="$ac_optarg" ;;
+    program_transform_name=$ac_optarg ;;
+
+  -pdfdir | --pdfdir | --pdfdi | --pdfd | --pdf | --pd)
+    ac_prev=pdfdir ;;
+  -pdfdir=* | --pdfdir=* | --pdfdi=* | --pdfd=* | --pdf=* | --pd=*)
+    pdfdir=$ac_optarg ;;
+
+  -psdir | --psdir | --psdi | --psd | --ps)
+    ac_prev=psdir ;;
+  -psdir=* | --psdir=* | --psdi=* | --psd=* | --ps=*)
+    psdir=$ac_optarg ;;
 
   -q | -quiet | --quiet | --quie | --qui | --qu | --q \
   | -silent | --silent | --silen | --sile | --sil)
@@ -294,7 +924,7 @@
     ac_prev=sbindir ;;
   -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \
   | --sbi=* | --sb=*)
-    sbindir="$ac_optarg" ;;
+    sbindir=$ac_optarg ;;
 
   -sharedstatedir | --sharedstatedir | --sharedstatedi \
   | --sharedstated | --sharedstate | --sharedstat | --sharedsta \
@@ -305,58 +935,53 @@
   | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \
   | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \
   | --sha=* | --sh=*)
-    sharedstatedir="$ac_optarg" ;;
+    sharedstatedir=$ac_optarg ;;
 
   -site | --site | --sit)
     ac_prev=site ;;
   -site=* | --site=* | --sit=*)
-    site="$ac_optarg" ;;
+    site=$ac_optarg ;;
 
   -srcdir | --srcdir | --srcdi | --srcd | --src | --sr)
     ac_prev=srcdir ;;
   -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*)
-    srcdir="$ac_optarg" ;;
+    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" ;;
+    sysconfdir=$ac_optarg ;;
 
   -target | --target | --targe | --targ | --tar | --ta | --t)
-    ac_prev=target ;;
+    ac_prev=target_alias ;;
   -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*)
-    target="$ac_optarg" ;;
+    target_alias=$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 ;;
+  -version | --version | --versio | --versi | --vers | -V)
+    ac_init_version=: ;;
 
   -with-* | --with-*)
-    ac_package=`echo $ac_option|sed -e 's/-*with-//' -e 's/=.*//'`
+    ac_package=`expr "x$ac_option" : 'x-*with-\([^=]*\)'`
     # 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'" ;;
+    expr "x$ac_package" : ".*[^-._$as_cr_alnum]" >/dev/null &&
+      { echo "$as_me: error: invalid package name: $ac_package" >&2
+   { (exit 1); exit 1; }; }
+    ac_package=`echo $ac_package | sed 's/[-.]/_/g'`
+    eval with_$ac_package=\$ac_optarg ;;
 
   -without-* | --without-*)
-    ac_package=`echo $ac_option|sed -e 's/-*without-//'`
+    ac_package=`expr "x$ac_option" : 'x-*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" ;;
+    expr "x$ac_package" : ".*[^-._$as_cr_alnum]" >/dev/null &&
+      { echo "$as_me: error: invalid package name: $ac_package" >&2
+   { (exit 1); exit 1; }; }
+    ac_package=`echo $ac_package | sed 's/[-.]/_/g'`
+    eval with_$ac_package=no ;;
 
   --x)
     # Obsolete; use --with-x.
@@ -367,396 +992,1478 @@
     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_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; }
+    x_libraries=$ac_optarg ;;
+
+  -*) { echo "$as_me: error: unrecognized option: $ac_option
+Try \`$0 --help' for more information." >&2
+   { (exit 1); exit 1; }; }
     ;;
 
+  *=*)
+    ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='`
+    # Reject names that are not valid shell variable names.
+    expr "x$ac_envvar" : ".*[^_$as_cr_alnum]" >/dev/null &&
+      { echo "$as_me: error: invalid variable name: $ac_envvar" >&2
+   { (exit 1); exit 1; }; }
+    eval $ac_envvar=\$ac_optarg
+    export $ac_envvar ;;
+
   *)
-    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"
+    # FIXME: should be removed in autoconf 3.0.
+    echo "$as_me: WARNING: you should use --build, --host, --target" >&2
+    expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null &&
+      echo "$as_me: WARNING: invalid host type: $ac_option" >&2
+    : ${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$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; }
+  ac_option=--`echo $ac_prev | sed 's/_/-/g'`
+  { echo "$as_me: error: missing argument to $ac_option" >&2
+   { (exit 1); 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
+# Be sure to have absolute directory names.
+for ac_var in	exec_prefix prefix bindir sbindir libexecdir datarootdir \
+		datadir sysconfdir sharedstatedir localstatedir includedir \
+		oldincludedir docdir infodir htmldir dvidir pdfdir psdir \
+		libdir localedir mandir
+do
+  eval ac_val=\$$ac_var
+  case $ac_val in
+    [\\/$]* | ?:[\\/]* )  continue;;
+    NONE | '' ) case $ac_var in *prefix ) continue;; esac;;
+  esac
+  { echo "$as_me: error: expected an absolute directory name for --$ac_var: $ac_val" >&2
+   { (exit 1); exit 1; }; }
+done
+
+# There might be people who depend on the old broken behavior: `$host'
+# used to hold the argument of --host etc.
+# FIXME: To remove some day.
+build=$build_alias
+host=$host_alias
+target=$target_alias
+
+# FIXME: To remove some day.
+if test "x$host_alias" != x; then
+  if test "x$build_alias" = x; then
+    cross_compiling=maybe
+    echo "$as_me: WARNING: If you wanted to set the --build type, don't use --host.
+    If a cross compiler is detected then cross compile mode will be used." >&2
+  elif test "x$build_alias" != "x$host_alias"; then
+    cross_compiling=yes
+  fi
 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=gen-perf.cc
+
+ac_tool_prefix=
+test -n "$host_alias" && ac_tool_prefix=$host_alias-
+
+test "$silent" = yes && exec 6>/dev/null
+
+
+ac_pwd=`pwd` && test -n "$ac_pwd" &&
+ac_ls_di=`ls -di .` &&
+ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` ||
+  { echo "$as_me: error: Working directory cannot be determined" >&2
+   { (exit 1); exit 1; }; }
+test "X$ac_ls_di" = "X$ac_pwd_ls_di" ||
+  { echo "$as_me: error: pwd does not report name of working directory" >&2
+   { (exit 1); exit 1; }; }
+
 
 # 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=.
+  # Try the directory containing this script, then the parent directory.
+  ac_confdir=`$as_dirname -- "$0" ||
+$as_expr X"$0" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+	 X"$0" : 'X\(//\)[^/]' \| \
+	 X"$0" : 'X\(//\)$' \| \
+	 X"$0" : 'X\(/\)' \| . 2>/dev/null ||
+echo X"$0" |
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)[^/].*/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
   srcdir=$ac_confdir
-  if test ! -r $srcdir/$ac_unique_file; then
+  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
+if test ! -r "$srcdir/$ac_unique_file"; then
+  test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .."
+  { echo "$as_me: error: cannot find sources ($ac_unique_file) in $srcdir" >&2
+   { (exit 1); exit 1; }; }
 fi
-srcdir=`echo "${srcdir}" | sed 's%\([^/]\)/*$%\1%'`
-
+ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work"
+ac_abs_confdir=`(
+	cd "$srcdir" && test -r "./$ac_unique_file" || { echo "$as_me: error: $ac_msg" >&2
+   { (exit 1); exit 1; }; }
+	pwd)`
+# When building in place, set srcdir=.
+if test "$ac_abs_confdir" = "$ac_pwd"; then
+  srcdir=.
+fi
+# Remove unnecessary trailing slashes from srcdir.
+# Double slashes in file names in object file debugging info
+# mess up M-x gdb in Emacs.
+case $srcdir in
+*/) srcdir=`expr "X$srcdir" : 'X\(.*[^/]\)' \| "X$srcdir" : 'X\(.*\)'`;;
+esac
+for ac_var in $ac_precious_vars; do
+  eval ac_env_${ac_var}_set=\${${ac_var}+set}
+  eval ac_env_${ac_var}_value=\$${ac_var}
+  eval ac_cv_env_${ac_var}_set=\${${ac_var}+set}
+  eval ac_cv_env_${ac_var}_value=\$${ac_var}
+done
+
+#
+# Report the --help message.
+#
+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 this package to adapt to many kinds of systems.
+
+Usage: $0 [OPTION]... [VAR=VALUE]...
+
+To assign environment variables (e.g., CC, CFLAGS...), specify them as
+VAR=VALUE.  See below for descriptions of some of the useful variables.
+
+Defaults for the options are specified in brackets.
+
+Configuration:
+  -h, --help              display this help and exit
+      --help=short        display options specific to this package
+      --help=recursive    display the short help of all the included packages
+  -V, --version           display version information and exit
+  -q, --quiet, --silent   do not print \`checking...' messages
+      --cache-file=FILE   cache test results in FILE [disabled]
+  -C, --config-cache      alias for \`--cache-file=config.cache'
+  -n, --no-create         do not create output files
+      --srcdir=DIR        find the sources in DIR [configure dir or \`..']
+
+Installation directories:
+  --prefix=PREFIX         install architecture-independent files in PREFIX
+			  [$ac_default_prefix]
+  --exec-prefix=EPREFIX   install architecture-dependent files in EPREFIX
+			  [PREFIX]
+
+By default, \`make install' will install all the files in
+\`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc.  You can specify
+an installation prefix other than \`$ac_default_prefix' using \`--prefix',
+for instance \`--prefix=\$HOME'.
+
+For better control, use the options below.
+
+Fine tuning of the installation directories:
+  --bindir=DIR           user executables [EPREFIX/bin]
+  --sbindir=DIR          system admin executables [EPREFIX/sbin]
+  --libexecdir=DIR       program executables [EPREFIX/libexec]
+  --sysconfdir=DIR       read-only single-machine data [PREFIX/etc]
+  --sharedstatedir=DIR   modifiable architecture-independent data [PREFIX/com]
+  --localstatedir=DIR    modifiable single-machine data [PREFIX/var]
+  --libdir=DIR           object code libraries [EPREFIX/lib]
+  --includedir=DIR       C header files [PREFIX/include]
+  --oldincludedir=DIR    C header files for non-gcc [/usr/include]
+  --datarootdir=DIR      read-only arch.-independent data root [PREFIX/share]
+  --datadir=DIR          read-only architecture-independent data [DATAROOTDIR]
+  --infodir=DIR          info documentation [DATAROOTDIR/info]
+  --localedir=DIR        locale-dependent data [DATAROOTDIR/locale]
+  --mandir=DIR           man documentation [DATAROOTDIR/man]
+  --docdir=DIR           documentation root [DATAROOTDIR/doc/PACKAGE]
+  --htmldir=DIR          html documentation [DOCDIR]
+  --dvidir=DIR           dvi documentation [DOCDIR]
+  --pdfdir=DIR           pdf documentation [DOCDIR]
+  --psdir=DIR            ps documentation [DOCDIR]
+_ACEOF
+
+  cat <<\_ACEOF
+_ACEOF
+fi
+
+if test -n "$ac_init_help"; then
+
+  cat <<\_ACEOF
+
+Some influential environment variables:
+  CC          C compiler command
+  CFLAGS      C compiler flags
+  LDFLAGS     linker flags, e.g. -L<lib dir> if you have libraries in a
+              nonstandard directory <lib dir>
+  LIBS        libraries to pass to the linker, e.g. -l<library>
+  CPPFLAGS    C/C++/Objective C preprocessor flags, e.g. -I<include dir> if
+              you have headers in a nonstandard directory <include dir>
+  CPP         C preprocessor
+  CXX         C++ compiler command
+  CXXFLAGS    C++ compiler flags
+  CXXCPP      C++ preprocessor
+
+Use these variables to override the choices made by `configure' or to help
+it to find libraries and programs with nonstandard names/locations.
+
+_ACEOF
+ac_status=$?
+fi
+
+if test "$ac_init_help" = "recursive"; then
+  # If there are subdirs, report their specific --help.
+  for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue
+    test -d "$ac_dir" || continue
+    ac_builddir=.
+
+case "$ac_dir" in
+.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;
+*)
+  ac_dir_suffix=/`echo "$ac_dir" | sed 's,^\.[\\/],,'`
+  # A ".." for each directory in $ac_dir_suffix.
+  ac_top_builddir_sub=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,/..,g;s,/,,'`
+  case $ac_top_builddir_sub in
+  "") ac_top_builddir_sub=. ac_top_build_prefix= ;;
+  *)  ac_top_build_prefix=$ac_top_builddir_sub/ ;;
+  esac ;;
+esac
+ac_abs_top_builddir=$ac_pwd
+ac_abs_builddir=$ac_pwd$ac_dir_suffix
+# for backward compatibility:
+ac_top_builddir=$ac_top_build_prefix
+
+case $srcdir in
+  .)  # We are building in place.
+    ac_srcdir=.
+    ac_top_srcdir=$ac_top_builddir_sub
+    ac_abs_top_srcdir=$ac_pwd ;;
+  [\\/]* | ?:[\\/]* )  # Absolute name.
+    ac_srcdir=$srcdir$ac_dir_suffix;
+    ac_top_srcdir=$srcdir
+    ac_abs_top_srcdir=$srcdir ;;
+  *) # Relative name.
+    ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix
+    ac_top_srcdir=$ac_top_build_prefix$srcdir
+    ac_abs_top_srcdir=$ac_pwd/$srcdir ;;
+esac
+ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix
+
+    cd "$ac_dir" || { ac_status=$?; continue; }
+    # Check for guested configure.
+    if test -f "$ac_srcdir/configure.gnu"; then
+      echo &&
+      $SHELL "$ac_srcdir/configure.gnu" --help=recursive
+    elif test -f "$ac_srcdir/configure"; then
+      echo &&
+      $SHELL "$ac_srcdir/configure" --help=recursive
+    else
+      echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2
+    fi || ac_status=$?
+    cd "$ac_pwd" || { ac_status=$?; break; }
+  done
+fi
+
+test -n "$ac_init_help" && exit $ac_status
+if $ac_init_version; then
+  cat <<\_ACEOF
+configure
+generated by GNU Autoconf 2.61
+
+Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001,
+2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc.
+This configure script is free software; the Free Software Foundation
+gives unlimited permission to copy, distribute and modify it.
+_ACEOF
+  exit
+fi
+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 $as_me, which was
+generated by GNU Autoconf 2.61.  Invocation command line was
+
+  $ $0 $@
+
+_ACEOF
+exec 5>>config.log
+{
+cat <<_ASUNAME
+## --------- ##
+## Platform. ##
+## --------- ##
+
+hostname = `(hostname || uname -n) 2>/dev/null | sed 1q`
+uname -m = `(uname -m) 2>/dev/null || echo unknown`
+uname -r = `(uname -r) 2>/dev/null || echo unknown`
+uname -s = `(uname -s) 2>/dev/null || echo unknown`
+uname -v = `(uname -v) 2>/dev/null || echo unknown`
+
+/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown`
+/bin/uname -X     = `(/bin/uname -X) 2>/dev/null     || echo unknown`
+
+/bin/arch              = `(/bin/arch) 2>/dev/null              || echo unknown`
+/usr/bin/arch -k       = `(/usr/bin/arch -k) 2>/dev/null       || echo unknown`
+/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown`
+/usr/bin/hostinfo      = `(/usr/bin/hostinfo) 2>/dev/null      || echo unknown`
+/bin/machine           = `(/bin/machine) 2>/dev/null           || echo unknown`
+/usr/bin/oslevel       = `(/usr/bin/oslevel) 2>/dev/null       || echo unknown`
+/bin/universe          = `(/bin/universe) 2>/dev/null          || echo unknown`
+
+_ASUNAME
+
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+  echo "PATH: $as_dir"
+done
+IFS=$as_save_IFS
+
+} >&5
+
+cat >&5 <<_ACEOF
+
+
+## ----------- ##
+## Core tests. ##
+## ----------- ##
+
+_ACEOF
+
+
+# Keep a trace of the command line.
+# Strip out --no-create and --no-recursion so they do not pile up.
+# Strip out --silent because we don't want to record it for future runs.
+# Also quote any args containing shell meta-characters.
+# Make two passes to allow for proper duplicate-argument suppression.
+ac_configure_args=
+ac_configure_args0=
+ac_configure_args1=
+ac_must_keep_next=false
+for ac_pass in 1 2
+do
+  for ac_arg
+  do
+    case $ac_arg in
+    -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;;
+    -q | -quiet | --quiet | --quie | --qui | --qu | --q \
+    | -silent | --silent | --silen | --sile | --sil)
+      continue ;;
+    *\'*)
+      ac_arg=`echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;;
+    esac
+    case $ac_pass in
+    1) ac_configure_args0="$ac_configure_args0 '$ac_arg'" ;;
+    2)
+      ac_configure_args1="$ac_configure_args1 '$ac_arg'"
+      if test $ac_must_keep_next = true; then
+	ac_must_keep_next=false # Got value, back to normal.
+      else
+	case $ac_arg in
+	  *=* | --config-cache | -C | -disable-* | --disable-* \
+	  | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \
+	  | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \
+	  | -with-* | --with-* | -without-* | --without-* | --x)
+	    case "$ac_configure_args0 " in
+	      "$ac_configure_args1"*" '$ac_arg' "* ) continue ;;
+	    esac
+	    ;;
+	  -* ) ac_must_keep_next=true ;;
+	esac
+      fi
+      ac_configure_args="$ac_configure_args '$ac_arg'"
+      ;;
+    esac
+  done
+done
+$as_unset ac_configure_args0 || test "${ac_configure_args0+set}" != set || { ac_configure_args0=; export ac_configure_args0; }
+$as_unset ac_configure_args1 || test "${ac_configure_args1+set}" != set || { ac_configure_args1=; export ac_configure_args1; }
+
+# When interrupted or exit'd, cleanup temporary files, and complete
+# config.log.  We remove comments because anyway the quotes in there
+# would cause problems or look ugly.
+# WARNING: Use '\'' to represent an apostrophe within the trap.
+# WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug.
+trap 'exit_status=$?
+  # Save into config.log some information that might help in debugging.
+  {
+    echo
+
+    cat <<\_ASBOX
+## ---------------- ##
+## Cache variables. ##
+## ---------------- ##
+_ASBOX
+    echo
+    # The following way of writing the cache mishandles newlines in values,
+(
+  for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do
+    eval ac_val=\$$ac_var
+    case $ac_val in #(
+    *${as_nl}*)
+      case $ac_var in #(
+      *_cv_*) { echo "$as_me:$LINENO: WARNING: Cache variable $ac_var contains a newline." >&5
+echo "$as_me: WARNING: Cache variable $ac_var contains a newline." >&2;} ;;
+      esac
+      case $ac_var in #(
+      _ | IFS | as_nl) ;; #(
+      *) $as_unset $ac_var ;;
+      esac ;;
+    esac
+  done
+  (set) 2>&1 |
+    case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #(
+    *${as_nl}ac_space=\ *)
+      sed -n \
+	"s/'\''/'\''\\\\'\'''\''/g;
+	  s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p"
+      ;; #(
+    *)
+      sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p"
+      ;;
+    esac |
+    sort
+)
+    echo
+
+    cat <<\_ASBOX
+## ----------------- ##
+## Output variables. ##
+## ----------------- ##
+_ASBOX
+    echo
+    for ac_var in $ac_subst_vars
+    do
+      eval ac_val=\$$ac_var
+      case $ac_val in
+      *\'\''*) ac_val=`echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;;
+      esac
+      echo "$ac_var='\''$ac_val'\''"
+    done | sort
+    echo
+
+    if test -n "$ac_subst_files"; then
+      cat <<\_ASBOX
+## ------------------- ##
+## File substitutions. ##
+## ------------------- ##
+_ASBOX
+      echo
+      for ac_var in $ac_subst_files
+      do
+	eval ac_val=\$$ac_var
+	case $ac_val in
+	*\'\''*) ac_val=`echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;;
+	esac
+	echo "$ac_var='\''$ac_val'\''"
+      done | sort
+      echo
+    fi
+
+    if test -s confdefs.h; then
+      cat <<\_ASBOX
+## ----------- ##
+## confdefs.h. ##
+## ----------- ##
+_ASBOX
+      echo
+      cat confdefs.h
+      echo
+    fi
+    test "$ac_signal" != 0 &&
+      echo "$as_me: caught signal $ac_signal"
+    echo "$as_me: exit $exit_status"
+  } >&5
+  rm -f core *.core core.conftest.* &&
+    rm -f -r conftest* confdefs* conf$$* $ac_clean_files &&
+    exit $exit_status
+' 0
+for ac_signal in 1 2 13 15; do
+  trap 'ac_signal='$ac_signal'; { (exit 1); exit 1; }' $ac_signal
+done
+ac_signal=0
+
+# confdefs.h avoids OS command line length limits that DEFS can exceed.
+rm -f -r conftest* confdefs.h
+
+# Predefined preprocessor variables.
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_NAME "$PACKAGE_NAME"
+_ACEOF
+
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_TARNAME "$PACKAGE_TARNAME"
+_ACEOF
+
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_VERSION "$PACKAGE_VERSION"
+_ACEOF
+
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_STRING "$PACKAGE_STRING"
+_ACEOF
+
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT"
+_ACEOF
+
+
+# Let the site file select an alternate cache file if it wants to.
 # 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
+if test -n "$CONFIG_SITE"; then
+  set x "$CONFIG_SITE"
+elif test "x$prefix" != xNONE; then
+  set x "$prefix/share/config.site" "$prefix/etc/config.site"
+else
+  set x "$ac_default_prefix/share/config.site" \
+	"$ac_default_prefix/etc/config.site"
 fi
-for ac_site_file in $CONFIG_SITE; do
+shift
+for ac_site_file
+do
   if test -r "$ac_site_file"; then
-    echo "loading site script $ac_site_file"
+    { echo "$as_me:$LINENO: loading site script $ac_site_file" >&5
+echo "$as_me: loading site script $ac_site_file" >&6;}
+    sed 's/^/| /' "$ac_site_file" >&5
     . "$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 at 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=
+  # Some versions of bash will fail to source /dev/null (special
+  # files actually), so we avoid doing that.
+  if test -f "$cache_file"; then
+    { echo "$as_me:$LINENO: loading cache $cache_file" >&5
+echo "$as_me: loading cache $cache_file" >&6;}
+    case $cache_file in
+      [\\/]* | ?:[\\/]* ) . "$cache_file";;
+      *)                      . "./$cache_file";;
+    esac
   fi
 else
-  ac_n= ac_c='\c' ac_t=
+  { echo "$as_me:$LINENO: creating cache $cache_file" >&5
+echo "$as_me: creating cache $cache_file" >&6;}
+  >$cache_file
 fi
 
-
-
-echo $ac_n "checking whether ${MAKE-make} sets \${MAKE}""... $ac_c" 1>&6
-echo "configure:527: 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
+# Check that the precious variables saved in the cache have kept the same
+# value.
+ac_cache_corrupted=false
+for ac_var in $ac_precious_vars; do
+  eval ac_old_set=\$ac_cv_env_${ac_var}_set
+  eval ac_new_set=\$ac_env_${ac_var}_set
+  eval ac_old_val=\$ac_cv_env_${ac_var}_value
+  eval ac_new_val=\$ac_env_${ac_var}_value
+  case $ac_old_set,$ac_new_set in
+    set,)
+      { echo "$as_me:$LINENO: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5
+echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;}
+      ac_cache_corrupted=: ;;
+    ,set)
+      { echo "$as_me:$LINENO: error: \`$ac_var' was not set in the previous run" >&5
+echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;}
+      ac_cache_corrupted=: ;;
+    ,);;
+    *)
+      if test "x$ac_old_val" != "x$ac_new_val"; then
+	{ echo "$as_me:$LINENO: error: \`$ac_var' has changed since the previous run:" >&5
+echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;}
+	{ echo "$as_me:$LINENO:   former value:  $ac_old_val" >&5
+echo "$as_me:   former value:  $ac_old_val" >&2;}
+	{ echo "$as_me:$LINENO:   current value: $ac_new_val" >&5
+echo "$as_me:   current value: $ac_new_val" >&2;}
+	ac_cache_corrupted=:
+      fi;;
+  esac
+  # Pass precious variables to config.status.
+  if test "$ac_new_set" = set; then
+    case $ac_new_val in
+    *\'*) ac_arg=$ac_var=`echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;;
+    *) ac_arg=$ac_var=$ac_new_val ;;
+    esac
+    case " $ac_configure_args " in
+      *" '$ac_arg' "*) ;; # Avoid dups.  Use of quotes ensures accuracy.
+      *) ac_configure_args="$ac_configure_args '$ac_arg'" ;;
+    esac
+  fi
+done
+if $ac_cache_corrupted; then
+  { echo "$as_me:$LINENO: error: changes in the environment can compromise the build" >&5
+echo "$as_me: error: changes in the environment can compromise the build" >&2;}
+  { { echo "$as_me:$LINENO: error: run \`make distclean' and/or \`rm $cache_file' and start over" >&5
+echo "$as_me: error: run \`make distclean' and/or \`rm $cache_file' and start over" >&2;}
+   { (exit 1); exit 1; }; }
+fi
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+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
+
+
+ac_config_headers="$ac_config_headers config.h"
+
+{ echo "$as_me:$LINENO: checking whether ${MAKE-make} sets \$(MAKE)" >&5
+echo $ECHO_N "checking whether ${MAKE-make} sets \$(MAKE)... $ECHO_C" >&6; }
+set x ${MAKE-make}; ac_make=`echo "$2" | sed 's/+/p/g; s/[^a-zA-Z0-9_]/_/g'`
+if { as_var=ac_cv_prog_make_${ac_make}_set; eval "test \"\${$as_var+set}\" = set"; }; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
 else
-  cat > conftestmake <<\EOF
+  cat >conftest.make <<\_ACEOF
+SHELL = /bin/sh
 all:
-	@echo 'ac_maketemp="${MAKE}"'
-EOF
+	@echo '@@@%%%=$(MAKE)=@@@%%%'
+_ACEOF
 # 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
+case `${MAKE-make} -f conftest.make 2>/dev/null` in
+  *@@@%%%=?*=@@@%%%*)
+    eval ac_cv_prog_make_${ac_make}_set=yes;;
+  *)
+    eval ac_cv_prog_make_${ac_make}_set=no;;
+esac
+rm -f conftest.make
 fi
-rm -f conftestmake
-fi
-if eval "test \"`echo '$ac_cv_prog_make_'${ac_make}_set`\" = yes"; then
-  echo "$ac_t""yes" 1>&6
+if eval test \$ac_cv_prog_make_${ac_make}_set = yes; then
+  { echo "$as_me:$LINENO: result: yes" >&5
+echo "${ECHO_T}yes" >&6; }
   SET_MAKE=
 else
-  echo "$ac_t""no" 1>&6
+  { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
   SET_MAKE="MAKE=${MAKE-make}"
 fi
 
-# 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:556: checking for $ac_word" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_CC'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
+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
+if test -n "$ac_tool_prefix"; then
+  # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args.
+set dummy ${ac_tool_prefix}gcc; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_prog_CC+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&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"
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+  for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_CC="${ac_tool_prefix}gcc"
+    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+done
+IFS=$as_save_IFS
+
 fi
 fi
-CC="$ac_cv_prog_CC"
+CC=$ac_cv_prog_CC
 if test -n "$CC"; then
-  echo "$ac_t""$CC" 1>&6
+  { echo "$as_me:$LINENO: result: $CC" >&5
+echo "${ECHO_T}$CC" >&6; }
 else
-  echo "$ac_t""no" 1>&6
+  { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
 fi
 
+
+fi
+if test -z "$ac_cv_prog_CC"; then
+  ac_ct_CC=$CC
+  # Extract the first word of "gcc", so it can be a program name with args.
+set dummy gcc; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_prog_ac_ct_CC+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+  if test -n "$ac_ct_CC"; then
+  ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+  for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_ac_ct_CC="gcc"
+    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+done
+IFS=$as_save_IFS
+
+fi
+fi
+ac_ct_CC=$ac_cv_prog_ac_ct_CC
+if test -n "$ac_ct_CC"; then
+  { echo "$as_me:$LINENO: result: $ac_ct_CC" >&5
+echo "${ECHO_T}$ac_ct_CC" >&6; }
+else
+  { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+  if test "x$ac_ct_CC" = x; then
+    CC=""
+  else
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools
+whose name does not start with the host triplet.  If you think this
+configuration is useful to you, please write to autoconf at gnu.org." >&5
+echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools
+whose name does not start with the host triplet.  If you think this
+configuration is useful to you, please write to autoconf at gnu.org." >&2;}
+ac_tool_warned=yes ;;
+esac
+    CC=$ac_ct_CC
+  fi
+else
+  CC="$ac_cv_prog_CC"
+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:586: checking for $ac_word" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_CC'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
+          if test -n "$ac_tool_prefix"; then
+    # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args.
+set dummy ${ac_tool_prefix}cc; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_prog_CC+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&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=":"
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+  for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_CC="${ac_tool_prefix}cc"
+    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+done
+IFS=$as_save_IFS
+
+fi
+fi
+CC=$ac_cv_prog_CC
+if test -n "$CC"; then
+  { echo "$as_me:$LINENO: result: $CC" >&5
+echo "${ECHO_T}$CC" >&6; }
+else
+  { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+  fi
+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 "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_prog_CC+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+  if test -n "$CC"; then
+  ac_cv_prog_CC="$CC" # Let the user override the test.
+else
   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"
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+  for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then
+       ac_prog_rejected=yes
+       continue
+     fi
+    ac_cv_prog_CC="cc"
+    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+done
+IFS=$as_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
+  if test $# != 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="$@"
+    ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@"
   fi
 fi
 fi
 fi
-CC="$ac_cv_prog_CC"
+CC=$ac_cv_prog_CC
 if test -n "$CC"; then
-  echo "$ac_t""$CC" 1>&6
+  { echo "$as_me:$LINENO: result: $CC" >&5
+echo "${ECHO_T}$CC" >&6; }
 else
-  echo "$ac_t""no" 1>&6
+  { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&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:637: checking for $ac_word" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_CC'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
+
+fi
+if test -z "$CC"; then
+  if test -n "$ac_tool_prefix"; then
+  for ac_prog in cl.exe
+  do
+    # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args.
+set dummy $ac_tool_prefix$ac_prog; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_prog_CC+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&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
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+  for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_CC="$ac_tool_prefix$ac_prog"
+    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+done
+IFS=$as_save_IFS
+
+fi
+fi
+CC=$ac_cv_prog_CC
+if test -n "$CC"; then
+  { echo "$as_me:$LINENO: result: $CC" >&5
+echo "${ECHO_T}$CC" >&6; }
+else
+  { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+    test -n "$CC" && break
+  done
+fi
+if test -z "$CC"; then
+  ac_ct_CC=$CC
+  for ac_prog in cl.exe
+do
+  # Extract the first word of "$ac_prog", so it can be a program name with args.
+set dummy $ac_prog; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_prog_ac_ct_CC+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+  if test -n "$ac_ct_CC"; then
+  ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+  for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_ac_ct_CC="$ac_prog"
+    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+done
+IFS=$as_save_IFS
+
+fi
+fi
+ac_ct_CC=$ac_cv_prog_ac_ct_CC
+if test -n "$ac_ct_CC"; then
+  { echo "$as_me:$LINENO: result: $ac_ct_CC" >&5
+echo "${ECHO_T}$ac_ct_CC" >&6; }
+else
+  { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+  test -n "$ac_ct_CC" && break
+done
+
+  if test "x$ac_ct_CC" = x; then
+    CC=""
+  else
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools
+whose name does not start with the host triplet.  If you think this
+configuration is useful to you, please write to autoconf at gnu.org." >&5
+echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools
+whose name does not start with the host triplet.  If you think this
+configuration is useful to you, please write to autoconf at gnu.org." >&2;}
+ac_tool_warned=yes ;;
+esac
+    CC=$ac_ct_CC
+  fi
+fi
+
+fi
+
+
+test -z "$CC" && { { echo "$as_me:$LINENO: error: no acceptable C compiler found in \$PATH
+See \`config.log' for more details." >&5
+echo "$as_me: error: no acceptable C compiler found in \$PATH
+See \`config.log' for more details." >&2;}
+   { (exit 1); exit 1; }; }
+
+# Provide some information about the compiler.
+echo "$as_me:$LINENO: checking for C compiler version" >&5
+ac_compiler=`set X $ac_compile; echo $2`
+{ (ac_try="$ac_compiler --version >&5"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compiler --version >&5") 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }
+{ (ac_try="$ac_compiler -v >&5"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compiler -v >&5") 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }
+{ (ac_try="$ac_compiler -V >&5"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compiler -V >&5") 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }
+
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+ac_clean_files_save=$ac_clean_files
+ac_clean_files="$ac_clean_files a.out a.exe b.out"
+# Try to create an executable without -o first, disregard a.out.
+# It will help us diagnose broken compilers, and finding out an intuition
+# of exeext.
+{ echo "$as_me:$LINENO: checking for C compiler default output file name" >&5
+echo $ECHO_N "checking for C compiler default output file name... $ECHO_C" >&6; }
+ac_link_default=`echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'`
+#
+# List of possible output files, starting from the most likely.
+# The algorithm is not robust to junk in `.', hence go to wildcards (a.*)
+# only as a last resort.  b.out is created by i960 compilers.
+ac_files='a_out.exe a.exe conftest.exe a.out conftest a.* conftest.* b.out'
+#
+# The IRIX 6 linker writes into existing files which may not be
+# executable, retaining their permissions.  Remove them first so a
+# subsequent execution test works.
+ac_rmfiles=
+for ac_file in $ac_files
+do
+  case $ac_file in
+    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.o | *.obj ) ;;
+    * ) ac_rmfiles="$ac_rmfiles $ac_file";;
+  esac
+done
+rm -f $ac_rmfiles
+
+if { (ac_try="$ac_link_default"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_link_default") 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; then
+  # Autoconf-2.13 could set the ac_cv_exeext variable to `no'.
+# So ignore a value of `no', otherwise this would lead to `EXEEXT = no'
+# in a Makefile.  We should not override ac_cv_exeext if it was cached,
+# so that the user can short-circuit this test for compilers unknown to
+# Autoconf.
+for ac_file in $ac_files ''
+do
+  test -f "$ac_file" || continue
+  case $ac_file in
+    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.o | *.obj )
+	;;
+    [ab].out )
+	# We found the default executable, but exeext='' is most
+	# certainly right.
+	break;;
+    *.* )
+        if test "${ac_cv_exeext+set}" = set && test "$ac_cv_exeext" != no;
+	then :; else
+	   ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'`
+	fi
+	# We set ac_cv_exeext here because the later test for it is not
+	# safe: cross compilers may not add the suffix if given an `-o'
+	# argument, so we may need to know it at that point already.
+	# Even if this section looks crufty: it has the advantage of
+	# actually working.
+	break;;
+    * )
+	break;;
+  esac
+done
+test "$ac_cv_exeext" = no && ac_cv_exeext=
+
+else
+  ac_file=''
+fi
+
+{ echo "$as_me:$LINENO: result: $ac_file" >&5
+echo "${ECHO_T}$ac_file" >&6; }
+if test -z "$ac_file"; then
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+{ { echo "$as_me:$LINENO: error: C compiler cannot create executables
+See \`config.log' for more details." >&5
+echo "$as_me: error: C compiler cannot create executables
+See \`config.log' for more details." >&2;}
+   { (exit 77); exit 77; }; }
+fi
+
+ac_exeext=$ac_cv_exeext
+
+# Check that the compiler produces executables we can run.  If not, either
+# the compiler is broken, or we cross compile.
+{ echo "$as_me:$LINENO: checking whether the C compiler works" >&5
+echo $ECHO_N "checking whether the C compiler works... $ECHO_C" >&6; }
+# FIXME: These cross compiler hacks should be removed for Autoconf 3.0
+# If not cross compiling, check that we can run a simple program.
+if test "$cross_compiling" != yes; then
+  if { ac_try='./$ac_file'
+  { (case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_try") 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; }; then
+    cross_compiling=no
+  else
+    if test "$cross_compiling" = maybe; then
+	cross_compiling=yes
+    else
+	{ { echo "$as_me:$LINENO: error: cannot run C compiled programs.
+If you meant to cross compile, use \`--host'.
+See \`config.log' for more details." >&5
+echo "$as_me: error: cannot run C compiled programs.
+If you meant to cross compile, use \`--host'.
+See \`config.log' for more details." >&2;}
+   { (exit 1); exit 1; }; }
     fi
-  done
-  IFS="$ac_save_ifs"
+  fi
 fi
+{ echo "$as_me:$LINENO: result: yes" >&5
+echo "${ECHO_T}yes" >&6; }
+
+rm -f a.out a.exe conftest$ac_cv_exeext b.out
+ac_clean_files=$ac_clean_files_save
+# Check that the compiler produces executables we can run.  If not, either
+# the compiler is broken, or we cross compile.
+{ echo "$as_me:$LINENO: checking whether we are cross compiling" >&5
+echo $ECHO_N "checking whether we are cross compiling... $ECHO_C" >&6; }
+{ echo "$as_me:$LINENO: result: $cross_compiling" >&5
+echo "${ECHO_T}$cross_compiling" >&6; }
+
+{ echo "$as_me:$LINENO: checking for suffix of executables" >&5
+echo $ECHO_N "checking for suffix of executables... $ECHO_C" >&6; }
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_link") 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; then
+  # If both `conftest.exe' and `conftest' are `present' (well, observable)
+# catch `conftest.exe'.  For instance with Cygwin, `ls conftest' will
+# work properly (i.e., refer to `conftest.exe'), while it won't with
+# `rm'.
+for ac_file in conftest.exe conftest conftest.*; do
+  test -f "$ac_file" || continue
+  case $ac_file in
+    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.o | *.obj ) ;;
+    *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'`
+	  break;;
+    * ) break;;
+  esac
+done
+else
+  { { echo "$as_me:$LINENO: error: cannot compute suffix of executables: cannot compile and link
+See \`config.log' for more details." >&5
+echo "$as_me: error: cannot compute suffix of executables: cannot compile and link
+See \`config.log' for more details." >&2;}
+   { (exit 1); exit 1; }; }
 fi
-CC="$ac_cv_prog_CC"
-if test -n "$CC"; then
-  echo "$ac_t""$CC" 1>&6
+
+rm -f conftest$ac_cv_exeext
+{ echo "$as_me:$LINENO: result: $ac_cv_exeext" >&5
+echo "${ECHO_T}$ac_cv_exeext" >&6; }
+
+rm -f conftest.$ac_ext
+EXEEXT=$ac_cv_exeext
+ac_exeext=$EXEEXT
+{ echo "$as_me:$LINENO: checking for suffix of object files" >&5
+echo $ECHO_N "checking for suffix of object files... $ECHO_C" >&6; }
+if test "${ac_cv_objext+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
 else
-  echo "$ac_t""no" 1>&6
+  cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.o conftest.obj
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compile") 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }; then
+  for ac_file in conftest.o conftest.obj conftest.*; do
+  test -f "$ac_file" || continue;
+  case $ac_file in
+    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf ) ;;
+    *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'`
+       break;;
+  esac
+done
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+{ { echo "$as_me:$LINENO: error: cannot compute suffix of object files: cannot compile
+See \`config.log' for more details." >&5
+echo "$as_me: error: cannot compute suffix of object files: cannot compile
+See \`config.log' for more details." >&2;}
+   { (exit 1); exit 1; }; }
 fi
- ;;
-    esac
-  fi
-  test -z "$CC" && { echo "configure: error: no acceptable cc found in \$PATH" 1>&2; exit 1; }
+
+rm -f conftest.$ac_cv_objext conftest.$ac_ext
 fi
-
-echo $ac_n "checking whether the C compiler ($CC $CFLAGS $LDFLAGS) works""... $ac_c" 1>&6
-echo "configure:669: checking whether the C compiler ($CC $CFLAGS $LDFLAGS) works" >&5
-
-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 << EOF
-
-#line 680 "configure"
-#include "confdefs.h"
-
-main(){return(0);}
-EOF
-if { (eval echo configure:685: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
-  ac_cv_prog_cc_works=yes
-  # If we can't run a trivial program, we are probably using a cross compiler.
-  if (./conftest; exit) 2>/dev/null; then
-    ac_cv_prog_cc_cross=no
-  else
-    ac_cv_prog_cc_cross=yes
-  fi
+{ echo "$as_me:$LINENO: result: $ac_cv_objext" >&5
+echo "${ECHO_T}$ac_cv_objext" >&6; }
+OBJEXT=$ac_cv_objext
+ac_objext=$OBJEXT
+{ echo "$as_me:$LINENO: checking whether we are using the GNU C compiler" >&5
+echo $ECHO_N "checking whether we are using the GNU C compiler... $ECHO_C" >&6; }
+if test "${ac_cv_c_compiler_gnu+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
 else
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  ac_cv_prog_cc_works=no
+  cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+
+int
+main ()
+{
+#ifndef __GNUC__
+       choke me
+#endif
+
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compile") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } && {
+	 test -z "$ac_c_werror_flag" ||
+	 test ! -s conftest.err
+       } && test -s conftest.$ac_objext; then
+  ac_compiler_gnu=yes
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+	ac_compiler_gnu=no
 fi
-rm -fr 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
-
-echo "$ac_t""$ac_cv_prog_cc_works" 1>&6
-if test $ac_cv_prog_cc_works = no; then
-  { echo "configure: error: installation or configuration problem: C compiler cannot create executables." 1>&2; exit 1; }
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+ac_cv_c_compiler_gnu=$ac_compiler_gnu
+
 fi
-echo $ac_n "checking whether the C compiler ($CC $CFLAGS $LDFLAGS) is a cross-compiler""... $ac_c" 1>&6
-echo "configure:711: checking whether the C compiler ($CC $CFLAGS $LDFLAGS) is a cross-compiler" >&5
-echo "$ac_t""$ac_cv_prog_cc_cross" 1>&6
-cross_compiling=$ac_cv_prog_cc_cross
-
-echo $ac_n "checking whether we are using GNU C""... $ac_c" 1>&6
-echo "configure:716: 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
+{ echo "$as_me:$LINENO: result: $ac_cv_c_compiler_gnu" >&5
+echo "${ECHO_T}$ac_cv_c_compiler_gnu" >&6; }
+GCC=`test $ac_compiler_gnu = yes && echo yes`
+ac_test_CFLAGS=${CFLAGS+set}
+ac_save_CFLAGS=$CFLAGS
+{ echo "$as_me:$LINENO: checking whether $CC accepts -g" >&5
+echo $ECHO_N "checking whether $CC accepts -g... $ECHO_C" >&6; }
+if test "${ac_cv_prog_cc_g+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
 else
-  cat > conftest.c <<EOF
-#ifdef __GNUC__
-  yes;
-#endif
-EOF
-if { ac_try='${CC-cc} -E conftest.c'; { (eval echo configure:725: \"$ac_try\") 1>&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:744: 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_save_c_werror_flag=$ac_c_werror_flag
+   ac_c_werror_flag=yes
+   ac_cv_prog_cc_g=no
+   CFLAGS="-g"
+   cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compile") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } && {
+	 test -z "$ac_c_werror_flag" ||
+	 test ! -s conftest.err
+       } && test -s conftest.$ac_objext; then
   ac_cv_prog_cc_g=yes
 else
-  ac_cv_prog_cc_g=no
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+	CFLAGS=""
+      cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compile") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } && {
+	 test -z "$ac_c_werror_flag" ||
+	 test ! -s conftest.err
+       } && test -s conftest.$ac_objext; then
+  :
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+	ac_c_werror_flag=$ac_save_c_werror_flag
+	 CFLAGS="-g"
+	 cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compile") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } && {
+	 test -z "$ac_c_werror_flag" ||
+	 test ! -s conftest.err
+       } && test -s conftest.$ac_objext; then
+  ac_cv_prog_cc_g=yes
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+
 fi
-rm -f conftest*
-
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
 fi
 
-echo "$ac_t""$ac_cv_prog_cc_g" 1>&6
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+   ac_c_werror_flag=$ac_save_c_werror_flag
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_prog_cc_g" >&5
+echo "${ECHO_T}$ac_cv_prog_cc_g" >&6; }
 if test "$ac_test_CFLAGS" = set; then
-  CFLAGS="$ac_save_CFLAGS"
+  CFLAGS=$ac_save_CFLAGS
 elif test $ac_cv_prog_cc_g = yes; then
   if test "$GCC" = yes; then
     CFLAGS="-g -O2"
@@ -770,216 +2477,702 @@
     CFLAGS=
   fi
 fi
-
-                      echo $ac_n "checking how to run the C preprocessor""... $ac_c" 1>&6
-echo "configure:776: checking how to run the C preprocessor" >&5
+{ echo "$as_me:$LINENO: checking for $CC option to accept ISO C89" >&5
+echo $ECHO_N "checking for $CC option to accept ISO C89... $ECHO_C" >&6; }
+if test "${ac_cv_prog_cc_c89+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+  ac_cv_prog_cc_c89=no
+ac_save_CC=$CC
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+#include <stdarg.h>
+#include <stdio.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+/* Most of the following tests are stolen from RCS 5.7's src/conf.sh.  */
+struct buf { int x; };
+FILE * (*rcsopen) (struct buf *, struct stat *, int);
+static char *e (p, i)
+     char **p;
+     int i;
+{
+  return p[i];
+}
+static char *f (char * (*g) (char **, int), char **p, ...)
+{
+  char *s;
+  va_list v;
+  va_start (v,p);
+  s = g (p, va_arg (v,int));
+  va_end (v);
+  return s;
+}
+
+/* OSF 4.0 Compaq cc is some sort of almost-ANSI by default.  It has
+   function prototypes and stuff, but not '\xHH' hex character constants.
+   These don't provoke an error unfortunately, instead are silently treated
+   as 'x'.  The following induces an error, until -std is added to get
+   proper ANSI mode.  Curiously '\x00'!='x' always comes out true, for an
+   array size at least.  It's necessary to write '\x00'==0 to get something
+   that's true only with -std.  */
+int osf4_cc_array ['\x00' == 0 ? 1 : -1];
+
+/* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters
+   inside strings and character constants.  */
+#define FOO(x) 'x'
+int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1];
+
+int test (int i, double x);
+struct s1 {int (*f) (int a);};
+struct s2 {int (*f) (double a);};
+int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int);
+int argc;
+char **argv;
+int
+main ()
+{
+return f (e, argv, 0) != argv[0]  ||  f (e, argv, 1) != argv[1];
+  ;
+  return 0;
+}
+_ACEOF
+for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \
+	-Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__"
+do
+  CC="$ac_save_CC $ac_arg"
+  rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compile") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } && {
+	 test -z "$ac_c_werror_flag" ||
+	 test ! -s conftest.err
+       } && test -s conftest.$ac_objext; then
+  ac_cv_prog_cc_c89=$ac_arg
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+
+fi
+
+rm -f core conftest.err conftest.$ac_objext
+  test "x$ac_cv_prog_cc_c89" != "xno" && break
+done
+rm -f conftest.$ac_ext
+CC=$ac_save_CC
+
+fi
+# AC_CACHE_VAL
+case "x$ac_cv_prog_cc_c89" in
+  x)
+    { echo "$as_me:$LINENO: result: none needed" >&5
+echo "${ECHO_T}none needed" >&6; } ;;
+  xno)
+    { echo "$as_me:$LINENO: result: unsupported" >&5
+echo "${ECHO_T}unsupported" >&6; } ;;
+  *)
+    CC="$CC $ac_cv_prog_cc_c89"
+    { echo "$as_me:$LINENO: result: $ac_cv_prog_cc_c89" >&5
+echo "${ECHO_T}$ac_cv_prog_cc_c89" >&6; } ;;
+esac
+
+
+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
+
+                      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: checking how to run the C preprocessor" >&5
+echo $ECHO_N "checking how to run the C preprocessor... $ECHO_C" >&6; }
 # 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
+  if test "${ac_cv_prog_CPP+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&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"
+      # Double quotes because CPP needs to be expanded
+    for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp"
+    do
+      ac_preproc_ok=false
+for ac_c_preproc_warn_flag in '' yes
+do
+  # Use a header file that comes with gcc, so configuring glibc
+  # with a fresh cross-compiler works.
+  # Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+  # <limits.h> exists even on freestanding compilers.
   # On the NeXT, cc -E runs the code through the compiler's parser,
-  # not just through cpp.
-  cat > conftest.$ac_ext <<EOF
-#line 791 "configure"
-#include "confdefs.h"
-#include <assert.h>
-Syntax Error
-EOF
-ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
-{ (eval echo configure:797: \"$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
+  # not just through cpp. "Syntax error" is here to catch this case.
+  cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+		     Syntax error
+_ACEOF
+if { (ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } >/dev/null && {
+	 test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
+	 test ! -s conftest.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 <<EOF
-#line 808 "configure"
-#include "confdefs.h"
-#include <assert.h>
-Syntax Error
-EOF
-ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
-{ (eval echo configure:814: \"$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
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+  # Broken: fails on valid input.
+continue
+fi
+
+rm -f conftest.err conftest.$ac_ext
+
+  # OK, works on sane cases.  Now check whether nonexistent headers
+  # can be detected and how.
+  cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+#include <ac_nonexistent.h>
+_ACEOF
+if { (ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } >/dev/null && {
+	 test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
+	 test ! -s conftest.err
+       }; then
+  # Broken: success on invalid input.
+continue
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+  # Passes both tests.
+ac_preproc_ok=:
+break
+fi
+
+rm -f conftest.err conftest.$ac_ext
+
+done
+# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
+rm -f conftest.err conftest.$ac_ext
+if $ac_preproc_ok; then
+  break
+fi
+
+    done
+    ac_cv_prog_CPP=$CPP
+
+fi
+  CPP=$ac_cv_prog_CPP
+else
+  ac_cv_prog_CPP=$CPP
+fi
+{ echo "$as_me:$LINENO: result: $CPP" >&5
+echo "${ECHO_T}$CPP" >&6; }
+ac_preproc_ok=false
+for ac_c_preproc_warn_flag in '' yes
+do
+  # Use a header file that comes with gcc, so configuring glibc
+  # with a fresh cross-compiler works.
+  # Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+  # <limits.h> exists even on freestanding compilers.
+  # On the NeXT, cc -E runs the code through the compiler's parser,
+  # not just through cpp. "Syntax error" is here to catch this case.
+  cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+		     Syntax error
+_ACEOF
+if { (ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } >/dev/null && {
+	 test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
+	 test ! -s conftest.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 <<EOF
-#line 825 "configure"
-#include "confdefs.h"
-#include <assert.h>
-Syntax Error
-EOF
-ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
-{ (eval echo configure:831: \"$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
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+  # Broken: fails on valid input.
+continue
+fi
+
+rm -f conftest.err conftest.$ac_ext
+
+  # OK, works on sane cases.  Now check whether nonexistent headers
+  # can be detected and how.
+  cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+#include <ac_nonexistent.h>
+_ACEOF
+if { (ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } >/dev/null && {
+	 test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
+	 test ! -s conftest.err
+       }; then
+  # Broken: success on invalid input.
+continue
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+  # Passes both tests.
+ac_preproc_ok=:
+break
+fi
+
+rm -f conftest.err conftest.$ac_ext
+
+done
+# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
+rm -f conftest.err conftest.$ac_ext
+if $ac_preproc_ok; then
   :
 else
-  echo "$ac_err" >&5
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  CPP=/lib/cpp
+  { { echo "$as_me:$LINENO: error: C preprocessor \"$CPP\" fails sanity check
+See \`config.log' for more details." >&5
+echo "$as_me: error: C preprocessor \"$CPP\" fails sanity check
+See \`config.log' for more details." >&2;}
+   { (exit 1); exit 1; }; }
 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
-
-                      for ac_prog in $CCC c++ g++ gcc CC cxx cc++ cl
-do
-# Extract the first word of "$ac_prog", so it can be a program name with args.
-set dummy $ac_prog; ac_word=$2
-echo $ac_n "checking for $ac_word""... $ac_c" 1>&6
-echo "configure:860: checking for $ac_word" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_CXX'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
+
+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
+
+                      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
+if test -z "$CXX"; then
+  if test -n "$CCC"; then
+    CXX=$CCC
+  else
+    if test -n "$ac_tool_prefix"; then
+  for ac_prog in g++ c++ gpp aCC CC cxx cc++ cl.exe FCC KCC RCC xlC_r xlC
+  do
+    # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args.
+set dummy $ac_tool_prefix$ac_prog; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_prog_CXX+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
 else
   if test -n "$CXX"; then
   ac_cv_prog_CXX="$CXX" # 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_CXX="$ac_prog"
-      break
-    fi
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+  for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_CXX="$ac_tool_prefix$ac_prog"
+    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+done
+IFS=$as_save_IFS
+
+fi
+fi
+CXX=$ac_cv_prog_CXX
+if test -n "$CXX"; then
+  { echo "$as_me:$LINENO: result: $CXX" >&5
+echo "${ECHO_T}$CXX" >&6; }
+else
+  { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
+fi
+
+
+    test -n "$CXX" && break
   done
-  IFS="$ac_save_ifs"
 fi
+if test -z "$CXX"; then
+  ac_ct_CXX=$CXX
+  for ac_prog in g++ c++ gpp aCC CC cxx cc++ cl.exe FCC KCC RCC xlC_r xlC
+do
+  # Extract the first word of "$ac_prog", so it can be a program name with args.
+set dummy $ac_prog; ac_word=$2
+{ echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
+if test "${ac_cv_prog_ac_ct_CXX+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+  if test -n "$ac_ct_CXX"; then
+  ac_cv_prog_ac_ct_CXX="$ac_ct_CXX" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+  for ac_exec_ext in '' $ac_executable_extensions; do
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+    ac_cv_prog_ac_ct_CXX="$ac_prog"
+    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+done
+IFS=$as_save_IFS
+
 fi
-CXX="$ac_cv_prog_CXX"
-if test -n "$CXX"; then
-  echo "$ac_t""$CXX" 1>&6
+fi
+ac_ct_CXX=$ac_cv_prog_ac_ct_CXX
+if test -n "$ac_ct_CXX"; then
+  { echo "$as_me:$LINENO: result: $ac_ct_CXX" >&5
+echo "${ECHO_T}$ac_ct_CXX" >&6; }
 else
-  echo "$ac_t""no" 1>&6
+  { echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
 fi
 
-test -n "$CXX" && break
+
+  test -n "$ac_ct_CXX" && break
 done
-test -n "$CXX" || CXX="gcc"
-
-
-echo $ac_n "checking whether the C++ compiler ($CXX $CXXFLAGS $LDFLAGS) works""... $ac_c" 1>&6
-echo "configure:892: checking whether the C++ compiler ($CXX $CXXFLAGS $LDFLAGS) works" >&5
-
-ac_ext=C
-# CXXFLAGS is not in ac_cpp because -g, -O, etc. are not valid cpp options.
-ac_cpp='$CXXCPP $CPPFLAGS'
-ac_compile='${CXX-g++} -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext 1>&5'
-ac_link='${CXX-g++} -o conftest${ac_exeext} $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS 1>&5'
-cross_compiling=$ac_cv_prog_cxx_cross
-
-cat > conftest.$ac_ext << EOF
-
-#line 903 "configure"
-#include "confdefs.h"
-
-int main(){return(0);}
-EOF
-if { (eval echo configure:908: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest${ac_exeext}; then
-  ac_cv_prog_cxx_works=yes
-  # If we can't run a trivial program, we are probably using a cross compiler.
-  if (./conftest; exit) 2>/dev/null; then
-    ac_cv_prog_cxx_cross=no
+
+  if test "x$ac_ct_CXX" = x; then
+    CXX="g++"
   else
-    ac_cv_prog_cxx_cross=yes
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools
+whose name does not start with the host triplet.  If you think this
+configuration is useful to you, please write to autoconf at gnu.org." >&5
+echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools
+whose name does not start with the host triplet.  If you think this
+configuration is useful to you, please write to autoconf at gnu.org." >&2;}
+ac_tool_warned=yes ;;
+esac
+    CXX=$ac_ct_CXX
   fi
+fi
+
+  fi
+fi
+# Provide some information about the compiler.
+echo "$as_me:$LINENO: checking for C++ compiler version" >&5
+ac_compiler=`set X $ac_compile; echo $2`
+{ (ac_try="$ac_compiler --version >&5"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compiler --version >&5") 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }
+{ (ac_try="$ac_compiler -v >&5"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compiler -v >&5") 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }
+{ (ac_try="$ac_compiler -V >&5"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compiler -V >&5") 2>&5
+  ac_status=$?
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); }
+
+{ echo "$as_me:$LINENO: checking whether we are using the GNU C++ compiler" >&5
+echo $ECHO_N "checking whether we are using the GNU C++ compiler... $ECHO_C" >&6; }
+if test "${ac_cv_cxx_compiler_gnu+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
 else
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  ac_cv_prog_cxx_works=no
+  cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+
+int
+main ()
+{
+#ifndef __GNUC__
+       choke me
+#endif
+
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compile") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } && {
+	 test -z "$ac_cxx_werror_flag" ||
+	 test ! -s conftest.err
+       } && test -s conftest.$ac_objext; then
+  ac_compiler_gnu=yes
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+	ac_compiler_gnu=no
 fi
-rm -fr 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
-
-echo "$ac_t""$ac_cv_prog_cxx_works" 1>&6
-if test $ac_cv_prog_cxx_works = no; then
-  { echo "configure: error: installation or configuration problem: C++ compiler cannot create executables." 1>&2; exit 1; }
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+ac_cv_cxx_compiler_gnu=$ac_compiler_gnu
+
 fi
-echo $ac_n "checking whether the C++ compiler ($CXX $CXXFLAGS $LDFLAGS) is a cross-compiler""... $ac_c" 1>&6
-echo "configure:934: checking whether the C++ compiler ($CXX $CXXFLAGS $LDFLAGS) is a cross-compiler" >&5
-echo "$ac_t""$ac_cv_prog_cxx_cross" 1>&6
-cross_compiling=$ac_cv_prog_cxx_cross
-
-echo $ac_n "checking whether we are using GNU C++""... $ac_c" 1>&6
-echo "configure:939: checking whether we are using GNU C++" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_gxx'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
+{ echo "$as_me:$LINENO: result: $ac_cv_cxx_compiler_gnu" >&5
+echo "${ECHO_T}$ac_cv_cxx_compiler_gnu" >&6; }
+GXX=`test $ac_compiler_gnu = yes && echo yes`
+ac_test_CXXFLAGS=${CXXFLAGS+set}
+ac_save_CXXFLAGS=$CXXFLAGS
+{ echo "$as_me:$LINENO: checking whether $CXX accepts -g" >&5
+echo $ECHO_N "checking whether $CXX accepts -g... $ECHO_C" >&6; }
+if test "${ac_cv_prog_cxx_g+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
 else
-  cat > conftest.C <<EOF
-#ifdef __GNUC__
-  yes;
-#endif
-EOF
-if { ac_try='${CXX-g++} -E conftest.C'; { (eval echo configure:948: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }; } | egrep yes >/dev/null 2>&1; then
-  ac_cv_prog_gxx=yes
-else
-  ac_cv_prog_gxx=no
-fi
-fi
-
-echo "$ac_t""$ac_cv_prog_gxx" 1>&6
-
-if test $ac_cv_prog_gxx = yes; then
-  GXX=yes
-else
-  GXX=
-fi
-
-ac_test_CXXFLAGS="${CXXFLAGS+set}"
-ac_save_CXXFLAGS="$CXXFLAGS"
-CXXFLAGS=
-echo $ac_n "checking whether ${CXX-g++} accepts -g""... $ac_c" 1>&6
-echo "configure:967: checking whether ${CXX-g++} accepts -g" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_cxx_g'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  echo 'void f(){}' > conftest.cc
-if test -z "`${CXX-g++} -g -c conftest.cc 2>&1`"; then
+  ac_save_cxx_werror_flag=$ac_cxx_werror_flag
+   ac_cxx_werror_flag=yes
+   ac_cv_prog_cxx_g=no
+   CXXFLAGS="-g"
+   cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compile") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } && {
+	 test -z "$ac_cxx_werror_flag" ||
+	 test ! -s conftest.err
+       } && test -s conftest.$ac_objext; then
   ac_cv_prog_cxx_g=yes
 else
-  ac_cv_prog_cxx_g=no
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+	CXXFLAGS=""
+      cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compile") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } && {
+	 test -z "$ac_cxx_werror_flag" ||
+	 test ! -s conftest.err
+       } && test -s conftest.$ac_objext; then
+  :
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+	ac_cxx_werror_flag=$ac_save_cxx_werror_flag
+	 CXXFLAGS="-g"
+	 cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compile") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } && {
+	 test -z "$ac_cxx_werror_flag" ||
+	 test ! -s conftest.err
+       } && test -s conftest.$ac_objext; then
+  ac_cv_prog_cxx_g=yes
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+
 fi
-rm -f conftest*
-
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
 fi
 
-echo "$ac_t""$ac_cv_prog_cxx_g" 1>&6
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+   ac_cxx_werror_flag=$ac_save_cxx_werror_flag
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_prog_cxx_g" >&5
+echo "${ECHO_T}$ac_cv_prog_cxx_g" >&6; }
 if test "$ac_test_CXXFLAGS" = set; then
-  CXXFLAGS="$ac_save_CXXFLAGS"
+  CXXFLAGS=$ac_save_CXXFLAGS
 elif test $ac_cv_prog_cxx_g = yes; then
   if test "$GXX" = yes; then
     CXXFLAGS="-g -O2"
@@ -993,49 +3186,237 @@
     CXXFLAGS=
   fi
 fi
-
-                      echo $ac_n "checking how to run the C++ preprocessor""... $ac_c" 1>&6
-echo "configure:999: checking how to run the C++ preprocessor" >&5
+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
+
+                      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
+{ echo "$as_me:$LINENO: checking how to run the C++ preprocessor" >&5
+echo $ECHO_N "checking how to run the C++ preprocessor... $ECHO_C" >&6; }
 if test -z "$CXXCPP"; then
-if eval "test \"`echo '$''{'ac_cv_prog_CXXCPP'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
+  if test "${ac_cv_prog_CXXCPP+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
 else
-  ac_ext=C
-# CXXFLAGS is not in ac_cpp because -g, -O, etc. are not valid cpp options.
-ac_cpp='$CXXCPP $CPPFLAGS'
-ac_compile='${CXX-g++} -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext 1>&5'
-ac_link='${CXX-g++} -o conftest${ac_exeext} $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS 1>&5'
-cross_compiling=$ac_cv_prog_cxx_cross
-  CXXCPP="${CXX-g++} -E"
-  cat > conftest.$ac_ext <<EOF
-#line 1012 "configure"
-#include "confdefs.h"
-#include <stdlib.h>
-EOF
-ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
-{ (eval echo configure:1017: \"$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
+      # Double quotes because CXXCPP needs to be expanded
+    for CXXCPP in "$CXX -E" "/lib/cpp"
+    do
+      ac_preproc_ok=false
+for ac_cxx_preproc_warn_flag in '' yes
+do
+  # Use a header file that comes with gcc, so configuring glibc
+  # with a fresh cross-compiler works.
+  # Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+  # <limits.h> exists even on freestanding compilers.
+  # On the NeXT, cc -E runs the code through the compiler's parser,
+  # not just through cpp. "Syntax error" is here to catch this case.
+  cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+		     Syntax error
+_ACEOF
+if { (ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } >/dev/null && {
+	 test -z "$ac_cxx_preproc_warn_flag$ac_cxx_werror_flag" ||
+	 test ! -s conftest.err
+       }; then
   :
 else
-  echo "$ac_err" >&5
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  CXXCPP=/lib/cpp
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+  # Broken: fails on valid input.
+continue
 fi
-rm -f conftest*
-  ac_cv_prog_CXXCPP="$CXXCPP"
+
+rm -f conftest.err conftest.$ac_ext
+
+  # OK, works on sane cases.  Now check whether nonexistent headers
+  # can be detected and how.
+  cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+#include <ac_nonexistent.h>
+_ACEOF
+if { (ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } >/dev/null && {
+	 test -z "$ac_cxx_preproc_warn_flag$ac_cxx_werror_flag" ||
+	 test ! -s conftest.err
+       }; then
+  # Broken: success on invalid input.
+continue
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+  # Passes both tests.
+ac_preproc_ok=:
+break
+fi
+
+rm -f conftest.err conftest.$ac_ext
+
+done
+# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
+rm -f conftest.err conftest.$ac_ext
+if $ac_preproc_ok; then
+  break
+fi
+
+    done
+    ac_cv_prog_CXXCPP=$CXXCPP
+
+fi
+  CXXCPP=$ac_cv_prog_CXXCPP
+else
+  ac_cv_prog_CXXCPP=$CXXCPP
+fi
+{ echo "$as_me:$LINENO: result: $CXXCPP" >&5
+echo "${ECHO_T}$CXXCPP" >&6; }
+ac_preproc_ok=false
+for ac_cxx_preproc_warn_flag in '' yes
+do
+  # Use a header file that comes with gcc, so configuring glibc
+  # with a fresh cross-compiler works.
+  # Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+  # <limits.h> exists even on freestanding compilers.
+  # On the NeXT, cc -E runs the code through the compiler's parser,
+  # not just through cpp. "Syntax error" is here to catch this case.
+  cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+		     Syntax error
+_ACEOF
+if { (ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } >/dev/null && {
+	 test -z "$ac_cxx_preproc_warn_flag$ac_cxx_werror_flag" ||
+	 test ! -s conftest.err
+       }; then
+  :
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+  # Broken: fails on valid input.
+continue
+fi
+
+rm -f conftest.err conftest.$ac_ext
+
+  # OK, works on sane cases.  Now check whether nonexistent headers
+  # can be detected and how.
+  cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+#include <ac_nonexistent.h>
+_ACEOF
+if { (ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } >/dev/null && {
+	 test -z "$ac_cxx_preproc_warn_flag$ac_cxx_werror_flag" ||
+	 test ! -s conftest.err
+       }; then
+  # Broken: success on invalid input.
+continue
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+  # Passes both tests.
+ac_preproc_ok=:
+break
+fi
+
+rm -f conftest.err conftest.$ac_ext
+
+done
+# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
+rm -f conftest.err conftest.$ac_ext
+if $ac_preproc_ok; then
+  :
+else
+  { { echo "$as_me:$LINENO: error: C++ preprocessor \"$CXXCPP\" fails sanity check
+See \`config.log' for more details." >&5
+echo "$as_me: error: C++ preprocessor \"$CXXCPP\" fails sanity check
+See \`config.log' for more details." >&2;}
+   { (exit 1); exit 1; }; }
+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
-fi
-fi
-CXXCPP="$ac_cv_prog_CXXCPP"
-echo "$ac_t""$CXXCPP" 1>&6
+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
 
                       # Find a good install program.  We prefer a C program (faster),
 # so one script is as good as another.  But avoid the broken or
@@ -1047,11 +3428,11 @@
 # 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:1052: checking for a BSD compatible install" >&5
+{ echo "$as_me:$LINENO: checking for a BSD compatible install" >&5
+echo $ECHO_N "checking for a BSD compatible install... $ECHO_C" >&6; }
 if test -z "$INSTALL"; then
-if eval "test \"`echo '$''{'cl_cv_path_install'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
+if test "${cl_cv_path_install+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
 else
     IFS="${IFS= 	}"; ac_save_ifs="$IFS"; IFS="${IFS}:"
   for ac_dir in $PATH; do
@@ -1089,7 +3470,8 @@
 fi
   INSTALL="$cl_cv_path_install"
 fi
-echo "$ac_t""$INSTALL" 1>&6
+{ echo "$as_me:$LINENO: result: $INSTALL" >&5
+echo "${ECHO_T}$INSTALL" >&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)'
@@ -1100,561 +3482,1244 @@
   esac
 fi
 
-                      echo $ac_n "checking for working throw()""... $ac_c" 1>&6
-echo "configure:1105: checking for working throw()" >&5
-if eval "test \"`echo '$''{'gp_cv_cxx_throw_decl'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
+                      { echo "$as_me:$LINENO: checking for stack-allocated variable-size arrays" >&5
+echo $ECHO_N "checking for stack-allocated variable-size arrays... $ECHO_C" >&6; }
+
+if test "${gp_cv_cxx_dynamic_array+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
 else
-  
-
-ac_ext=C
-# CXXFLAGS is not in ac_cpp because -g, -O, etc. are not valid cpp options.
+
+
+ac_ext=cpp
 ac_cpp='$CXXCPP $CPPFLAGS'
-ac_compile='${CXX-g++} -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext 1>&5'
-ac_link='${CXX-g++} -o conftest${ac_exeext} $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS 1>&5'
-cross_compiling=$ac_cv_prog_cxx_cross
-
-cat > conftest.$ac_ext <<EOF
-#line 1119 "configure"
-#include "confdefs.h"
-#include <stdlib.h>
-void operator delete (void* ptr) throw() {}
-int main() {
-
-; return 0; }
-EOF
-if { (eval echo configure:1127: \"$ac_compile\") 1>&5; (eval $ac_compile) 2>&5; }; then
-  rm -rf conftest*
-  gp_cv_cxx_throw_decl=yes
+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
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+int func (int n) { int dynamic_array[n]; }
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compile") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } && {
+	 test -z "$ac_cxx_werror_flag" ||
+	 test ! -s conftest.err
+       } && test -s conftest.$ac_objext; then
+  gp_cv_cxx_dynamic_array=yes
 else
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  rm -rf conftest*
-  gp_cv_cxx_throw_decl=no
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+	gp_cv_cxx_dynamic_array=no
 fi
-rm -f conftest*
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
 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_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
 
 
 fi
 
-echo "$ac_t""$gp_cv_cxx_throw_decl" 1>&6
-if test $gp_cv_cxx_throw_decl = yes; then
-  cat >> confdefs.h <<\EOF
-#define HAVE_THROW_DECL 1
-EOF
+{ echo "$as_me:$LINENO: result: $gp_cv_cxx_dynamic_array" >&5
+echo "${ECHO_T}$gp_cv_cxx_dynamic_array" >&6; }
+if test $gp_cv_cxx_dynamic_array = yes; then
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE_DYNAMIC_ARRAY 1
+_ACEOF
 
 fi
-for ac_hdr in unistd.h sys/time.h sys/resource.h
-do
-ac_safe=`echo "$ac_hdr" | sed 'y%./+-%__p_%'`
-echo $ac_n "checking for $ac_hdr""... $ac_c" 1>&6
-echo "configure:1158: 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
+
+{ echo "$as_me:$LINENO: checking for rand in -lm" >&5
+echo $ECHO_N "checking for rand in -lm... $ECHO_C" >&6; }
+if test "${ac_cv_lib_m_rand+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
 else
-  cat > conftest.$ac_ext <<EOF
-#line 1163 "configure"
-#include "confdefs.h"
-#include <$ac_hdr>
-EOF
-ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
-{ (eval echo configure:1168: \"$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"
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-lm  $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char rand ();
+int
+main ()
+{
+return rand ();
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_link") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } && {
+	 test -z "$ac_c_werror_flag" ||
+	 test ! -s conftest.err
+       } && test -s conftest$ac_exeext &&
+       $as_test_x conftest$ac_exeext; then
+  ac_cv_lib_m_rand=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"
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+	ac_cv_lib_m_rand=no
 fi
-rm -f conftest*
+
+rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
+      conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
 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 <<EOF
-#define $ac_tr_hdr 1
-EOF
- 
+{ echo "$as_me:$LINENO: result: $ac_cv_lib_m_rand" >&5
+echo "${ECHO_T}$ac_cv_lib_m_rand" >&6; }
+if test $ac_cv_lib_m_rand = yes; then
+  GPERF_LIBM="-lm"
 else
-  echo "$ac_t""no" 1>&6
+  GPERF_LIBM=""
 fi
-done
-
-                      if test $ac_cv_header_sys_resource_h = yes; then
-for ac_func in getrlimit
-do
-echo $ac_n "checking for $ac_func""... $ac_c" 1>&6
-echo "configure:1198: 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 <<EOF
-#line 1203 "configure"
-#include "confdefs.h"
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char $ac_func(); below.  */
-#include <assert.h>
-/* 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:1226: \"$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 <<EOF
-#define $ac_tr_func 1
-EOF
- 
-else
-  echo "$ac_t""no" 1>&6
-fi
-done
-
-                      if test $ac_cv_func_getrlimit = yes; then
-for ac_func in setrlimit
-do
-echo $ac_n "checking for $ac_func""... $ac_c" 1>&6
-echo "configure:1254: 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 <<EOF
-#line 1259 "configure"
-#include "confdefs.h"
-/* System header to define __stub macros and hopefully few prototypes,
-    which can conflict with char $ac_func(); below.  */
-#include <assert.h>
-/* 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:1282: \"$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 <<EOF
-#define $ac_tr_func 1
-EOF
- 
-else
-  echo "$ac_t""no" 1>&6
-fi
-done
-
-                      fi
-fi
-trap '' 1 2 15
-cat > confcache <<\EOF
+
+
+ac_config_files="$ac_config_files Makefile"
+
+cat >confcache <<\_ACEOF
 # 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.
+# scripts and configure runs, see configure's option --config-cache.
+# 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.
+# config.status only pays attention to the cache file if you give it
+# the --recheck option to rerun configure.
 #
-EOF
+# `ac_cv_env_foo' variables (set or unset) will be overridden when
+# loading this file, other *unset* `ac_cv_foo' will be assigned the
+# following values.
+
+_ACEOF
+
 # 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.
+# So, we kill variables containing newlines.
 # 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
+(
+  for ac_var in `(set) 2>&1 | sed -n 's/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'`; do
+    eval ac_val=\$$ac_var
+    case $ac_val in #(
+    *${as_nl}*)
+      case $ac_var in #(
+      *_cv_*) { echo "$as_me:$LINENO: WARNING: Cache variable $ac_var contains a newline." >&5
+echo "$as_me: WARNING: Cache variable $ac_var contains a newline." >&2;} ;;
+      esac
+      case $ac_var in #(
+      _ | IFS | as_nl) ;; #(
+      *) $as_unset $ac_var ;;
+      esac ;;
+    esac
+  done
+
+  (set) 2>&1 |
+    case $as_nl`(ac_space=' '; set) 2>&1` in #(
+    *${as_nl}ac_space=\ *)
+      # `set' does not quote correctly, so add quotes (double-quote
+      # substitution turns \\\\ into \\, and sed turns \\ into \).
+      sed -n \
+	"s/'/'\\\\''/g;
+	  s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p"
+      ;; #(
+    *)
+      # `set' quotes correctly as required by POSIX, so do not add quotes.
+      sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p"
+      ;;
+    esac |
+    sort
+) |
+  sed '
+     /^ac_cv_env_/b end
+     t clear
+     :clear
+     s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/
+     t end
+     s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/
+     :end' >>confcache
+if diff "$cache_file" confcache >/dev/null 2>&1; then :; else
+  if test -w "$cache_file"; then
+    test "x$cache_file" != "x/dev/null" &&
+      { echo "$as_me:$LINENO: updating cache $cache_file" >&5
+echo "$as_me: updating cache $cache_file" >&6;}
+    cat confcache >$cache_file
   else
-    echo "not updating unwritable cache $cache_file"
+    { echo "$as_me:$LINENO: not updating unwritable cache $cache_file" >&5
+echo "$as_me: not updating unwritable cache $cache_file" >&6;}
   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'
+DEFS=-DHAVE_CONFIG_H
+
+ac_libobjs=
+ac_ltlibobjs=
+for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue
+  # 1. Remove the extension, and $U if already installed.
+  ac_script='s/\$U\././;s/\.o$//;s/\.obj$//'
+  ac_i=`echo "$ac_i" | sed "$ac_script"`
+  # 2. Prepend LIBOBJDIR.  When used with automake>=1.10 LIBOBJDIR
+  #    will be set to the directory where LIBOBJS objects are built.
+  ac_libobjs="$ac_libobjs \${LIBOBJDIR}$ac_i\$U.$ac_objext"
+  ac_ltlibobjs="$ac_ltlibobjs \${LIBOBJDIR}$ac_i"'$U.lo'
+done
+LIBOBJS=$ac_libobjs
+
+LTLIBOBJS=$ac_ltlibobjs
+
+
+
+: ${CONFIG_STATUS=./config.status}
+ac_clean_files_save=$ac_clean_files
+ac_clean_files="$ac_clean_files $CONFIG_STATUS"
+{ echo "$as_me:$LINENO: creating $CONFIG_STATUS" >&5
+echo "$as_me: creating $CONFIG_STATUS" >&6;}
+cat >$CONFIG_STATUS <<_ACEOF
+#! $SHELL
+# Generated by $as_me.
+# Run this file to recreate the current configuration.
+# Compiler output produced by configure, useful for debugging
+# configure, is in config.log if it exists.
+
+debug=false
+ac_cs_recheck=false
+ac_cs_silent=false
+SHELL=\${CONFIG_SHELL-$SHELL}
+_ACEOF
+
+cat >>$CONFIG_STATUS <<\_ACEOF
+## --------------------- ##
+## M4sh Initialization.  ##
+## --------------------- ##
+
+# Be more Bourne compatible
+DUALCASE=1; export DUALCASE # for MKS sh
+if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
+  emulate sh
+  NULLCMD=:
+  # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
+  # is contrary to our usage.  Disable this feature.
+  alias -g '${1+"$@"}'='"$@"'
+  setopt NO_GLOB_SUBST
+else
+  case `(set -o) 2>/dev/null` in
+  *posix*) set -o posix ;;
+esac
+
 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 <<EOF
-#! /bin/sh
-# Generated automatically by configure.
-# Run this file to recreate the current configuration.
-# This directory was configured as follows,
-# on host `(hostname || uname -n) 2>/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
+
+
+
+# PATH needs CR
+# Avoid depending upon Character Ranges.
+as_cr_letters='abcdefghijklmnopqrstuvwxyz'
+as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
+as_cr_Letters=$as_cr_letters$as_cr_LETTERS
+as_cr_digits='0123456789'
+as_cr_alnum=$as_cr_Letters$as_cr_digits
+
+# The user is always right.
+if test "${PATH_SEPARATOR+set}" != set; then
+  echo "#! /bin/sh" >conf$$.sh
+  echo  "exit 0"   >>conf$$.sh
+  chmod +x conf$$.sh
+  if (PATH="/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then
+    PATH_SEPARATOR=';'
+  else
+    PATH_SEPARATOR=:
+  fi
+  rm -f conf$$.sh
+fi
+
+# Support unset when possible.
+if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then
+  as_unset=unset
+else
+  as_unset=false
+fi
+
+
+# IFS
+# We need space, tab and new line, in precisely that order.  Quoting is
+# there to prevent editors from complaining about space-tab.
+# (If _AS_PATH_WALK were called with IFS unset, it would disable word
+# splitting by setting IFS to empty value.)
+as_nl='
+'
+IFS=" ""	$as_nl"
+
+# Find who we are.  Look in the path if we contain no directory separator.
+case $0 in
+  *[\\/]* ) as_myself=$0 ;;
+  *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
 do
-  case "\$ac_option" in
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+  test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break
+done
+IFS=$as_save_IFS
+
+     ;;
+esac
+# We did not find ourselves, most probably we were run as `sh COMMAND'
+# in which case we are not to be found in the path.
+if test "x$as_myself" = x; then
+  as_myself=$0
+fi
+if test ! -f "$as_myself"; then
+  echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2
+  { (exit 1); exit 1; }
+fi
+
+# Work around bugs in pre-3.0 UWIN ksh.
+for as_var in ENV MAIL MAILPATH
+do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var
+done
+PS1='$ '
+PS2='> '
+PS4='+ '
+
+# NLS nuisances.
+for as_var in \
+  LANG LANGUAGE LC_ADDRESS LC_ALL LC_COLLATE LC_CTYPE LC_IDENTIFICATION \
+  LC_MEASUREMENT LC_MESSAGES LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER \
+  LC_TELEPHONE LC_TIME
+do
+  if (set +x; test -z "`(eval $as_var=C; export $as_var) 2>&1`"); then
+    eval $as_var=C; export $as_var
+  else
+    ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var
+  fi
+done
+
+# Required to use basename.
+if expr a : '\(a\)' >/dev/null 2>&1 &&
+   test "X`expr 00001 : '.*\(...\)'`" = X001; then
+  as_expr=expr
+else
+  as_expr=false
+fi
+
+if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then
+  as_basename=basename
+else
+  as_basename=false
+fi
+
+
+# Name of the executable.
+as_me=`$as_basename -- "$0" ||
+$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
+	 X"$0" : 'X\(//\)$' \| \
+	 X"$0" : 'X\(/\)' \| . 2>/dev/null ||
+echo X/"$0" |
+    sed '/^.*\/\([^/][^/]*\)\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\/\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\/\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+
+# CDPATH.
+$as_unset CDPATH
+
+
+
+  as_lineno_1=$LINENO
+  as_lineno_2=$LINENO
+  test "x$as_lineno_1" != "x$as_lineno_2" &&
+  test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2" || {
+
+  # Create $as_me.lineno as a copy of $as_myself, but with $LINENO
+  # uniformly replaced by the line number.  The first 'sed' inserts a
+  # line-number line after each line using $LINENO; the second 'sed'
+  # does the real work.  The second script uses 'N' to pair each
+  # line-number line with the line containing $LINENO, and appends
+  # trailing '-' during substitution so that $LINENO is not a special
+  # case at line end.
+  # (Raja R Harinath suggested sed '=', and Paul Eggert wrote the
+  # scripts with optimization help from Paolo Bonzini.  Blame Lee
+  # E. McMahon (1931-1989) for sed's syntax.  :-)
+  sed -n '
+    p
+    /[$]LINENO/=
+  ' <$as_myself |
+    sed '
+      s/[$]LINENO.*/&-/
+      t lineno
+      b
+      :lineno
+      N
+      :loop
+      s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/
+      t loop
+      s/-\n.*//
+    ' >$as_me.lineno &&
+  chmod +x "$as_me.lineno" ||
+    { echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2
+   { (exit 1); exit 1; }; }
+
+  # Don't try to exec as it changes $[0], causing all sort of problems
+  # (the dirname of $[0] is not the place where we might find the
+  # original and so on.  Autoconf is especially sensitive to this).
+  . "./$as_me.lineno"
+  # Exit status is that of the last command.
+  exit
+}
+
+
+if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then
+  as_dirname=dirname
+else
+  as_dirname=false
+fi
+
+ECHO_C= ECHO_N= ECHO_T=
+case `echo -n x` in
+-n*)
+  case `echo 'x\c'` in
+  *c*) ECHO_T='	';;	# ECHO_T is single tab character.
+  *)   ECHO_C='\c';;
+  esac;;
+*)
+  ECHO_N='-n';;
+esac
+
+if expr a : '\(a\)' >/dev/null 2>&1 &&
+   test "X`expr 00001 : '.*\(...\)'`" = X001; then
+  as_expr=expr
+else
+  as_expr=false
+fi
+
+rm -f conf$$ conf$$.exe conf$$.file
+if test -d conf$$.dir; then
+  rm -f conf$$.dir/conf$$.file
+else
+  rm -f conf$$.dir
+  mkdir conf$$.dir
+fi
+echo >conf$$.file
+if ln -s conf$$.file conf$$ 2>/dev/null; then
+  as_ln_s='ln -s'
+  # ... but there are two gotchas:
+  # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail.
+  # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable.
+  # In both cases, we have to default to `cp -p'.
+  ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe ||
+    as_ln_s='cp -p'
+elif ln conf$$.file conf$$ 2>/dev/null; then
+  as_ln_s=ln
+else
+  as_ln_s='cp -p'
+fi
+rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file
+rmdir conf$$.dir 2>/dev/null
+
+if mkdir -p . 2>/dev/null; then
+  as_mkdir_p=:
+else
+  test -d ./-p && rmdir ./-p
+  as_mkdir_p=false
+fi
+
+if test -x / >/dev/null 2>&1; then
+  as_test_x='test -x'
+else
+  if ls -dL / >/dev/null 2>&1; then
+    as_ls_L_option=L
+  else
+    as_ls_L_option=
+  fi
+  as_test_x='
+    eval sh -c '\''
+      if test -d "$1"; then
+        test -d "$1/.";
+      else
+	case $1 in
+        -*)set "./$1";;
+	esac;
+	case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in
+	???[sx]*):;;*)false;;esac;fi
+    '\'' sh
+  '
+fi
+as_executable_p=$as_test_x
+
+# Sed expression to map a string onto a valid CPP name.
+as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
+
+# Sed expression to map a string onto a valid variable name.
+as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'"
+
+
+exec 6>&1
+
+# Save the log message, to keep $[0] and so on meaningful, and to
+# report actual input values of CONFIG_FILES etc. instead of their
+# values after options handling.
+ac_log="
+This file was extended by $as_me, which was
+generated by GNU Autoconf 2.61.  Invocation command line was
+
+  CONFIG_FILES    = $CONFIG_FILES
+  CONFIG_HEADERS  = $CONFIG_HEADERS
+  CONFIG_LINKS    = $CONFIG_LINKS
+  CONFIG_COMMANDS = $CONFIG_COMMANDS
+  $ $0 $@
+
+on `(hostname || uname -n) 2>/dev/null | sed 1q`
+"
+
+_ACEOF
+
+cat >>$CONFIG_STATUS <<_ACEOF
+# Files that config.status was made for.
+config_files="$ac_config_files"
+config_headers="$ac_config_headers"
+
+_ACEOF
+
+cat >>$CONFIG_STATUS <<\_ACEOF
+ac_cs_usage="\
+\`$as_me' instantiates files from templates according to the
+current configuration.
+
+Usage: $0 [OPTIONS] [FILE]...
+
+  -h, --help       print this help, then exit
+  -V, --version    print version number and configuration settings, then exit
+  -q, --quiet      do not print progress messages
+  -d, --debug      don't remove temporary files
+      --recheck    update $as_me by reconfiguring in the same conditions
+  --file=FILE[:TEMPLATE]
+		   instantiate the configuration file FILE
+  --header=FILE[:TEMPLATE]
+		   instantiate the configuration header FILE
+
+Configuration files:
+$config_files
+
+Configuration headers:
+$config_headers
+
+Report bugs to <bug-autoconf at gnu.org>."
+
+_ACEOF
+cat >>$CONFIG_STATUS <<_ACEOF
+ac_cs_version="\\
+config.status
+configured by $0, generated by GNU Autoconf 2.61,
+  with options \\"`echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`\\"
+
+Copyright (C) 2006 Free Software Foundation, Inc.
+This config.status script is free software; the Free Software Foundation
+gives unlimited permission to copy, distribute and modify it."
+
+ac_pwd='$ac_pwd'
+srcdir='$srcdir'
+_ACEOF
+
+cat >>$CONFIG_STATUS <<\_ACEOF
+# If no file are specified by the user, then we need to provide default
+# value.  By we need to know if files were specified by the user.
+ac_need_defaults=:
+while test $# != 0
+do
+  case $1 in
+  --*=*)
+    ac_option=`expr "X$1" : 'X\([^=]*\)='`
+    ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'`
+    ac_shift=:
+    ;;
+  *)
+    ac_option=$1
+    ac_optarg=$2
+    ac_shift=shift
+    ;;
+  esac
+
+  case $ac_option in
+  # Handling of the options.
   -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 ;;
+    ac_cs_recheck=: ;;
+  --version | --versio | --versi | --vers | --ver | --ve | --v | -V )
+    echo "$ac_cs_version"; exit ;;
+  --debug | --debu | --deb | --de | --d | -d )
+    debug=: ;;
+  --file | --fil | --fi | --f )
+    $ac_shift
+    CONFIG_FILES="$CONFIG_FILES $ac_optarg"
+    ac_need_defaults=false;;
+  --header | --heade | --head | --hea )
+    $ac_shift
+    CONFIG_HEADERS="$CONFIG_HEADERS $ac_optarg"
+    ac_need_defaults=false;;
+  --he | --h)
+    # Conflict between --help and --header
+    { echo "$as_me: error: ambiguous option: $1
+Try \`$0 --help' for more information." >&2
+   { (exit 1); exit 1; }; };;
+  --help | --hel | -h )
+    echo "$ac_cs_usage"; exit ;;
+  -q | -quiet | --quiet | --quie | --qui | --qu | --q \
+  | -silent | --silent | --silen | --sile | --sil | --si | --s)
+    ac_cs_silent=: ;;
+
+  # This is an error.
+  -*) { echo "$as_me: error: unrecognized option: $1
+Try \`$0 --help' for more information." >&2
+   { (exit 1); exit 1; }; } ;;
+
+  *) ac_config_targets="$ac_config_targets $1"
+     ac_need_defaults=false ;;
+
+  esac
+  shift
+done
+
+ac_configure_extra_args=
+
+if $ac_cs_silent; then
+  exec 6>/dev/null
+  ac_configure_extra_args="$ac_configure_extra_args --silent"
+fi
+
+_ACEOF
+cat >>$CONFIG_STATUS <<_ACEOF
+if \$ac_cs_recheck; then
+  echo "running CONFIG_SHELL=$SHELL $SHELL $0 "$ac_configure_args \$ac_configure_extra_args " --no-create --no-recursion" >&6
+  CONFIG_SHELL=$SHELL
+  export CONFIG_SHELL
+  exec $SHELL "$0"$ac_configure_args \$ac_configure_extra_args --no-create --no-recursion
+fi
+
+_ACEOF
+cat >>$CONFIG_STATUS <<\_ACEOF
+exec 5>>config.log
+{
+  echo
+  sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX
+## Running $as_me. ##
+_ASBOX
+  echo "$ac_log"
+} >&5
+
+_ACEOF
+cat >>$CONFIG_STATUS <<_ACEOF
+_ACEOF
+
+cat >>$CONFIG_STATUS <<\_ACEOF
+
+# Handling of arguments.
+for ac_config_target in $ac_config_targets
+do
+  case $ac_config_target in
+    "config.h") CONFIG_HEADERS="$CONFIG_HEADERS config.h" ;;
+    "Makefile") CONFIG_FILES="$CONFIG_FILES Makefile" ;;
+
+  *) { { echo "$as_me:$LINENO: error: invalid argument: $ac_config_target" >&5
+echo "$as_me: error: invalid argument: $ac_config_target" >&2;}
+   { (exit 1); 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 <<EOF
-
-# Protect against being on the right side of a sed subst in config.status.
-sed 's/%@/@@/; s/@%/@@/; s/%g\$/@g/; /@g\$/s/[\\\\&%]/\\\\&/g;
- s/@@/%@/; s/@@/@%/; s/@g\$/%g/' > 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%@SET_MAKE@%$SET_MAKE%g
-s%@CC@%$CC%g
-s%@CPP@%$CPP%g
-s%@CXX@%$CXX%g
-s%@CXXCPP@%$CXXCPP%g
-s%@INSTALL@%$INSTALL%g
-s%@INSTALL_PROGRAM@%$INSTALL_PROGRAM%g
-s%@INSTALL_DATA@%$INSTALL_DATA%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
+
+# If the user did not use the arguments to specify the items to instantiate,
+# then the envvar interface is used.  Set only those that are not.
+# We use the long form for the default assignment because of an extremely
+# bizarre bug on SunOS 4.1.3.
+if $ac_need_defaults; then
+  test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files
+  test "${CONFIG_HEADERS+set}" = set || CONFIG_HEADERS=$config_headers
+fi
+
+# Have a temporary directory for convenience.  Make it in the build tree
+# simply because there is no reason against having it here, and in addition,
+# creating and moving files from /tmp can sometimes cause problems.
+# Hook for its removal unless debugging.
+# Note that there is a small window in which the directory will not be cleaned:
+# after its creation but before its name has been assigned to `$tmp'.
+$debug ||
+{
+  tmp=
+  trap 'exit_status=$?
+  { test -z "$tmp" || test ! -d "$tmp" || rm -fr "$tmp"; } && exit $exit_status
+' 0
+  trap '{ (exit 1); exit 1; }' 1 2 13 15
+}
+# Create a (secure) tmp directory for tmp files.
+
+{
+  tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` &&
+  test -n "$tmp" && test -d "$tmp"
+}  ||
+{
+  tmp=./conf$$-$RANDOM
+  (umask 077 && mkdir "$tmp")
+} ||
+{
+   echo "$me: cannot create a temporary directory in ." >&2
+   { (exit 1); exit 1; }
+}
+
+#
+# Set up the sed scripts for CONFIG_FILES section.
+#
+
+# No need to generate the scripts if there are no CONFIG_FILES.
+# This happens for instance when ./config.status config.h
+if test -n "$CONFIG_FILES"; then
+
+_ACEOF
+
+
+
+ac_delim='%!_!# '
+for ac_last_try in false false false false false :; do
+  cat >conf$$subs.sed <<_ACEOF
+SHELL!$SHELL$ac_delim
+PATH_SEPARATOR!$PATH_SEPARATOR$ac_delim
+PACKAGE_NAME!$PACKAGE_NAME$ac_delim
+PACKAGE_TARNAME!$PACKAGE_TARNAME$ac_delim
+PACKAGE_VERSION!$PACKAGE_VERSION$ac_delim
+PACKAGE_STRING!$PACKAGE_STRING$ac_delim
+PACKAGE_BUGREPORT!$PACKAGE_BUGREPORT$ac_delim
+exec_prefix!$exec_prefix$ac_delim
+prefix!$prefix$ac_delim
+program_transform_name!$program_transform_name$ac_delim
+bindir!$bindir$ac_delim
+sbindir!$sbindir$ac_delim
+libexecdir!$libexecdir$ac_delim
+datarootdir!$datarootdir$ac_delim
+datadir!$datadir$ac_delim
+sysconfdir!$sysconfdir$ac_delim
+sharedstatedir!$sharedstatedir$ac_delim
+localstatedir!$localstatedir$ac_delim
+includedir!$includedir$ac_delim
+oldincludedir!$oldincludedir$ac_delim
+docdir!$docdir$ac_delim
+infodir!$infodir$ac_delim
+htmldir!$htmldir$ac_delim
+dvidir!$dvidir$ac_delim
+pdfdir!$pdfdir$ac_delim
+psdir!$psdir$ac_delim
+libdir!$libdir$ac_delim
+localedir!$localedir$ac_delim
+mandir!$mandir$ac_delim
+DEFS!$DEFS$ac_delim
+ECHO_C!$ECHO_C$ac_delim
+ECHO_N!$ECHO_N$ac_delim
+ECHO_T!$ECHO_T$ac_delim
+LIBS!$LIBS$ac_delim
+build_alias!$build_alias$ac_delim
+host_alias!$host_alias$ac_delim
+target_alias!$target_alias$ac_delim
+SET_MAKE!$SET_MAKE$ac_delim
+CC!$CC$ac_delim
+CFLAGS!$CFLAGS$ac_delim
+LDFLAGS!$LDFLAGS$ac_delim
+CPPFLAGS!$CPPFLAGS$ac_delim
+ac_ct_CC!$ac_ct_CC$ac_delim
+EXEEXT!$EXEEXT$ac_delim
+OBJEXT!$OBJEXT$ac_delim
+CPP!$CPP$ac_delim
+CXX!$CXX$ac_delim
+CXXFLAGS!$CXXFLAGS$ac_delim
+ac_ct_CXX!$ac_ct_CXX$ac_delim
+CXXCPP!$CXXCPP$ac_delim
+INSTALL!$INSTALL$ac_delim
+INSTALL_PROGRAM!$INSTALL_PROGRAM$ac_delim
+INSTALL_DATA!$INSTALL_DATA$ac_delim
+GPERF_LIBM!$GPERF_LIBM$ac_delim
+LIBOBJS!$LIBOBJS$ac_delim
+LTLIBOBJS!$LTLIBOBJS$ac_delim
+_ACEOF
+
+  if test `sed -n "s/.*$ac_delim\$/X/p" conf$$subs.sed | grep -c X` = 56; then
+    break
+  elif $ac_last_try; then
+    { { echo "$as_me:$LINENO: error: could not make $CONFIG_STATUS" >&5
+echo "$as_me: error: could not make $CONFIG_STATUS" >&2;}
+   { (exit 1); exit 1; }; }
   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`
+    ac_delim="$ac_delim!$ac_delim _$ac_delim!! "
   fi
 done
-if test -z "$ac_sed_cmds"; then
-  ac_sed_cmds=cat
+
+ac_eof=`sed -n '/^CEOF[0-9]*$/s/CEOF/0/p' conf$$subs.sed`
+if test -n "$ac_eof"; then
+  ac_eof=`echo "$ac_eof" | sort -nru | sed 1q`
+  ac_eof=`expr $ac_eof + 1`
 fi
-EOF
-
-cat >> $CONFIG_STATUS <<EOF
-
-CONFIG_FILES=\${CONFIG_FILES-"Makefile"}
-EOF
-cat >> $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" ;;
+
+cat >>$CONFIG_STATUS <<_ACEOF
+cat >"\$tmp/subs-1.sed" <<\CEOF$ac_eof
+/@[a-zA-Z_][a-zA-Z_0-9]*@/!b end
+_ACEOF
+sed '
+s/[,\\&]/\\&/g; s/@/@|#_!!_#|/g
+s/^/s,@/; s/!/@,|#_!!_#|/
+:n
+t n
+s/'"$ac_delim"'$/,g/; t
+s/$/\\/; p
+N; s/^.*\n//; s/[,\\&]/\\&/g; s/@/@|#_!!_#|/g; b n
+' >>$CONFIG_STATUS <conf$$subs.sed
+rm -f conf$$subs.sed
+cat >>$CONFIG_STATUS <<_ACEOF
+:end
+s/|#_!!_#|//g
+CEOF$ac_eof
+_ACEOF
+
+
+# VPATH may cause trouble with some makes, so we remove $(srcdir),
+# ${srcdir} and @srcdir@ from VPATH if srcdir is ".", strip leading and
+# trailing colons and then remove the whole line if VPATH becomes empty
+# (actually we leave an empty line to preserve line numbers).
+if test "x$srcdir" = x.; then
+  ac_vpsub='/^[	 ]*VPATH[	 ]*=/{
+s/:*\$(srcdir):*/:/
+s/:*\${srcdir}:*/:/
+s/:*@srcdir@:*/:/
+s/^\([^=]*=[	 ]*\):*/\1/
+s/:*$//
+s/^[^=]*=[	 ]*$//
+}'
+fi
+
+cat >>$CONFIG_STATUS <<\_ACEOF
+fi # test -n "$CONFIG_FILES"
+
+
+for ac_tag in  :F $CONFIG_FILES  :H $CONFIG_HEADERS
+do
+  case $ac_tag in
+  :[FHLC]) ac_mode=$ac_tag; continue;;
   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" ;;
+  case $ac_mode$ac_tag in
+  :[FHL]*:*);;
+  :L* | :C*:*) { { echo "$as_me:$LINENO: error: Invalid tag $ac_tag." >&5
+echo "$as_me: error: Invalid tag $ac_tag." >&2;}
+   { (exit 1); exit 1; }; };;
+  :[FH]-) ac_tag=-:-;;
+  :[FH]*) ac_tag=$ac_tag:$ac_tag.in;;
   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= ;;
+  ac_save_IFS=$IFS
+  IFS=:
+  set x $ac_tag
+  IFS=$ac_save_IFS
+  shift
+  ac_file=$1
+  shift
+
+  case $ac_mode in
+  :L) ac_source=$1;;
+  :[FH])
+    ac_file_inputs=
+    for ac_f
+    do
+      case $ac_f in
+      -) ac_f="$tmp/stdin";;
+      *) # Look for the file first in the build tree, then in the source tree
+	 # (if the path is not absolute).  The absolute path cannot be DOS-style,
+	 # because $ac_f cannot contain `:'.
+	 test -f "$ac_f" ||
+	   case $ac_f in
+	   [\\/$]*) false;;
+	   *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";;
+	   esac ||
+	   { { echo "$as_me:$LINENO: error: cannot find input file: $ac_f" >&5
+echo "$as_me: error: cannot find input file: $ac_f" >&2;}
+   { (exit 1); exit 1; }; };;
+      esac
+      ac_file_inputs="$ac_file_inputs $ac_f"
+    done
+
+    # Let's still pretend it is `configure' which instantiates (i.e., don't
+    # use $as_me), people would be surprised to read:
+    #    /* config.h.  Generated by config.status.  */
+    configure_input="Generated from "`IFS=:
+	  echo $* | sed 's|^[^:]*/||;s|:[^:]*/|, |g'`" by configure."
+    if test x"$ac_file" != x-; then
+      configure_input="$ac_file.  $configure_input"
+      { echo "$as_me:$LINENO: creating $ac_file" >&5
+echo "$as_me: creating $ac_file" >&6;}
+    fi
+
+    case $ac_tag in
+    *:-:* | *:-) cat >"$tmp/stdin";;
+    esac
+    ;;
   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 <<EOF
-  CONFIG_HEADERS="config.h"
-EOF
-cat >> $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" ;;
+  ac_dir=`$as_dirname -- "$ac_file" ||
+$as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+	 X"$ac_file" : 'X\(//\)[^/]' \| \
+	 X"$ac_file" : 'X\(//\)$' \| \
+	 X"$ac_file" : 'X\(/\)' \| . 2>/dev/null ||
+echo X"$ac_file" |
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)[^/].*/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+  { as_dir="$ac_dir"
+  case $as_dir in #(
+  -*) as_dir=./$as_dir;;
   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
+  test -d "$as_dir" || { $as_mkdir_p && mkdir -p "$as_dir"; } || {
+    as_dirs=
+    while :; do
+      case $as_dir in #(
+      *\'*) as_qdir=`echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #(
+      *) as_qdir=$as_dir;;
+      esac
+      as_dirs="'$as_qdir' $as_dirs"
+      as_dir=`$as_dirname -- "$as_dir" ||
+$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+	 X"$as_dir" : 'X\(//\)[^/]' \| \
+	 X"$as_dir" : 'X\(//\)$' \| \
+	 X"$as_dir" : 'X\(/\)' \| . 2>/dev/null ||
+echo X"$as_dir" |
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)[^/].*/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+      test -d "$as_dir" && break
+    done
+    test -z "$as_dirs" || eval "mkdir $as_dirs"
+  } || test -d "$as_dir" || { { echo "$as_me:$LINENO: error: cannot create directory $as_dir" >&5
+echo "$as_me: error: cannot create directory $as_dir" >&2;}
+   { (exit 1); exit 1; }; }; }
+  ac_builddir=.
+
+case "$ac_dir" in
+.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;
+*)
+  ac_dir_suffix=/`echo "$ac_dir" | sed 's,^\.[\\/],,'`
+  # A ".." for each directory in $ac_dir_suffix.
+  ac_top_builddir_sub=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,/..,g;s,/,,'`
+  case $ac_top_builddir_sub in
+  "") ac_top_builddir_sub=. ac_top_build_prefix= ;;
+  *)  ac_top_build_prefix=$ac_top_builddir_sub/ ;;
+  esac ;;
+esac
+ac_abs_top_builddir=$ac_pwd
+ac_abs_builddir=$ac_pwd$ac_dir_suffix
+# for backward compatibility:
+ac_top_builddir=$ac_top_build_prefix
+
+case $srcdir in
+  .)  # We are building in place.
+    ac_srcdir=.
+    ac_top_srcdir=$ac_top_builddir_sub
+    ac_abs_top_srcdir=$ac_pwd ;;
+  [\\/]* | ?:[\\/]* )  # Absolute name.
+    ac_srcdir=$srcdir$ac_dir_suffix;
+    ac_top_srcdir=$srcdir
+    ac_abs_top_srcdir=$srcdir ;;
+  *) # Relative name.
+    ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix
+    ac_top_srcdir=$ac_top_build_prefix$srcdir
+    ac_abs_top_srcdir=$ac_pwd/$srcdir ;;
+esac
+ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix
+
+
+  case $ac_mode in
+  :F)
+  #
+  # CONFIG_FILE
+  #
+
+_ACEOF
+
+cat >>$CONFIG_STATUS <<\_ACEOF
+# If the template does not know about datarootdir, expand it.
+# FIXME: This hack should be removed a few years after 2.60.
+ac_datarootdir_hack=; ac_datarootdir_seen=
+
+case `sed -n '/datarootdir/ {
+  p
+  q
+}
+/@datadir@/p
+/@docdir@/p
+/@infodir@/p
+/@localedir@/p
+/@mandir@/p
+' $ac_file_inputs` in
+*datarootdir*) ac_datarootdir_seen=yes;;
+*@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*)
+  { echo "$as_me:$LINENO: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5
+echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;}
+_ACEOF
+cat >>$CONFIG_STATUS <<_ACEOF
+  ac_datarootdir_hack='
+  s&@datadir@&$datadir&g
+  s&@docdir@&$docdir&g
+  s&@infodir@&$infodir&g
+  s&@localedir@&$localedir&g
+  s&@mandir@&$mandir&g
+    s&\\\${datarootdir}&$datarootdir&g' ;;
+esac
+_ACEOF
+
+# Neutralize VPATH when `$srcdir' = `.'.
+# Shell code in configure.ac might set extrasub.
+# FIXME: do we really want to maintain this feature?
+cat >>$CONFIG_STATUS <<_ACEOF
+  sed "$ac_vpsub
+$extrasub
+_ACEOF
+cat >>$CONFIG_STATUS <<\_ACEOF
+:t
+/@[a-zA-Z_][a-zA-Z_0-9]*@/!b
+s&@configure_input@&$configure_input&;t t
+s&@top_builddir@&$ac_top_builddir_sub&;t t
+s&@srcdir@&$ac_srcdir&;t t
+s&@abs_srcdir@&$ac_abs_srcdir&;t t
+s&@top_srcdir@&$ac_top_srcdir&;t t
+s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t
+s&@builddir@&$ac_builddir&;t t
+s&@abs_builddir@&$ac_abs_builddir&;t t
+s&@abs_top_builddir@&$ac_abs_top_builddir&;t t
+$ac_datarootdir_hack
+" $ac_file_inputs | sed -f "$tmp/subs-1.sed" >$tmp/out
+
+test -z "$ac_datarootdir_hack$ac_datarootdir_seen" &&
+  { ac_out=`sed -n '/\${datarootdir}/p' "$tmp/out"`; test -n "$ac_out"; } &&
+  { ac_out=`sed -n '/^[	 ]*datarootdir[	 ]*:*=/p' "$tmp/out"`; test -z "$ac_out"; } &&
+  { echo "$as_me:$LINENO: WARNING: $ac_file contains a reference to the variable \`datarootdir'
+which seems to be undefined.  Please make sure it is defined." >&5
+echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir'
+which seems to be undefined.  Please make sure it is defined." >&2;}
+
+  rm -f "$tmp/stdin"
+  case $ac_file in
+  -) cat "$tmp/out"; rm -f "$tmp/out";;
+  *) rm -f "$ac_file"; mv "$tmp/out" $ac_file;;
+  esac
+ ;;
+  :H)
+  #
+  # CONFIG_HEADER
+  #
+_ACEOF
+
+# Transform confdefs.h into a sed script `conftest.defines', that
+# substitutes the proper values into config.h.in to produce config.h.
+rm -f conftest.defines conftest.tail
+# First, append a space to every undef/define line, to ease matching.
+echo 's/$/ /' >conftest.defines
+# Then, protect against being on the right side of a sed subst, or in
+# an unquoted here document, in config.status.  If some macros were
+# called several times there might be several #defines for the same
+# symbol, which is useless.  But do not sort them, since the last
+# AC_DEFINE must be honored.
+ac_word_re=[_$as_cr_Letters][_$as_cr_alnum]*
+# These sed commands are passed to sed as "A NAME B PARAMS C VALUE D", where
+# NAME is the cpp macro being defined, VALUE is the value it is being given.
+# PARAMS is the parameter list in the macro definition--in most cases, it's
+# just an empty string.
+ac_dA='s,^\\([	 #]*\\)[^	 ]*\\([	 ]*'
+ac_dB='\\)[	 (].*,\\1define\\2'
+ac_dC=' '
+ac_dD=' ,'
+
+uniq confdefs.h |
+  sed -n '
+	t rset
+	:rset
+	s/^[	 ]*#[	 ]*define[	 ][	 ]*//
+	t ok
+	d
+	:ok
+	s/[\\&,]/\\&/g
+	s/^\('"$ac_word_re"'\)\(([^()]*)\)[	 ]*\(.*\)/ '"$ac_dA"'\1'"$ac_dB"'\2'"${ac_dC}"'\3'"$ac_dD"'/p
+	s/^\('"$ac_word_re"'\)[	 ]*\(.*\)/'"$ac_dA"'\1'"$ac_dB$ac_dC"'\2'"$ac_dD"'/p
+  ' >>conftest.defines
+
+# Remove the space that was appended to ease matching.
+# Then replace #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
+# (The regexp can be short, since the line contains either #define or #undef.)
+echo 's/ $//
+s,^[	 #]*u.*,/* & */,' >>conftest.defines
+
+# Break up conftest.defines:
+ac_max_sed_lines=50
+
+# First sed command is:	 sed -f defines.sed $ac_file_inputs >"$tmp/out1"
+# Second one is:	 sed -f defines.sed "$tmp/out1" >"$tmp/out2"
+# Third one will be:	 sed -f defines.sed "$tmp/out2" >"$tmp/out1"
+# et cetera.
+ac_in='$ac_file_inputs'
+ac_out='"$tmp/out1"'
+ac_nxt='"$tmp/out2"'
+
 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 <<CEOF' >> $CONFIG_STATUS
-  sed ${ac_max_here_lines}q conftest.vals >> $CONFIG_STATUS
+  # Write a here document:
+    cat >>$CONFIG_STATUS <<_ACEOF
+    # First, check the format of the line:
+    cat >"\$tmp/defines.sed" <<\\CEOF
+/^[	 ]*#[	 ]*undef[	 ][	 ]*$ac_word_re[	 ]*\$/b def
+/^[	 ]*#[	 ]*define[	 ][	 ]*$ac_word_re[(	 ]/b def
+b
+:def
+_ACEOF
+  sed ${ac_max_sed_lines}q conftest.defines >>$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
+    sed -f "$tmp/defines.sed"' "$ac_in >$ac_out" >>$CONFIG_STATUS
+  ac_in=$ac_out; ac_out=$ac_nxt; ac_nxt=$ac_in
+  sed 1,${ac_max_sed_lines}d conftest.defines >conftest.tail
+  grep . conftest.tail >/dev/null || break
+  rm -f conftest.defines
+  mv conftest.tail conftest.defines
 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
+rm -f conftest.defines conftest.tail
+
+echo "ac_result=$ac_in" >>$CONFIG_STATUS
+cat >>$CONFIG_STATUS <<\_ACEOF
+  if test x"$ac_file" != x-; then
+    echo "/* $configure_input  */" >"$tmp/config.h"
+    cat "$ac_result" >>"$tmp/config.h"
+    if diff $ac_file "$tmp/config.h" >/dev/null 2>&1; then
+      { echo "$as_me:$LINENO: $ac_file is unchanged" >&5
+echo "$as_me: $ac_file is unchanged" >&6;}
+    else
+      rm -f $ac_file
+      mv "$tmp/config.h" $ac_file
+    fi
   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
+    echo "/* $configure_input  */"
+    cat "$ac_result"
   fi
-fi; done
-
-EOF
-cat >> $CONFIG_STATUS <<EOF
-
-EOF
-cat >> $CONFIG_STATUS <<\EOF
-
-exit 0
-EOF
+  rm -f "$tmp/out12"
+ ;;
+
+
+  esac
+
+done # for ac_tag
+
+
+{ (exit 0); exit 0; }
+_ACEOF
 chmod +x $CONFIG_STATUS
-rm -fr confdefs* $ac_clean_files
-test "$no_create" = yes || ${CONFIG_SHELL-/bin/sh} $CONFIG_STATUS || exit 1
-
+ac_clean_files=$ac_clean_files_save
+
+
+# configure is writing to config.log, and then calls config.status.
+# config.status does its own redirection, appending to config.log.
+# Unfortunately, on DOS this fails, as config.log is still kept open
+# by configure, so config.status won't be able to write to it; its
+# output is simply discarded.  So we exec the FD to /dev/null,
+# effectively closing config.log, so it can be properly (re)opened and
+# appended to by config.status.  When coming back to configure, we
+# need to make the FD available again.
+if test "$no_create" != yes; then
+  ac_cs_success=:
+  ac_config_status_args=
+  test "$silent" = yes &&
+    ac_config_status_args="$ac_config_status_args --quiet"
+  exec 5>/dev/null
+  $SHELL $CONFIG_STATUS $ac_config_status_args || ac_cs_success=false
+  exec 5>>config.log
+  # Use ||, not &&, to avoid exiting from the if with $? = 1, which
+  # would make configure fail if this is the last instruction.
+  $ac_cs_success || { (exit 1); exit 1; }
+fi
+
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/src/configure.ac
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/contrib/gperf/src/configure.ac	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,68 @@
+dnl autoconf configuration for gperf/src
+
+dnl Copyright (C) 1998, 2000, 2002-2003, 2007 Free Software Foundation, Inc.
+dnl Written by Douglas C. Schmidt <schmidt at ics.uci.edu>
+dnl and Bruno Haible <bruno at clisp.org>.
+dnl
+dnl This file is part of GNU GPERF.
+dnl
+dnl GNU GPERF is free software; you can redistribute it and/or modify
+dnl it under the terms of the GNU General Public License as published by
+dnl the Free Software Foundation; either version 2, or (at your option)
+dnl any later version.
+dnl
+dnl GNU GPERF is distributed in the hope that it will be useful,
+dnl but WITHOUT ANY WARRANTY; without even the implied warranty of
+dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+dnl GNU General Public License for more details.
+dnl
+dnl You should have received a copy of the GNU General Public License
+dnl along with this program; see the file COPYING.
+dnl If not, write to the Free Software Foundation, Inc.,
+dnl 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+
+AC_PREREQ([2.60])
+AC_INIT(main.cc)
+AC_CONFIG_HEADER(config.h)
+AC_PROG_MAKE_SET
+dnl
+dnl           checks for programs
+dnl
+AC_PROG_CC
+                      dnl sets variable CC
+AC_PROG_CPP
+                      dnl sets variable CPP
+AC_PROG_CXX
+                      dnl sets variable CXX
+AC_PROG_CXXCPP
+                      dnl sets variable CXXCPP
+CL_PROG_INSTALL
+                      dnl sets variables INSTALL, INSTALL_DATA, INSTALL_PROGRAM
+dnl
+dnl           checks for compiler characteristics
+dnl
+AC_MSG_CHECKING([for stack-allocated variable-size arrays])
+AC_CACHE_VAL(gp_cv_cxx_dynamic_array, [
+AC_LANG_SAVE()
+AC_LANG_CPLUSPLUS()
+AC_TRY_COMPILE([int func (int n) { int dynamic_array[n]; }], [],
+gp_cv_cxx_dynamic_array=yes, gp_cv_cxx_dynamic_array=no)
+AC_LANG_RESTORE()
+])
+AC_MSG_RESULT($gp_cv_cxx_dynamic_array)
+if test $gp_cv_cxx_dynamic_array = yes; then
+  AC_DEFINE(HAVE_DYNAMIC_ARRAY, 1,
+    [Define if the C++ compiler supports stack-allocated variable-size arrays.])
+fi
+dnl
+dnl           checks for functions and declarations
+dnl
+dnl
+dnl           checks for libraries
+dnl
+AC_CHECK_LIB(m, rand, GPERF_LIBM="-lm", GPERF_LIBM="")
+AC_SUBST(GPERF_LIBM)
+dnl
+dnl           That's it.
+dnl
+AC_OUTPUT(Makefile)
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/src/configure.in
--- a/head/contrib/gperf/src/configure.in	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,71 +0,0 @@
-dnl autoconf configuration for gperf/src
-
-dnl Copyright (C) 1998, 2000 Free Software Foundation, Inc.
-dnl written by Douglas C. Schmidt (schmidt at ics.uci.edu)
-dnl
-dnl This file is part of GNU GPERF.
-dnl
-dnl GNU GPERF is free software; you can redistribute it and/or modify
-dnl it under the terms of the GNU General Public License as published by
-dnl the Free Software Foundation; either version 1, or (at your option)
-dnl any later version.
-dnl
-dnl GNU GPERF is distributed in the hope that it will be useful,
-dnl but WITHOUT ANY WARRANTY; without even the implied warranty of
-dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-dnl GNU General Public License for more details.
-dnl
-dnl You should have received a copy of the GNU General Public License
-dnl along with GNU GPERF; see the file COPYING.  If not, write to the
-dnl Free Software Foundation, 59 Temple Place - Suite 330, Boston,
-dnl MA 02111-1307, USA.
-
-AC_INIT(gen-perf.cc)
-AC_CONFIG_HEADER(config.h)
-AC_PROG_MAKE_SET
-dnl
-dnl           checks for programs
-dnl
-AC_PROG_CC
-                      dnl sets variable CC
-AC_PROG_CPP
-                      dnl sets variable CPP
-AC_PROG_CXX
-                      dnl sets variable CXX
-AC_PROG_CXXCPP
-                      dnl sets variable CXXCPP
-CL_PROG_INSTALL
-                      dnl sets variables INSTALL, INSTALL_DATA, INSTALL_PROGRAM
-dnl
-dnl           checks for compiler characteristics
-dnl
-AC_MSG_CHECKING([for working throw()])
-AC_CACHE_VAL(gp_cv_cxx_throw_decl,[
-AC_LANG_SAVE()
-AC_LANG_CPLUSPLUS()
-AC_TRY_COMPILE([#include <stdlib.h>
-void operator delete (void* ptr) throw() {}], [],
-gp_cv_cxx_throw_decl=yes, gp_cv_cxx_throw_decl=no)
-AC_LANG_RESTORE()
-])
-AC_MSG_RESULT([$]gp_cv_cxx_throw_decl)
-if test [$]gp_cv_cxx_throw_decl = yes; then
-  AC_DEFINE(HAVE_THROW_DECL)
-fi
-dnl
-dnl           checks for functions and declarations
-dnl
-AC_CHECK_HEADERS(unistd.h sys/time.h sys/resource.h)
-                      dnl DEFs HAVE_UNISTD_H, HAVE_SYS_TIME_H, HAVE_SYS_RESOURCE_H
-if test $ac_cv_header_sys_resource_h = yes; then
-AC_CHECK_FUNCS(getrlimit)
-                      dnl DEFS HAVE_GETRLIMIT
-if test $ac_cv_func_getrlimit = yes; then
-AC_CHECK_FUNCS(setrlimit)
-                      dnl DEFS HAVE_SETRLIMIT
-fi
-fi
-dnl
-dnl           That's it.
-dnl
-AC_OUTPUT(Makefile)
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/src/gen-perf.cc
--- a/head/contrib/gperf/src/gen-perf.cc	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,359 +0,0 @@
-/* Provides high-level routines to manipulate the keywork list
-   structures the code generation output.
-   Copyright (C) 1989-1998, 2000 Free Software Foundation, Inc.
-   written by Douglas C. Schmidt (schmidt at ics.uci.edu)
-
-This file is part of GNU GPERF.
-
-GNU GPERF 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 1, or (at your option)
-any later version.
-
-GNU GPERF 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 GPERF; see the file COPYING.  If not, write to the Free
-Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111, USA.  */
-
-#include <stdio.h>
-#include <stdlib.h> /* declares rand(), srand() */
-#include <time.h> /* declares time() */
-#include "options.h"
-#include "gen-perf.h"
-#include "trace.h"
-
-/* Efficiently returns the least power of two greater than or equal to X! */
-#define POW(X) ((!X)?1:(X-=1,X|=X>>1,X|=X>>2,X|=X>>4,X|=X>>8,X|=X>>16,(++X)))
-
-/* Reads input keys, possibly applies the reordering heuristic, sets the
-   maximum associated value size (rounded up to the nearest power of 2),
-   may initialize the associated values array, and determines the maximum
-   hash table size.  Note: using the random numbers is often helpful,
-   though not as deterministic, of course! */
-
-Gen_Perf::Gen_Perf (void)
-{
-  T (Trace t ("Gen_Perf::Gen_Perf");)
-  int asso_value_max;
-  int non_linked_length;
-
-  Key_List::read_keys ();
-  if (option[ORDER])
-    reorder ();
-  asso_value_max    = option.get_asso_max ();
-  non_linked_length = Key_List::keyword_list_length ();
-  num_done          = 1;
-  fewest_collisions = 0;
-  if (asso_value_max == 0)
-    asso_value_max = non_linked_length;
-  else if (asso_value_max > 0)
-    asso_value_max *= non_linked_length;
-  else /* if (asso_value_max < 0) */
-    asso_value_max = non_linked_length / -asso_value_max;
-  option.set_asso_max (POW (asso_value_max));
-
-  if (option[RANDOM])
-    {
-      srand ((long) time (0));
-
-      for (int i = 0; i < ALPHA_SIZE; i++)
-        asso_values[i] = (rand () & asso_value_max - 1);
-    }
-  else
-    {
-      int asso_value = option.initial_value ();
-
-      if (asso_value)           /* Initialize array if user requests non-zero default. */
-        for (int i = ALPHA_SIZE - 1; i >= 0; i--)
-          asso_values[i] = asso_value & option.get_asso_max () - 1;
-    }
-  max_hash_value = Key_List::max_key_length () + option.get_asso_max () *
-    option.get_max_keysig_size ();
-
-  if (option[DEBUG])
-    fprintf (stderr, "total non-linked keys = %d\nmaximum associated value is %d"
-             "\nmaximum size of generated hash table is %d\n",
-             non_linked_length, asso_value_max, max_hash_value);
-}
-
-/* Merge two disjoint hash key multisets to form the ordered disjoint union of the sets.
-   (In a multiset, an element can occur multiple times.)
-   Precondition: both set_1 and set_2 must be ordered. Returns the length
-   of the combined set. */
-
-inline int
-Gen_Perf::compute_disjoint_union  (const char *set_1, int size_1, const char *set_2, int size_2, char *set_3)
-{
-  T (Trace t ("Gen_Perf::compute_disjoint_union");)
-  char *base = set_3;
-
-  while (size_1 > 0 && size_2 > 0)
-    if (*set_1 == *set_2)
-      set_1++, size_1--, set_2++, size_2--;
-    else
-      {
-        char next;
-        if (*set_1 < *set_2)
-          next = *set_1++, size_1--;
-        else
-          next = *set_2++, size_2--;
-        if (set_3 == base || next != set_3[-1])
-          *set_3++ = next;
-      }
-
-  while (size_1 > 0)
-    {
-      char next;
-      next = *set_1++, size_1--;
-      if (set_3 == base || next != set_3[-1])
-        *set_3++ = next;
-    }
-
-  while (size_2 > 0)
-    {
-      char next;
-      next = *set_2++, size_2--;
-      if (set_3 == base || next != set_3[-1])
-        *set_3++ = next;
-    }
-  return set_3 - base;
-}
-
-/* Sort the UNION_SET in increasing frequency of occurrence.
-   This speeds up later processing since we may assume the resulting
-   set (Set_3, in this case), is ordered. Uses insertion sort, since
-   the UNION_SET is typically short. */
-
-inline void
-Gen_Perf::sort_set (char *union_set, int len)
-{
-  T (Trace t ("Gen_Perf::sort_set");)
-  int i, j;
-
-  for (i = 0, j = len - 1; i < j; i++)
-    {
-      int curr;
-      char tmp;
-
-      for (curr = i + 1, tmp = union_set[curr];
-           curr > 0 && occurrences[(unsigned char)tmp] < occurrences[(unsigned char)(union_set[curr-1])];
-           curr--)
-        union_set[curr] = union_set[curr - 1];
-
-      union_set[curr] = tmp;
-    }
-}
-
-/* Generate a key set's hash value. */
-
-inline int
-Gen_Perf::hash (List_Node *key_node)
-{
-  T (Trace t ("Gen_Perf::hash");)
-  int sum = option[NOLENGTH] ? 0 : key_node->key_length;
-
-  const char *p = key_node->char_set;
-  int i = key_node->char_set_length;
-  for (; i > 0; p++, i--)
-      sum += asso_values[(unsigned char)(*p)];
-
-  return key_node->hash_value = sum;
-}
-
-/* Find out how character value change affects successfully hashed items.
-   Returns FALSE if no other hash values are affected, else returns TRUE.
-   Note that because Option.Get_Asso_Max is a power of two we can guarantee
-   that all legal Asso_Values are visited without repetition since
-   Option.Get_Jump was forced to be an odd value! */
-
-inline int
-Gen_Perf::affects_prev (char c, List_Node *curr)
-{
-  T (Trace t ("Gen_Perf::affects_prev");)
-  int original_char = asso_values[(unsigned char)c];
-  int total_iterations = !option[FAST]
-    ? option.get_asso_max () : option.get_iterations () ? option.get_iterations () : keyword_list_length ();
-
-  /* Try all legal associated values. */
-
-  for (int i = total_iterations - 1; i >= 0; i--)
-    {
-      int collisions = 0;
-
-      asso_values[(unsigned char)c] =
-        (asso_values[(unsigned char)c] + (option.get_jump () ? option.get_jump () : rand ()))
-        & (option.get_asso_max () - 1);
-
-      /* Iteration Number array is a win, O(1) intialization time! */
-      reset ();
-
-      /* See how this asso_value change affects previous keywords.  If
-         it does better than before we'll take it! */
-
-      for (List_Node *ptr = head;
-           !Bool_Array::find (hash (ptr)) || ++collisions < fewest_collisions;
-           ptr = ptr->next)
-        if (ptr == curr)
-          {
-            fewest_collisions = collisions;
-            if (option[DEBUG])
-              fprintf (stderr, "- resolved after %d iterations", total_iterations - i);
-            return 0;
-          }
-    }
-
-  /* Restore original values, no more tries. */
-  asso_values[(unsigned char)c] = original_char;
-  /* If we're this far it's time to try the next character.... */
-  return 1;
-}
-
-/* Change a character value, try least-used characters first. */
-
-void
-Gen_Perf::change (List_Node *prior, List_Node *curr)
-{
-  T (Trace t ("Gen_Perf::change");)
-  static char *union_set;
-  int union_set_length;
-
-  if (!union_set)
-    union_set = new char [2 * option.get_max_keysig_size ()];
-
-  if (option[DEBUG])
-    {
-      fprintf (stderr, "collision on keyword #%d, prior = \"%.*s\", curr = \"%.*s\" hash = %d\n",
-               num_done,
-               prior->key_length, prior->key,
-               curr->key_length, curr->key,
-               curr->hash_value);
-      fflush (stderr);
-    }
-  union_set_length = compute_disjoint_union (prior->char_set, prior->char_set_length, curr->char_set, curr->char_set_length, union_set);
-  sort_set (union_set, union_set_length);
-
-  /* Try changing some values, if change doesn't alter other values continue normal action. */
-  fewest_collisions++;
-
-  const char *p = union_set;
-  int i = union_set_length;
-  for (; i > 0; p++, i--)
-    if (!affects_prev (*p, curr))
-      {
-        if (option[DEBUG])
-          {
-            fprintf (stderr, " by changing asso_value['%c'] (char #%td) to %d\n",
-                     *p, p - union_set + 1, asso_values[(unsigned char)(*p)]);
-            fflush (stderr);
-          }
-        return; /* Good, doesn't affect previous hash values, we'll take it. */
-      }
-
-  for (List_Node *ptr = head; ptr != curr; ptr = ptr->next)
-    hash (ptr);
-
-  hash (curr);
-
-  if (option[DEBUG])
-    {
-      fprintf (stderr, "** collision not resolved after %d iterations, %d duplicates remain, continuing...\n",
-               !option[FAST] ? option.get_asso_max () : option.get_iterations () ? option.get_iterations () : keyword_list_length (),
-               fewest_collisions + total_duplicates);
-      fflush (stderr);
-    }
-}
-
-/* Does the hard stuff....
-   Initializes the Iteration Number array, and attempts to find a perfect
-   function that will hash all the key words without getting any
-   duplications.  This is made much easier since we aren't attempting
-   to generate *minimum* functions, only perfect ones.
-   If we can't generate a perfect function in one pass *and* the user
-   hasn't enabled the DUP option, we'll inform the user to try the
-   randomization option, use -D, or choose alternative key positions.
-   The alternatives (e.g., back-tracking) are too time-consuming, i.e,
-   exponential in the number of keys. */
-
-int
-Gen_Perf::operator() (void)
-{
-  T (Trace t ("Gen_Perf::operator()");)
-#if LARGE_STACK_ARRAYS
-  STORAGE_TYPE buffer[max_hash_value + 1];
-#else
-  // Note: we don't use new, because that invokes a custom operator new.
-  STORAGE_TYPE *buffer
-    = (STORAGE_TYPE*) malloc (sizeof(STORAGE_TYPE) * (max_hash_value + 1));
-  if (buffer == NULL)
-    abort ();
-#endif
-
-  Bool_Array::init (buffer, max_hash_value + 1);
-
-  List_Node *curr;
-  for (curr = head; curr; curr = curr->next)
-    {
-      hash (curr);
-
-      for (List_Node *ptr = head; ptr != curr; ptr = ptr->next)
-        if (ptr->hash_value == curr->hash_value)
-          {
-            change (ptr, curr);
-            break;
-          }
-      num_done++;
-    }
-
-  /* Make one final check, just to make sure nothing weird happened.... */
-
-  Bool_Array::reset ();
-
-  for (curr = head; curr; curr = curr->next)
-    if (Bool_Array::find (hash (curr)))
-      if (option[DUP]) /* Keep track of this number... */
-        total_duplicates++;
-      else /* Yow, big problems.  we're outta here! */
-        {
-          fprintf (stderr, "\nInternal error, duplicate value %d:\n"
-                           "try options -D or -r, or use new key positions.\n\n", hash (curr));
-#if !LARGE_STACK_ARRAYS
-          free ((char *) buffer);
-#endif
-          return 1;
-        }
-
-  /* Sorts the key word list by hash value, and then outputs the list.
-     The generated hash table code is only output if the early stage of
-     processing turned out O.K. */
-
-  sort ();
-  output ();
-#if !LARGE_STACK_ARRAYS
-  free ((char *) buffer);
-#endif
-  return 0;
-}
-
-/* Prints out some diagnostics upon completion. */
-
-Gen_Perf::~Gen_Perf (void)
-{
-  T (Trace t ("Gen_Perf::~Gen_Perf");)
-  if (option[DEBUG])
-    {
-      fprintf (stderr, "\ndumping occurrence and associated values tables\n");
-
-      for (int i = 0; i < ALPHA_SIZE; i++)
-        if (occurrences[i])
-          fprintf (stderr, "asso_values[%c] = %6d, occurrences[%c] = %6d\n",
-                   i, asso_values[i], i, occurrences[i]);
-
-      fprintf (stderr, "end table dumping\n");
-
-    }
-}
-
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/src/gen-perf.h
--- a/head/contrib/gperf/src/gen-perf.h	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,50 +0,0 @@
-/* This may look like C code, but it is really -*- C++ -*- */
-
-/* Provides high-level routines to manipulate the keyword list
-   structures the code generation output.
-
-   Copyright (C) 1989-1998, 2000 Free Software Foundation, Inc.
-   written by Douglas C. Schmidt (schmidt at ics.uci.edu)
-
-This file is part of GNU GPERF.
-
-GNU GPERF 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 1, or (at your option)
-any later version.
-
-GNU GPERF 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 GPERF; see the file COPYING.  If not, write to the Free
-Software Foundation, 59 Temple Place - Suite 330, Boston, MA  02111, USA. */
-
-#ifndef gen_perf_h
-#define gen_perf_h 1
-
-#include "key-list.h"
-#include "bool-array.h"
-
-class Gen_Perf : private Key_List, private Bool_Array
-{
-private:
-  int         max_hash_value;    /* Maximum possible hash value. */
-  int         fewest_collisions; /* Records fewest # of collisions for asso value. */
-  int         num_done;          /* Number of keywords processed without a collision. */
-
-  void        change (List_Node *prior, List_Node *curr);
-  int         affects_prev (char c, List_Node *curr);
-  static int  hash (List_Node *key_node);
-  static int  compute_disjoint_union (const char *set_1, int size_1, const char *set_2, int size_2, char *set_3);
-  static void sort_set (char *union_set, int len);
-
-public:
-              Gen_Perf (void);
-             ~Gen_Perf (void);
-  int         operator () (void);
-};
-
-#endif
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/src/hash-table.cc
--- a/head/contrib/gperf/src/hash-table.cc	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/contrib/gperf/src/hash-table.cc	Tue Dec 06 20:26:16 2011 +0200
@@ -1,95 +1,167 @@
 /* Hash table for checking keyword links.  Implemented using double hashing.
-   Copyright (C) 1989-1998, 2000 Free Software Foundation, Inc.
-   written by Douglas C. Schmidt (schmidt at ics.uci.edu)
+   Copyright (C) 1989-1998, 2000, 2002 Free Software Foundation, Inc.
+   Written by Douglas C. Schmidt <schmidt at ics.uci.edu>
+   and Bruno Haible <bruno at clisp.org>.
 
-This file is part of GNU GPERF.
+   This file is part of GNU GPERF.
 
-GNU GPERF 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 1, or (at your option)
-any later version.
+   GNU GPERF 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 GPERF 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.
+   GNU GPERF 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 GPERF; see the file COPYING.  If not, write to the Free
-Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111, USA.  */
+   You should have received a copy of the GNU General Public License
+   along with this program; see the file COPYING.
+   If not, write to the Free Software Foundation, Inc.,
+   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
 
+/* Specification. */
 #include "hash-table.h"
 
 #include <stdio.h>
 #include <string.h> /* declares memset(), strcmp() */
 #include <hash.h>
 #include "options.h"
-#include "trace.h"
 
-/* The size of the hash table is always the smallest power of 2 >= the size
-   indicated by the user.  This allows several optimizations, including
-   the use of double hashing and elimination of the mod instruction.
-   Note that the size had better be larger than the number of items
-   in the hash table, else there's trouble!!!  Note that the memory
-   for the hash table is allocated *outside* the intialization routine.
-   This compromises information hiding somewhat, but greatly reduces
-   memory fragmentation, since we can now use alloca! */
+/* We use a hash table with double hashing.  This is the simplest kind of
+   hash table, given that we always only insert and never remove entries
+   from the hash table.  */
 
-Hash_Table::Hash_Table (List_Node **table_ptr, int s, int ignore_len):
-     table (table_ptr), size (s), collisions (0), ignore_length (ignore_len)
+/* To make double hashing efficient, there need to be enough spare entries.  */
+static const int size_factor = 10;
+
+/* We make the size of the hash table a power of 2.  This allows for two
+   optimizations: It eliminates the modulo instruction, and allows for an
+   easy secondary hashing function.  */
+
+/* Constructor.  */
+Hash_Table::Hash_Table (unsigned int size, bool ignore_length)
+  : _ignore_length (ignore_length),
+    _collisions (0)
 {
-  T (Trace t ("Hash_Table::Hash_Table");)
-  memset ((char *) table, 0, size * sizeof (*table));
+  /* There need to be enough spare entries.  */
+  size = size * size_factor;
+
+  /* Find smallest power of 2 that is >= size.  */
+  unsigned int shift = 0;
+  if ((size >> 16) > 0)
+    {
+      size = size >> 16;
+      shift += 16;
+    }
+  if ((size >> 8) > 0)
+    {
+      size = size >> 8;
+      shift += 8;
+    }
+  if ((size >> 4) > 0)
+    {
+      size = size >> 4;
+      shift += 4;
+    }
+  if ((size >> 2) > 0)
+    {
+      size = size >> 2;
+      shift += 2;
+    }
+  if ((size >> 1) > 0)
+    {
+      size = size >> 1;
+      shift += 1;
+    }
+  _log_size = shift;
+  _size = 1 << shift;
+
+  /* Allocate table.  */
+  _table = new KeywordExt*[_size];
+  memset (_table, 0, _size * sizeof (*_table));
 }
 
-Hash_Table::~Hash_Table (void)
+/* Destructor.  */
+Hash_Table::~Hash_Table ()
 {
-  T (Trace t ("Hash_Table::~Hash_Table");)
-  if (option[DEBUG])
-    {
-      int field_width = option.get_max_keysig_size ();
-
-      fprintf (stderr,
-               "\ndumping the hash table\n"
-               "total available table slots = %d, total bytes = %d, total collisions = %d\n"
-               "location, %*s, keyword\n",
-               size, size * (int) sizeof (*table), collisions,
-               field_width, "keysig");
-
-      for (int i = size - 1; i >= 0; i--)
-        if (table[i])
-          fprintf (stderr, "%8d, %*.*s, %.*s\n",
-                   i,
-                   field_width, table[i]->char_set_length, table[i]->char_set,
-                   table[i]->key_length, table[i]->key);
-
-      fprintf (stderr, "\nend dumping hash table\n\n");
-    }
+  delete[] _table;
 }
 
-/* If the ITEM is already in the hash table return the item found
-   in the table.  Otherwise inserts the ITEM, and returns FALSE.
-   Uses double hashing. */
+/* Print the table's contents.  */
+void
+Hash_Table::dump () const
+{
+  int field_width;
 
-List_Node *
-Hash_Table::insert (List_Node *item)
+  field_width = 0;
+  {
+    for (int i = _size - 1; i >= 0; i--)
+      if (_table[i])
+        if (field_width < _table[i]->_selchars_length)
+          field_width = _table[i]->_selchars_length;
+  }
+
+  fprintf (stderr,
+           "\ndumping the hash table\n"
+           "total available table slots = %d, total bytes = %d, total collisions = %d\n"
+           "location, %*s, keyword\n",
+           _size, _size * static_cast<unsigned int>(sizeof (*_table)),
+           _collisions, field_width, "keysig");
+
+  for (int i = _size - 1; i >= 0; i--)
+    if (_table[i])
+      {
+        fprintf (stderr, "%8d, ", i);
+        if (field_width > _table[i]->_selchars_length)
+          fprintf (stderr, "%*s", field_width - _table[i]->_selchars_length, "");
+        for (int j = 0; j < _table[i]->_selchars_length; j++)
+          putc (_table[i]->_selchars[j], stderr);
+        fprintf (stderr, ", %.*s\n",
+                 _table[i]->_allchars_length, _table[i]->_allchars);
+      }
+
+  fprintf (stderr, "\nend dumping hash table\n\n");
+}
+
+/* Compares two items.  */
+inline bool
+Hash_Table::equal (KeywordExt *item1, KeywordExt *item2) const
 {
-  T (Trace t ("Hash_Table::operator()");)
-  unsigned hash_val  = hashpjw (item->char_set, item->char_set_length);
-  int      probe     = hash_val & (size - 1);
-  int      increment = ((hash_val ^ item->key_length) | 1) & (size - 1);
+  return item1->_selchars_length == item2->_selchars_length
+         && memcmp (item1->_selchars, item2->_selchars,
+                    item2->_selchars_length * sizeof (unsigned int))
+            == 0
+         && (_ignore_length
+             || item1->_allchars_length == item2->_allchars_length);
+}
 
-  while (table[probe])
+/* Attempts to insert ITEM in the table.  If there is already an equal
+   entry in it, returns it.  Otherwise inserts ITEM and returns NULL.  */
+KeywordExt *
+Hash_Table::insert (KeywordExt *item)
+{
+  unsigned hash_val =
+    hashpjw (reinterpret_cast<const unsigned char *>(item->_selchars),
+             item->_selchars_length * sizeof (unsigned int));
+  unsigned int probe = hash_val & (_size - 1);
+  unsigned int increment =
+    (((hash_val >> _log_size)
+      ^ (_ignore_length ? 0 : item->_allchars_length))
+     << 1) + 1;
+  /* Note that because _size is a power of 2 and increment is odd,
+     we have gcd(increment,_size) = 1, which guarantees that we'll find
+     an empty entry during the loop.  */
+
+  while (_table[probe] != NULL)
     {
-      if (table[probe]->char_set_length == item->char_set_length
-          && memcmp (table[probe]->char_set, item->char_set, item->char_set_length) == 0
-          && (ignore_length || table[probe]->key_length == item->key_length))
-        return table[probe];
+      if (equal (_table[probe], item))
+        return _table[probe];
 
-      collisions++;
-      probe = (probe + increment) & (size - 1);
+      _collisions++;
+      probe = (probe + increment) & (_size - 1);
     }
 
-  table[probe] = item;
-  return (List_Node *) 0;
+  _table[probe] = item;
+  return NULL;
 }
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/src/hash-table.h
--- a/head/contrib/gperf/src/hash-table.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/contrib/gperf/src/hash-table.h	Tue Dec 06 20:26:16 2011 +0200
@@ -2,42 +2,65 @@
 
 /* Hash table used to check for duplicate keyword entries.
 
-   Copyright (C) 1989-1998, 2000 Free Software Foundation, Inc.
-   written by Douglas C. Schmidt (schmidt at ics.uci.edu)
+   Copyright (C) 1989-1998, 2000, 2002 Free Software Foundation, Inc.
+   Written by Douglas C. Schmidt <schmidt at ics.uci.edu>
+   and Bruno Haible <bruno at clisp.org>.
 
-This file is part of GNU GPERF.
+   This file is part of GNU GPERF.
 
-GNU GPERF 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 1, or (at your option)
-any later version.
+   GNU GPERF 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 GPERF 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.
+   GNU GPERF 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 GPERF; see the file COPYING.  If not, write to the Free
-Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111, USA.  */
+   You should have received a copy of the GNU General Public License
+   along with this program; see the file COPYING.
+   If not, write to the Free Software Foundation, Inc.,
+   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
 
 #ifndef hash_table_h
 #define hash_table_h 1
 
-#include "list-node.h"
+#include "keyword.h"
+
+/* Hash table of KeywordExt* entries.
+   Two entries are considered equal if their _selchars are the same and
+   - if !ignore_length - if their _allchars_length are the same.  */
 
 class Hash_Table
 {
+public:
+  /* Constructor.
+     size is the maximum number of entries.
+     ignore_length determines a detail in the comparison function.  */
+                        Hash_Table (unsigned int size, bool ignore_length);
+  /* Destructor.  */
+                        ~Hash_Table ();
+  /* Attempts to insert ITEM in the table.  If there is already an equal
+     entry in it, returns it.  Otherwise inserts ITEM and returns NULL.  */
+  KeywordExt *          insert (KeywordExt *item);
+  /* Print the table's contents.  */
+  void                  dump () const;
+
 private:
-  List_Node     **table;      /* Vector of pointers to linked lists of List_Node's. */
-  int             size;       /* Size of the vector. */
-  int             collisions; /* Find out how well our double hashing is working! */
-  int             ignore_length;
+  /* Vector of entries.  */
+  KeywordExt **         _table;
+  /* Size of the vector.  */
+  unsigned int          _size;
+  /* log2(_size).  */
+  unsigned int          _log_size;
+  /* A detail of the comparison function.  */
+  bool const            _ignore_length;
+  /* Statistics: Number of collisions so far.  */
+  unsigned int          _collisions;
 
-public:
-                  Hash_Table (List_Node **t, int s, int ignore_len);
-                 ~Hash_Table (void);
-  List_Node      *insert (List_Node *item);
+  /* Compares two items.  */
+  bool                  equal (KeywordExt *item1, KeywordExt *item2) const;
 };
 
 #endif
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/src/input.cc
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/contrib/gperf/src/input.cc	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,1005 @@
+/* Input routines.
+   Copyright (C) 1989-1998, 2002-2004 Free Software Foundation, Inc.
+   Written by Douglas C. Schmidt <schmidt at ics.uci.edu>
+   and Bruno Haible <bruno at clisp.org>.
+
+   This file is part of GNU GPERF.
+
+   GNU GPERF 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 GPERF 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; see the file COPYING.
+   If not, write to the Free Software Foundation, Inc.,
+   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
+
+/* Specification. */
+#include "input.h"
+
+#include <stdio.h>
+#include <stdlib.h> /* declares exit() */
+#include <string.h> /* declares strncpy(), strchr() */
+#include <limits.h> /* defines UCHAR_MAX etc. */
+#include "options.h"
+#include "getline.h"
+
+Input::Input (FILE *stream, Keyword_Factory *keyword_factory)
+  : _stream (stream), _factory (keyword_factory)
+{
+}
+
+/* Returns a pretty representation of the input file name, for error and
+   warning messages.  */
+static const char *
+pretty_input_file_name ()
+{
+  if (option.get_input_file_name ())
+    return option.get_input_file_name ();
+  else
+    return "(standard input)";
+}
+
+/* Returns true if the given line contains a "%DECL" declaration.  */
+static bool
+is_declaration (const char *line, const char *line_end, unsigned int lineno,
+                const char *decl)
+{
+  /* Skip '%'.  */
+  line++;
+
+  /* Skip DECL.  */
+  for (const char *d = decl; *d; d++)
+    {
+      if (!(line < line_end))
+        return false;
+      if (!(*line == *d || (*d == '-' && *line == '_')))
+        return false;
+      line++;
+    }
+  if (line < line_end
+      && ((*line >= 'A' && *line <= 'Z')
+          || (*line >= 'a' && *line <= 'z')
+          || *line == '-' || *line == '_'))
+    return false;
+
+  /* OK, found DECL.  */
+
+  /* Skip whitespace.  */
+  while (line < line_end && (*line == ' ' || *line == '\t'))
+    line++;
+
+  /* Expect end of line.  */
+  if (line < line_end && *line != '\n')
+    {
+      fprintf (stderr, "%s:%u: junk after declaration\n",
+               pretty_input_file_name (), lineno);
+      exit (1);
+    }
+
+  return true;
+}
+
+/* Tests if the given line contains a "%DECL=ARG" declaration.
+   If yes, it sets *ARGP to the argument, and returns true.
+   Otherwise, it returns false.  */
+static bool
+is_declaration_with_arg (const char *line, const char *line_end,
+                         unsigned int lineno,
+                         const char *decl, char **argp)
+{
+  /* Skip '%'.  */
+  line++;
+
+  /* Skip DECL.  */
+  for (const char *d = decl; *d; d++)
+    {
+      if (!(line < line_end))
+        return false;
+      if (!(*line == *d || (*d == '-' && *line == '_')))
+        return false;
+      line++;
+    }
+  if (line < line_end
+      && ((*line >= 'A' && *line <= 'Z')
+          || (*line >= 'a' && *line <= 'z')
+          || *line == '-' || *line == '_'))
+    return false;
+
+  /* OK, found DECL.  */
+
+  /* Skip '='.  */
+  if (!(line < line_end && *line == '='))
+    {
+      fprintf (stderr, "%s:%u: missing argument in %%%s=ARG declaration.\n",
+               pretty_input_file_name (), lineno, decl);
+      exit (1);
+    }
+  line++;
+
+  /* The next word is the argument.  */
+  char *arg = new char[line_end - line + 1];
+  char *p = arg;
+  while (line < line_end && !(*line == ' ' || *line == '\t' || *line == '\n'))
+    *p++ = *line++;
+  *p = '\0';
+
+  /* Skip whitespace.  */
+  while (line < line_end && (*line == ' ' || *line == '\t'))
+    line++;
+
+  /* Expect end of line.  */
+  if (line < line_end && *line != '\n')
+    {
+      fprintf (stderr, "%s:%u: junk after declaration\n",
+               pretty_input_file_name (), lineno);
+      exit (1);
+    }
+
+  *argp = arg;
+  return true;
+}
+
+/* Tests if the given line contains a "%define DECL ARG" declaration.
+   If yes, it sets *ARGP to the argument, and returns true.
+   Otherwise, it returns false.  */
+static bool
+is_define_declaration (const char *line, const char *line_end,
+                       unsigned int lineno,
+                       const char *decl, char **argp)
+{
+  /* Skip '%'.  */
+  line++;
+
+  /* Skip "define".  */
+  {
+    for (const char *d = "define"; *d; d++)
+      {
+        if (!(line < line_end))
+          return false;
+        if (!(*line == *d))
+          return false;
+        line++;
+      }
+    if (!(line < line_end && (*line == ' ' || *line == '\t')))
+      return false;
+  }
+
+  /* Skip whitespace.  */
+  while (line < line_end && (*line == ' ' || *line == '\t'))
+    line++;
+
+  /* Skip DECL.  */
+  for (const char *d = decl; *d; d++)
+    {
+      if (!(line < line_end))
+        return false;
+      if (!(*line == *d || (*d == '-' && *line == '_')))
+        return false;
+      line++;
+    }
+  if (line < line_end
+      && ((*line >= 'A' && *line <= 'Z')
+          || (*line >= 'a' && *line <= 'z')
+          || *line == '-' || *line == '_'))
+    return false;
+
+  /* OK, found DECL.  */
+
+  /* Skip whitespace.  */
+  if (!(line < line_end && (*line == ' ' || *line == '\t')))
+    {
+      fprintf (stderr, "%s:%u:"
+               " missing argument in %%define %s ARG declaration.\n",
+               pretty_input_file_name (), lineno, decl);
+      exit (1);
+    }
+  do
+    line++;
+  while (line < line_end && (*line == ' ' || *line == '\t'));
+
+  /* The next word is the argument.  */
+  char *arg = new char[line_end - line + 1];
+  char *p = arg;
+  while (line < line_end && !(*line == ' ' || *line == '\t' || *line == '\n'))
+    *p++ = *line++;
+  *p = '\0';
+
+  /* Skip whitespace.  */
+  while (line < line_end && (*line == ' ' || *line == '\t'))
+    line++;
+
+  /* Expect end of line.  */
+  if (line < line_end && *line != '\n')
+    {
+      fprintf (stderr, "%s:%u: junk after declaration\n",
+               pretty_input_file_name (), lineno);
+      exit (1);
+    }
+
+  *argp = arg;
+  return true;
+}
+
+/* Reads the entire input file.  */
+void
+Input::read_input ()
+{
+  /* The input file has the following structure:
+        DECLARATIONS
+        %%
+        KEYWORDS
+        %%
+        ADDITIONAL_CODE
+     Since the DECLARATIONS and the ADDITIONAL_CODE sections are optional,
+     we have to read the entire file in the case there is only one %%
+     separator line, in order to determine whether the structure is
+        DECLARATIONS
+        %%
+        KEYWORDS
+     or
+        KEYWORDS
+        %%
+        ADDITIONAL_CODE
+     When the option -t is given or when the first section contains
+     declaration lines starting with %, we go for the first interpretation,
+     otherwise for the second interpretation.  */
+
+  char *input = NULL;
+  size_t input_size = 0;
+  int input_length = get_delim (&input, &input_size, EOF, _stream);
+  if (input_length < 0)
+    {
+      if (ferror (_stream))
+        fprintf (stderr, "%s: error while reading input file\n",
+                 pretty_input_file_name ());
+      else
+        fprintf (stderr, "%s: The input file is empty!\n",
+                 pretty_input_file_name ());
+      exit (1);
+    }
+
+  /* We use input_end as a limit, in order to cope with NUL bytes in the
+     input.  But note that one trailing NUL byte has been added after
+     input_end, for convenience.  */
+  char *input_end = input + input_length;
+
+  const char *declarations;
+  const char *declarations_end;
+  const char *keywords;
+  const char *keywords_end;
+  unsigned int keywords_lineno;
+
+  /* Break up the input into the three sections.  */
+  {
+    const char *separator[2] = { NULL, NULL };
+    unsigned int separator_lineno[2] = { 0, 0 };
+    int separators = 0;
+    {
+      unsigned int lineno = 1;
+      for (const char *p = input; p < input_end; )
+        {
+          if (p[0] == '%' && p[1] == '%')
+            {
+              separator[separators] = p;
+              separator_lineno[separators] = lineno;
+              if (++separators == 2)
+                break;
+            }
+          lineno++;
+          p = (const char *) memchr (p, '\n', input_end - p);
+          if (p != NULL)
+            p++;
+          else
+            p = input_end;
+        }
+    }
+
+    bool has_declarations;
+    if (separators == 1)
+      {
+        if (option[TYPE])
+          has_declarations = true;
+        else
+          {
+            has_declarations = false;
+            for (const char *p = input; p < separator[0]; )
+              {
+                if (p[0] == '%')
+                  {
+                    has_declarations = true;
+                    break;
+                  }
+                p = (const char *) memchr (p, '\n', separator[0] - p);
+                if (p != NULL)
+                  p++;
+                else
+                  p = separator[0];
+              }
+          }
+      }
+    else
+      has_declarations = (separators > 0);
+
+    if (has_declarations)
+      {
+        declarations = input;
+        declarations_end = separator[0];
+        /* Give a warning if the separator line is nonempty.  */
+        bool nonempty_line = false;
+        const char *p;
+        for (p = declarations_end + 2; p < input_end; )
+          {
+            if (*p == '\n')
+              {
+                p++;
+                break;
+              }
+            if (!(*p == ' ' || *p == '\t'))
+              nonempty_line = true;
+            p++;
+          }
+        if (nonempty_line)
+          fprintf (stderr, "%s:%u: warning: junk after %%%% is ignored\n",
+                   pretty_input_file_name (), separator_lineno[0]);
+        keywords = p;
+        keywords_lineno = separator_lineno[0] + 1;
+      }
+    else
+      {
+        declarations = NULL;
+        declarations_end = NULL;
+        keywords = input;
+        keywords_lineno = 1;
+      }
+
+    if (separators > (has_declarations ? 1 : 0))
+      {
+        keywords_end = separator[separators-1];
+        _verbatim_code = separator[separators-1] + 2;
+        _verbatim_code_end = input_end;
+        _verbatim_code_lineno = separator_lineno[separators-1];
+      }
+    else
+      {
+        keywords_end = input_end;
+        _verbatim_code = NULL;
+        _verbatim_code_end = NULL;
+        _verbatim_code_lineno = 0;
+      }
+  }
+
+  /* Parse the declarations section.  */
+
+  _verbatim_declarations = NULL;
+  _verbatim_declarations_end = NULL;
+  _verbatim_declarations_lineno = 0;
+  _struct_decl = NULL;
+  _struct_decl_lineno = 0;
+  _return_type = NULL;
+  _struct_tag = NULL;
+  {
+    unsigned int lineno = 1;
+    char *struct_decl = NULL;
+    unsigned int *struct_decl_linenos = NULL;
+    unsigned int struct_decl_linecount = 0;
+    for (const char *line = declarations; line < declarations_end; )
+      {
+        const char *line_end;
+        line_end = (const char *) memchr (line, '\n', declarations_end - line);
+        if (line_end != NULL)
+          line_end++;
+        else
+          line_end = declarations_end;
+
+        if (*line == '%')
+          {
+            if (line[1] == '{')
+              {
+                /* Handle %{.  */
+                if (_verbatim_declarations != NULL)
+                  {
+                    fprintf (stderr, "%s:%u:\n%s:%u:"
+                             " only one %%{...%%} section is allowed\n",
+                             pretty_input_file_name (),
+                             _verbatim_declarations_lineno,
+                             pretty_input_file_name (), lineno);
+                    exit (1);
+                  }
+                _verbatim_declarations = line + 2;
+                _verbatim_declarations_lineno = lineno;
+              }
+            else if (line[1] == '}')
+              {
+                /* Handle %}.  */
+                if (_verbatim_declarations == NULL)
+                  {
+                    fprintf (stderr, "%s:%u:"
+                             " %%} outside of %%{...%%} section\n",
+                             pretty_input_file_name (), lineno);
+                    exit (1);
+                  }
+                if (_verbatim_declarations_end != NULL)
+                  {
+                    fprintf (stderr, "%s:%u:"
+                             " %%{...%%} section already closed\n",
+                             pretty_input_file_name (), lineno);
+                    exit (1);
+                  }
+                _verbatim_declarations_end = line;
+                /* Give a warning if the rest of the line is nonempty.  */
+                bool nonempty_line = false;
+                const char *q;
+                for (q = line + 2; q < line_end; q++)
+                  {
+                    if (*q == '\n')
+                      {
+                        q++;
+                        break;
+                      }
+                    if (!(*q == ' ' || *q == '\t'))
+                      nonempty_line = true;
+                  }
+                if (nonempty_line)
+                  fprintf (stderr, "%s:%u:"
+                           " warning: junk after %%} is ignored\n",
+                           pretty_input_file_name (), lineno);
+              }
+            else if (_verbatim_declarations != NULL
+                     && _verbatim_declarations_end == NULL)
+              {
+                fprintf (stderr, "%s:%u:"
+                         " warning: %% directives are ignored"
+                         " inside the %%{...%%} section\n",
+                         pretty_input_file_name (), lineno);
+              }
+            else
+              {
+                char *arg;
+
+                if (is_declaration_with_arg (line, line_end, lineno,
+                                             "delimiters", &arg))
+                  option.set_delimiters (arg);
+                else
+
+                if (is_declaration (line, line_end, lineno, "struct-type"))
+                  option.set (TYPE);
+                else
+
+                if (is_declaration (line, line_end, lineno, "ignore-case"))
+                  option.set (UPPERLOWER);
+                else
+
+                if (is_declaration_with_arg (line, line_end, lineno,
+                                             "language", &arg))
+                  option.set_language (arg);
+                else
+
+                if (is_define_declaration (line, line_end, lineno,
+                                           "slot-name", &arg))
+                  option.set_slot_name (arg);
+                else
+
+                if (is_define_declaration (line, line_end, lineno,
+                                           "initializer-suffix", &arg))
+                  option.set_initializer_suffix (arg);
+                else
+
+                if (is_define_declaration (line, line_end, lineno,
+                                           "hash-function-name", &arg))
+                  option.set_hash_name (arg);
+                else
+
+                if (is_define_declaration (line, line_end, lineno,
+                                           "lookup-function-name", &arg))
+                  option.set_function_name (arg);
+                else
+
+                if (is_define_declaration (line, line_end, lineno,
+                                           "class-name", &arg))
+                  option.set_class_name (arg);
+                else
+
+                if (is_declaration (line, line_end, lineno, "7bit"))
+                  option.set (SEVENBIT);
+                else
+
+                if (is_declaration (line, line_end, lineno, "compare-lengths"))
+                  option.set (LENTABLE);
+                else
+
+                if (is_declaration (line, line_end, lineno, "compare-strncmp"))
+                  option.set (COMP);
+                else
+
+                if (is_declaration (line, line_end, lineno, "readonly-tables"))
+                  option.set (CONST);
+                else
+
+                if (is_declaration (line, line_end, lineno, "enum"))
+                  option.set (ENUM);
+                else
+
+                if (is_declaration (line, line_end, lineno, "includes"))
+                  option.set (INCLUDE);
+                else
+
+                if (is_declaration (line, line_end, lineno, "global-table"))
+                  option.set (GLOBAL);
+                else
+
+                if (is_declaration (line, line_end, lineno, "pic"))
+                  option.set (SHAREDLIB);
+                else
+
+                if (is_define_declaration (line, line_end, lineno,
+                                           "string-pool-name", &arg))
+                  option.set_stringpool_name (arg);
+                else
+
+                if (is_declaration (line, line_end, lineno, "null-strings"))
+                  option.set (NULLSTRINGS);
+                else
+
+                if (is_define_declaration (line, line_end, lineno,
+                                           "word-array-name", &arg))
+                  option.set_wordlist_name (arg);
+                else
+
+                if (is_define_declaration (line, line_end, lineno,
+                                           "length-table-name", &arg))
+                  option.set_lengthtable_name (arg);
+                else
+
+                if (is_declaration_with_arg (line, line_end, lineno,
+                                             "switch", &arg))
+                  {
+                    option.set_total_switches (atoi (arg));
+                    if (option.get_total_switches () <= 0)
+                      {
+                        fprintf (stderr, "%s:%u: number of switches %s"
+                                 " must be a positive number\n",
+                                 pretty_input_file_name (), lineno, arg);
+                        exit (1);
+                      }
+                  }
+                else
+
+                if (is_declaration (line, line_end, lineno, "omit-struct-type"))
+                  option.set (NOTYPE);
+                else
+
+                  {
+                    fprintf (stderr, "%s:%u: unrecognized %% directive\n",
+                             pretty_input_file_name (), lineno);
+                    exit (1);
+                  }
+              }
+          }
+        else if (!(_verbatim_declarations != NULL
+                   && _verbatim_declarations_end == NULL))
+          {
+            /* Append the line to struct_decl.  */
+            size_t old_len = (struct_decl ? strlen (struct_decl) : 0);
+            size_t line_len = line_end - line;
+            size_t new_len = old_len + line_len + 1;
+            char *new_struct_decl = new char[new_len];
+            if (old_len > 0)
+              memcpy (new_struct_decl, struct_decl, old_len);
+            memcpy (new_struct_decl + old_len, line, line_len);
+            new_struct_decl[old_len + line_len] = '\0';
+            if (struct_decl)
+              delete[] struct_decl;
+            struct_decl = new_struct_decl;
+            /* Append the lineno to struct_decl_linenos.  */
+            unsigned int *new_struct_decl_linenos =
+              new unsigned int[struct_decl_linecount + 1];
+            if (struct_decl_linecount > 0)
+              memcpy (new_struct_decl_linenos, struct_decl_linenos,
+                      struct_decl_linecount * sizeof (unsigned int));
+            new_struct_decl_linenos[struct_decl_linecount] = lineno;
+            if (struct_decl_linenos)
+              delete[] struct_decl_linenos;
+            struct_decl_linenos = new_struct_decl_linenos;
+            /* Increment struct_decl_linecount.  */
+            struct_decl_linecount++;
+          }
+        lineno++;
+        line = line_end;
+      }
+    if (_verbatim_declarations != NULL && _verbatim_declarations_end == NULL)
+      {
+        fprintf (stderr, "%s:%u: unterminated %%{ section\n",
+                 pretty_input_file_name (), _verbatim_declarations_lineno);
+        exit (1);
+      }
+
+    /* Determine _struct_decl, _return_type, _struct_tag.  */
+    if (option[TYPE])
+      {
+        if (struct_decl)
+          {
+            /* Drop leading whitespace and comments.  */
+            {
+              char *p = struct_decl;
+              unsigned int *l = struct_decl_linenos;
+              for (;;)
+                {
+                  if (p[0] == ' ' || p[0] == '\t')
+                    {
+                      p++;
+                      continue;
+                    }
+                  if (p[0] == '\n')
+                    {
+                      l++;
+                      p++;
+                      continue;
+                    }
+                  if (p[0] == '/')
+                    {
+                      if (p[1] == '*')
+                        {
+                          /* Skip over ANSI C style comment.  */
+                          p += 2;
+                          while (p[0] != '\0')
+                            {
+                              if (p[0] == '*' && p[1] == '/')
+                                {
+                                  p += 2;
+                                  break;
+                                }
+                              if (p[0] == '\n')
+                                l++;
+                              p++;
+                            }
+                          continue;
+                        }
+                      if (p[1] == '/')
+                        {
+                          /* Skip over ISO C99 or C++ style comment.  */
+                          p += 2;
+                          while (p[0] != '\0' && p[0] != '\n')
+                            p++;
+                          if (p[0] == '\n')
+                            {
+                              l++;
+                              p++;
+                            }
+                          continue;
+                        }
+                    }
+                  break;
+                }
+              if (p != struct_decl)
+                {
+                  size_t len = strlen (p);
+                  char *new_struct_decl = new char[len + 1];
+                  memcpy (new_struct_decl, p, len + 1);
+                  delete[] struct_decl;
+                  struct_decl = new_struct_decl;
+                }
+              _struct_decl_lineno = *l;
+            }
+            /* Drop trailing whitespace.  */
+            for (char *p = struct_decl + strlen (struct_decl); p > struct_decl;)
+              if (p[-1] == '\n' || p[-1] == ' ' || p[-1] == '\t')
+                *--p = '\0';
+              else
+                break;
+          }
+        if (struct_decl == NULL || struct_decl[0] == '\0')
+          {
+            fprintf (stderr, "%s: missing struct declaration"
+                     " for option --struct-type\n",
+                     pretty_input_file_name ());
+            exit (1);
+          }
+        {
+          /* Ensure trailing semicolon.  */
+          size_t old_len = strlen (struct_decl);
+          if (struct_decl[old_len - 1] != ';')
+            {
+              char *new_struct_decl = new char[old_len + 2];
+              memcpy (new_struct_decl, struct_decl, old_len);
+              new_struct_decl[old_len] = ';';
+              new_struct_decl[old_len + 1] = '\0';
+              delete[] struct_decl;
+              struct_decl = new_struct_decl;
+            }
+        }
+        /* Set _struct_decl to the entire declaration.  */
+        _struct_decl = struct_decl;
+        /* Set _struct_tag to the naked "struct something".  */
+        const char *p;
+        for (p = struct_decl; *p && *p != '{' && *p != ';' && *p != '\n'; p++)
+          ;
+        for (; p > struct_decl;)
+          if (p[-1] == '\n' || p[-1] == ' ' || p[-1] == '\t')
+            --p;
+          else
+            break;
+        size_t struct_tag_length = p - struct_decl;
+        char *struct_tag = new char[struct_tag_length + 1];
+        memcpy (struct_tag, struct_decl, struct_tag_length);
+        struct_tag[struct_tag_length] = '\0';
+        _struct_tag = struct_tag;
+        /* The return type of the lookup function is "struct something *".
+           No "const" here, because if !option[CONST], some user code might
+           want to modify the structure. */
+        char *return_type = new char[struct_tag_length + 3];
+        memcpy (return_type, struct_decl, struct_tag_length);
+        return_type[struct_tag_length] = ' ';
+        return_type[struct_tag_length + 1] = '*';
+        return_type[struct_tag_length + 2] = '\0';
+        _return_type = return_type;
+      }
+
+    if (struct_decl_linenos)
+      delete[] struct_decl_linenos;
+  }
+
+  /* Parse the keywords section.  */
+  {
+    Keyword_List **list_tail = &_head;
+    const char *delimiters = option.get_delimiters ();
+    unsigned int lineno = keywords_lineno;
+    bool charset_dependent = false;
+    for (const char *line = keywords; line < keywords_end; )
+      {
+        const char *line_end;
+        line_end = (const char *) memchr (line, '\n', keywords_end - line);
+        if (line_end != NULL)
+          line_end++;
+        else
+          line_end = keywords_end;
+
+        if (line[0] == '#')
+          ; /* Comment line.  */
+        else if (line[0] == '%')
+          {
+            fprintf (stderr, "%s:%u:"
+                     " declarations are not allowed in the keywords section.\n"
+                     "To declare a keyword starting with %%, enclose it in"
+                     " double-quotes.\n",
+                     pretty_input_file_name (), lineno);
+            exit (1);
+          }
+        else
+          {
+            /* An input line carrying a keyword.  */
+            const char *keyword;
+            size_t keyword_length;
+            const char *rest;
+
+            if (line[0] == '"')
+              {
+                /* Parse a string in ANSI C syntax.  */
+                char *kp = new char[line_end-line];
+                keyword = kp;
+                const char *lp = line + 1;
+
+                for (;;)
+                  {
+                    if (lp == line_end)
+                      {
+                        fprintf (stderr, "%s:%u: unterminated string\n",
+                                 pretty_input_file_name (), lineno);
+                        exit (1);
+                      }
+
+                    char c = *lp;
+                    if (c == '\\')
+                      {
+                        c = *++lp;
+                        switch (c)
+                          {
+                          case '0': case '1': case '2': case '3':
+                          case '4': case '5': case '6': case '7':
+                            {
+                              int code = 0;
+                              int count = 0;
+                              while (count < 3 && *lp >= '0' && *lp <= '7')
+                                {
+                                  code = (code << 3) + (*lp - '0');
+                                  lp++;
+                                  count++;
+                                }
+                              if (code > UCHAR_MAX)
+                                fprintf (stderr,
+                                         "%s:%u: octal escape out of range\n",
+                                         pretty_input_file_name (), lineno);
+                              *kp = static_cast<char>(code);
+                              break;
+                            }
+                          case 'x':
+                            {
+                              int code = 0;
+                              int count = 0;
+                              lp++;
+                              while ((*lp >= '0' && *lp <= '9')
+                                     || (*lp >= 'A' && *lp <= 'F')
+                                     || (*lp >= 'a' && *lp <= 'f'))
+                                {
+                                  code = (code << 4)
+                                         + (*lp >= 'A' && *lp <= 'F'
+                                            ? *lp - 'A' + 10 :
+                                            *lp >= 'a' && *lp <= 'f'
+                                            ? *lp - 'a' + 10 :
+                                            *lp - '0');
+                                  lp++;
+                                  count++;
+                                }
+                              if (count == 0)
+                                fprintf (stderr, "%s:%u: hexadecimal escape"
+                                         " without any hex digits\n",
+                                         pretty_input_file_name (), lineno);
+                              if (code > UCHAR_MAX)
+                                fprintf (stderr, "%s:%u: hexadecimal escape"
+                                         " out of range\n",
+                                         pretty_input_file_name (), lineno);
+                              *kp = static_cast<char>(code);
+                              break;
+                            }
+                          case '\\': case '\'': case '"':
+                            *kp = c;
+                            lp++;
+                            charset_dependent = true;
+                            break;
+                          case 'n':
+                            *kp = '\n';
+                            lp++;
+                            charset_dependent = true;
+                            break;
+                          case 't':
+                            *kp = '\t';
+                            lp++;
+                            charset_dependent = true;
+                            break;
+                          case 'r':
+                            *kp = '\r';
+                            lp++;
+                            charset_dependent = true;
+                            break;
+                          case 'f':
+                            *kp = '\f';
+                            lp++;
+                            charset_dependent = true;
+                            break;
+                          case 'b':
+                            *kp = '\b';
+                            lp++;
+                            charset_dependent = true;
+                            break;
+                          case 'a':
+                            *kp = '\a';
+                            lp++;
+                            charset_dependent = true;
+                            break;
+                          case 'v':
+                            *kp = '\v';
+                            lp++;
+                            charset_dependent = true;
+                            break;
+                          default:
+                            fprintf (stderr, "%s:%u: invalid escape sequence"
+                                     " in string\n",
+                                     pretty_input_file_name (), lineno);
+                            exit (1);
+                          }
+                      }
+                    else if (c == '"')
+                      break;
+                    else
+                      {
+                        *kp = c;
+                        lp++;
+                        charset_dependent = true;
+                      }
+                    kp++;
+                  }
+                lp++;
+                if (lp < line_end && *lp != '\n')
+                  {
+                    if (strchr (delimiters, *lp) == NULL)
+                      {
+                        fprintf (stderr, "%s:%u: string not followed"
+                                 " by delimiter\n",
+                                 pretty_input_file_name (), lineno);
+                        exit (1);
+                      }
+                    lp++;
+                  }
+                keyword_length = kp - keyword;
+                if (option[TYPE])
+                  {
+                    char *line_rest = new char[line_end - lp + 1];
+                    memcpy (line_rest, lp, line_end - lp);
+                    line_rest[line_end - lp -
+                              (line_end > lp && line_end[-1] == '\n' ? 1 : 0)]
+                      = '\0';
+                    rest = line_rest;
+                  }
+                else
+                  rest = empty_string;
+              }
+            else
+              {
+                /* Not a string.  Look for the delimiter.  */
+                const char *lp = line;
+                for (;;)
+                  {
+                    if (!(lp < line_end && *lp != '\n'))
+                      {
+                        keyword = line;
+                        keyword_length = lp - line;
+                        rest = empty_string;
+                        break;
+                      }
+                    if (strchr (delimiters, *lp) != NULL)
+                      {
+                        keyword = line;
+                        keyword_length = lp - line;
+                        lp++;
+                        if (option[TYPE])
+                          {
+                            char *line_rest = new char[line_end - lp + 1];
+                            memcpy (line_rest, lp, line_end - lp);
+                            line_rest[line_end - lp -
+                                      (line_end > lp && line_end[-1] == '\n'
+                                       ? 1 : 0)]
+                              = '\0';
+                            rest = line_rest;
+                          }
+                        else
+                          rest = empty_string;
+                        break;
+                      }
+                    lp++;
+                  }
+                if (keyword_length > 0)
+                  charset_dependent = true;
+              }
+
+            /* Allocate Keyword and add it to the list.  */
+            Keyword *new_kw = _factory->create_keyword (keyword, keyword_length,
+                                                        rest);
+            new_kw->_lineno = lineno;
+            *list_tail = new Keyword_List (new_kw);
+            list_tail = &(*list_tail)->rest();
+          }
+
+        lineno++;
+        line = line_end;
+      }
+    *list_tail = NULL;
+
+    if (_head == NULL)
+      {
+        fprintf (stderr, "%s: No keywords in input file!\n",
+                 pretty_input_file_name ());
+        exit (1);
+      }
+
+    _charset_dependent = charset_dependent;
+  }
+
+  /* To be freed in the destructor.  */
+  _input = input;
+  _input_end = input_end;
+}
+
+Input::~Input ()
+{
+  /* Free allocated memory.  */
+  delete[] const_cast<char*>(_return_type);
+  delete[] const_cast<char*>(_struct_tag);
+  delete[] const_cast<char*>(_struct_decl);
+  delete[] _input;
+}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/src/input.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/contrib/gperf/src/input.h	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,69 @@
+/* This may look like C code, but it is really -*- C++ -*- */
+
+/* Input routines.
+
+   Copyright (C) 1989-1998, 2002-2003 Free Software Foundation, Inc.
+   Written by Douglas C. Schmidt <schmidt at ics.uci.edu>
+   and Bruno Haible <bruno at clisp.org>.
+
+   This file is part of GNU GPERF.
+
+   GNU GPERF 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 GPERF 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; see the file COPYING.
+   If not, write to the Free Software Foundation, Inc.,
+   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
+
+#ifndef input_h
+#define input_h 1
+
+#include <stdio.h>
+#include "keyword-list.h"
+
+class Input
+{
+public:
+                        Input (FILE *stream, Keyword_Factory *keyword_factory);
+                        ~Input ();
+  void                  read_input ();
+private:
+  /* Input stream.  */
+  FILE *                _stream;
+  /* Creates the keywords.  */
+  Keyword_Factory * const _factory;
+public:
+  /* Memory block containing the entire input.  */
+  char *                _input;
+  char *                _input_end;
+  /* The C code from the declarations section.  */
+  const char *          _verbatim_declarations;
+  const char *          _verbatim_declarations_end;
+  unsigned int          _verbatim_declarations_lineno;
+  /* The C code from the end of the file.  */
+  const char *          _verbatim_code;
+  const char *          _verbatim_code_end;
+  unsigned int          _verbatim_code_lineno;
+  /* Declaration of struct type for a keyword and its attributes.  */
+  const char *          _struct_decl;
+  unsigned int          _struct_decl_lineno;
+  /* Return type of the lookup function.  */
+  const char *          _return_type;
+  /* Shorthand for user-defined struct tag type.  */
+  const char *          _struct_tag;
+  /* List of all keywords.  */
+  Keyword_List *        _head;
+  /* Whether the keyword chars would have different values in a different
+     character set.  */
+  bool                  _charset_dependent;
+};
+
+#endif
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/src/iterator.cc
--- a/head/contrib/gperf/src/iterator.cc	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,87 +0,0 @@
-/* Provides an Iterator for keyword characters.
-   Copyright (C) 1989-1998, 2000 Free Software Foundation, Inc.
-   written by Douglas C. Schmidt (schmidt at ics.uci.edu)
-
-This file is part of GNU GPERF.
-
-GNU GPERF 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 1, or (at your option)
-any later version.
-
-GNU GPERF 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 GPERF; see the file COPYING.  If not, write to the Free
-Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111, USA.  */
-
-#include "iterator.h"
-
-#include <ctype.h>
-#include "trace.h"
-
-/* Constructor for Iterator. */
-
-Iterator::Iterator (const char *s, int lo, int hi, int word_end, int bad_val, int key_end)
-{
-  T (Trace t ("Iterator::Iterator");)
-  end         = key_end;
-  error_value = bad_val;
-  end_word    = word_end;
-  str         = s;
-  hi_bound    = hi;
-  lo_bound    = lo;
-}
-
-/* Provide an Iterator, returning the ``next'' value from
-   the list of valid values given in the constructor. */
-
-int
-Iterator::operator() (void)
-{
-  T (Trace t ("Iterator::operator()");)
-/* Variables to record the Iterator's status when handling ranges, e.g., 3-12. */
-
-  static int size;
-  static int curr_value;
-  static int upper_bound;
-
-  if (size)
-    {
-      if (++curr_value >= upper_bound)
-        size = 0;
-      return curr_value;
-    }
-  else
-    {
-      while (*str)
-        switch (*str)
-          {
-          default: return error_value;
-          case ',': str++; break;
-          case '$': str++; return end_word;
-          case '0': case '1': case '2': case '3': case '4':
-          case '5': case '6': case '7': case '8': case '9':
-            for (curr_value = 0; isdigit ((unsigned char)(*str)); str++)
-              curr_value = curr_value * 10 + (*str - '0');
-
-            if (*str == '-')
-              {
-
-                for (size = 1, upper_bound = 0;
-                     isdigit ((unsigned char)(*++str));
-                     upper_bound = upper_bound * 10 + (*str - '0'));
-
-                if (upper_bound <= curr_value || upper_bound > hi_bound)
-                  return error_value;
-              }
-            return curr_value >= lo_bound && curr_value <= hi_bound
-              ? curr_value : error_value;
-          }
-
-      return end;
-    }
-}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/src/iterator.h
--- a/head/contrib/gperf/src/iterator.h	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,51 +0,0 @@
-/* This may look like C code, but it is really -*- C++ -*- */
-
-/* Provides an Iterator for keyword characters.
-
-   Copyright (C) 1989-1998 Free Software Foundation, Inc.
-   written by Douglas C. Schmidt (schmidt at ics.uci.edu)
-
-This file is part of GNU GPERF.
-
-GNU GPERF 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 1, or (at your option)
-any later version.
-
-GNU GPERF 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 GPERF; see the file COPYING.  If not, write to the Free
-Software Foundation, 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.  */
-
-/* Provides an Iterator that expands and decodes a control string containing digits
-   and ranges, returning an integer every time the generator function is called.
-   This is used to decode the user's key position requests.  For example:
-   "-k 1,2,5-10,$"  will return 1, 2, 5, 6, 7, 8, 9, 10, and 0 ( representing
-   the abstract ``last character of the key'' on successive calls to the
-   member function operator ().
-   No errors are handled in these routines, they are passed back to the
-   calling routines via a user-supplied Error_Value */
-
-#ifndef iterator_h
-#define iterator_h 1
-
-class Iterator
-{
-private:
-  const char *str;              /* A pointer to the string provided by the user. */
-  int   end;                    /* Value returned after last key is processed. */
-  int   end_word;               /* A value marking the abstract ``end of word'' ( usually '$'). */
-  int   error_value;            /* Error value returned when input is syntactically erroneous. */
-  int   hi_bound;               /* Greatest possible value, inclusive. */
-  int   lo_bound;               /* Smallest possible value, inclusive. */
-
-public:
-        Iterator (const char *s, int lo, int hi, int word_end, int bad_val, int key_end);
-  int   operator () (void);
-};
-
-#endif
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/src/key-list.cc
--- a/head/contrib/gperf/src/key-list.cc	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,2182 +0,0 @@
-/* Routines for building, ordering, and printing the keyword list.
-   Copyright (C) 1989-1998, 2000 Free Software Foundation, Inc.
-   written by Douglas C. Schmidt (schmidt at ics.uci.edu)
-
-This file is part of GNU GPERF.
-
-GNU GPERF 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 1, or (at your option)
-any later version.
-
-GNU GPERF 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 GPERF; see the file COPYING.  If not, write to the Free
-Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111, USA.  */
-
-#include <stdio.h>
-#include <string.h> /* declares strncpy(), strchr() */
-#include <stdlib.h> /* declares malloc(), free(), abs(), exit(), abort() */
-#include <ctype.h>  /* declares isprint() */
-#include <assert.h> /* defines assert() */
-#include <limits.h> /* defines SCHAR_MAX etc. */
-#include "options.h"
-#include "read-line.h"
-#include "hash-table.h"
-#include "key-list.h"
-#include "trace.h"
-#include "version.h"
-
-/* Make the hash table 8 times larger than the number of keyword entries. */
-static const int TABLE_MULTIPLE     = 10;
-
-/* Efficiently returns the least power of two greater than or equal to X! */
-#define POW(X) ((!X)?1:(X-=1,X|=X>>1,X|=X>>2,X|=X>>4,X|=X>>8,X|=X>>16,(++X)))
-
-int Key_List::determined[MAX_ALPHA_SIZE];
-
-/* Destructor dumps diagnostics during debugging. */
-
-Key_List::~Key_List (void)
-{
-  T (Trace t ("Key_List::~Key_List");)
-  if (option[DEBUG])
-    {
-      fprintf (stderr, "\nDumping key list information:\ntotal non-static linked keywords = %d"
-               "\ntotal keywords = %d\ntotal duplicates = %d\nmaximum key length = %d\n",
-               list_len, total_keys, total_duplicates, max_key_len);
-      dump ();
-      fprintf (stderr, "End dumping list.\n\n");
-    }
-}
-
-/* Gathers the input stream into a buffer until one of two things occur:
-
-   1. We read a '%' followed by a '%'
-   2. We read a '%' followed by a '}'
-
-   The first symbolizes the beginning of the keyword list proper,
-   The second symbolizes the end of the C source code to be generated
-   verbatim in the output file.
-
-   I assume that the keys are separated from the optional preceding struct
-   declaration by a consecutive % followed by either % or } starting in
-   the first column. The code below uses an expandible buffer to scan off
-   and return a pointer to all the code (if any) appearing before the delimiter. */
-
-const char *
-Key_List::get_special_input (char delimiter)
-{
-  T (Trace t ("Key_List::get_special_input");)
-  int size  = 80;
-  char *buf = new char[size];
-  int c, i;
-
-  for (i = 0; (c = getchar ()) != EOF; i++)
-    {
-      if (c == '%')
-        {
-          if ((c = getchar ()) == delimiter)
-            {
-
-              while ((c = getchar ()) != '\n')
-                ; /* discard newline */
-
-              if (i == 0)
-                return "";
-              else
-                {
-                  buf[delimiter == '%' && buf[i - 2] == ';' ? i - 2 : i - 1] = '\0';
-                  return buf;
-                }
-            }
-          else
-            buf[i++] = '%';
-        }
-      else if (i >= size) /* Yikes, time to grow the buffer! */
-        {
-          char *temp = new char[size *= 2];
-          int j;
-
-          for (j = 0; j < i; j++)
-            temp[j] = buf[j];
-
-          buf = temp;
-        }
-      buf[i] = c;
-    }
-
-  return 0;        /* Problem here. */
-}
-
-/* Stores any C text that must be included verbatim into the
-   generated code output. */
-
-const char *
-Key_List::save_include_src (void)
-{
-  T (Trace t ("Key_List::save_include_src");)
-  int c;
-
-  if ((c = getchar ()) != '%')
-    ungetc (c, stdin);
-  else if ((c = getchar ()) != '{')
-    {
-      fprintf (stderr, "internal error, %c != '{' on line %d in file %s", c, __LINE__, __FILE__);
-      exit (1);
-    }
-  else
-    return get_special_input ('}');
-  return "";
-}
-
-/* Determines from the input file whether the user wants to build a table
-   from a user-defined struct, or whether the user is content to simply
-   use the default array of keys. */
-
-const char *
-Key_List::get_array_type (void)
-{
-  T (Trace t ("Key_List::get_array_type");)
-  return get_special_input ('%');
-}
-
-/* strcspn - find length of initial segment of S consisting entirely
-   of characters not from REJECT (borrowed from Henry Spencer's
-   ANSI string package, when GNU libc comes out I'll replace this...). */
-
-#ifndef strcspn
-inline int
-Key_List::strcspn (const char *s, const char *reject)
-{
-  T (Trace t ("Key_List::strcspn");)
-  const char *scan;
-  const char *rej_scan;
-  int   count = 0;
-
-  for (scan = s; *scan; scan++)
-    {
-
-      for (rej_scan = reject; *rej_scan; rej_scan++)
-        if (*scan == *rej_scan)
-          return count;
-
-      count++;
-    }
-
-  return count;
-}
-#endif
-
-/* Sets up the Return_Type, the Struct_Tag type and the Array_Type
-   based upon various user Options. */
-
-void
-Key_List::set_output_types (void)
-{
-  T (Trace t ("Key_List::set_output_types");)
-  if (option[TYPE])
-    {
-      array_type = get_array_type ();
-      if (!array_type)
-        /* Something's wrong, but we'll catch it later on, in read_keys()... */
-        return;
-      /* Yow, we've got a user-defined type... */
-      int i = strcspn (array_type, "{\n\0");
-      /* Remove trailing whitespace. */
-      while (i > 0 && strchr (" \t", array_type[i-1]))
-        i--;
-      int struct_tag_length = i;
-
-      /* Set `struct_tag' to a naked "struct something". */
-      char *structtag = new char[struct_tag_length + 1];
-      strncpy (structtag, array_type, struct_tag_length);
-      structtag[struct_tag_length] = '\0';
-      struct_tag = structtag;
-
-      /* The return type of the lookup function is "struct something *".
-         No "const" here, because if !option[CONST], some user code might want
-         to modify the structure. */
-      char *rettype = new char[struct_tag_length + 3];
-      strncpy (rettype, array_type, struct_tag_length);
-      rettype[struct_tag_length] = ' ';
-      rettype[struct_tag_length + 1] = '*';
-      rettype[struct_tag_length + 2] = '\0';
-      return_type = rettype;
-    }
-}
-
-/* Extracts a key from an input line and creates a new List_Node for it. */
-
-static List_Node *
-parse_line (const char *line, const char *delimiters)
-{
-  if (*line == '"')
-    {
-      /* Parse a string in ANSI C syntax. */
-      char *key = new char[strlen(line)];
-      char *kp = key;
-      const char *lp = line + 1;
-
-      for (; *lp;)
-        {
-          char c = *lp;
-
-          if (c == '\0')
-            {
-              fprintf (stderr, "unterminated string: %s\n", line);
-              exit (1);
-            }
-          else if (c == '\\')
-            {
-              c = *++lp;
-              switch (c)
-                {
-                case '0': case '1': case '2': case '3':
-                case '4': case '5': case '6': case '7':
-                  {
-                    int code = 0;
-                    int count = 0;
-                    while (count < 3 && *lp >= '0' && *lp <= '7')
-                      {
-                        code = (code << 3) + (*lp - '0');
-                        lp++;
-                        count++;
-                      }
-                    if (code > UCHAR_MAX)
-                      fprintf (stderr, "octal escape out of range: %s\n", line);
-                    *kp = (char) code;
-                    break;
-                  }
-                case 'x':
-                  {
-                    int code = 0;
-                    int count = 0;
-                    lp++;
-                    while ((*lp >= '0' && *lp <= '9')
-                           || (*lp >= 'A' && *lp <= 'F')
-                           || (*lp >= 'a' && *lp <= 'f'))
-                      {
-                        code = (code << 4)
-                               + (*lp >= 'A' && *lp <= 'F' ? *lp - 'A' + 10 :
-                                  *lp >= 'a' && *lp <= 'f' ? *lp - 'a' + 10 :
-                                  *lp - '0');
-                        lp++;
-                        count++;
-                      }
-                    if (count == 0)
-                      fprintf (stderr, "hexadecimal escape without any hex digits: %s\n", line);
-                    if (code > UCHAR_MAX)
-                      fprintf (stderr, "hexadecimal escape out of range: %s\n", line);
-                    *kp = (char) code;
-                    break;
-                  }
-                case '\\': case '\'': case '"':
-                  *kp = c;
-                  lp++;
-                  break;
-                case 'n':
-                  *kp = '\n';
-                  lp++;
-                  break;
-                case 't':
-                  *kp = '\t';
-                  lp++;
-                  break;
-                case 'r':
-                  *kp = '\r';
-                  lp++;
-                  break;
-                case 'f':
-                  *kp = '\f';
-                  lp++;
-                  break;
-                case 'b':
-                  *kp = '\b';
-                  lp++;
-                  break;
-                case 'a':
-                  *kp = '\a';
-                  lp++;
-                  break;
-                case 'v':
-                  *kp = '\v';
-                  lp++;
-                  break;
-                default:
-                  fprintf (stderr, "invalid escape sequence in string: %s\n", line);
-                  exit (1);
-                }
-            }
-          else if (c == '"')
-            break;
-          else
-            {
-              *kp = c;
-              lp++;
-            }
-          kp++;
-        }
-      lp++;
-      if (*lp != '\0')
-        {
-          if (strchr (delimiters, *lp) == NULL)
-            {
-              fprintf (stderr, "string not followed by delimiter: %s\n", line);
-              exit (1);
-            }
-          lp++;
-        }
-      return new List_Node (key, kp - key, option[TYPE] ? lp : "");
-    }
-  else
-    {
-      /* Not a string. Look for the delimiter. */
-      int len = strcspn (line, delimiters);
-      const char *rest;
-
-      if (line[len] == '\0')
-        rest = "";
-      else
-        /* Skip the first delimiter. */
-        rest = &line[len + 1];
-      return new List_Node (line, len, option[TYPE] ? rest : "");
-    }
-}
-
-/* Reads in all keys from standard input and creates a linked list pointed
-   to by Head.  This list is then quickly checked for ``links,'' i.e.,
-   unhashable elements possessing identical key sets and lengths. */
-
-void
-Key_List::read_keys (void)
-{
-  T (Trace t ("Key_List::read_keys");)
-  char *ptr;
-
-  include_src = save_include_src ();
-  set_output_types ();
-
-  /* Oops, problem with the input file. */
-  if (! (ptr = Read_Line::get_line ()))
-    {
-      fprintf (stderr, "No words in input file, did you forget to prepend %s or use -t accidentally?\n", "%%");
-      exit (1);
-    }
-
-  /* Read in all the keywords from the input file. */
-  else
-    {
-      const char *delimiter = option.get_delimiter ();
-      List_Node  *temp, *trail = 0;
-
-      head = parse_line (ptr, delimiter);
-
-      for (temp = head;
-           (ptr = Read_Line::get_line ()) && strcmp (ptr, "%%");
-           temp = temp->next)
-        {
-          temp->next = parse_line (ptr, delimiter);
-          total_keys++;
-        }
-
-      /* See if any additional C code is included at end of this file. */
-      if (ptr)
-        additional_code = 1;
-
-      /* Hash table this number of times larger than keyword number. */
-      int table_size = (list_len = total_keys) * TABLE_MULTIPLE;
-
-#if LARGE_STACK_ARRAYS
-      /* By allocating the memory here we save on dynamic allocation overhead.
-         Table must be a power of 2 for the hash function scheme to work. */
-      List_Node *table[POW (table_size)];
-#else
-      // Note: we don't use new, because that invokes a custom operator new.
-      int malloc_size = POW (table_size) * sizeof(List_Node*);
-      if (malloc_size == 0) malloc_size = 1;
-      List_Node **table = (List_Node**)malloc(malloc_size);
-      if (table == NULL)
-        abort ();
-#endif
-
-      /* Make large hash table for efficiency. */
-      Hash_Table found_link (table, table_size, option[NOLENGTH]);
-
-      /* Test whether there are any links and also set the maximum length of
-        an identifier in the keyword list. */
-
-      for (temp = head; temp; temp = temp->next)
-        {
-          List_Node *ptr = found_link.insert (temp);
-
-          /* Check for links.  We deal with these by building an equivalence class
-             of all duplicate values (i.e., links) so that only 1 keyword is
-             representative of the entire collection.  This *greatly* simplifies
-             processing during later stages of the program. */
-
-          if (ptr)
-            {
-              total_duplicates++;
-              list_len--;
-              trail->next = temp->next;
-              temp->link  = ptr->link;
-              ptr->link   = temp;
-
-              /* Complain if user hasn't enabled the duplicate option. */
-              if (!option[DUP] || option[DEBUG])
-                fprintf (stderr, "Key link: \"%.*s\" = \"%.*s\", with key set \"%.*s\".\n",
-                                 temp->key_length, temp->key,
-                                 ptr->key_length, ptr->key,
-                                 temp->char_set_length, temp->char_set);
-            }
-          else
-            trail = temp;
-
-          /* Update minimum and maximum keyword length, if needed. */
-          if (max_key_len < temp->key_length)
-            max_key_len = temp->key_length;
-          if (min_key_len > temp->key_length)
-            min_key_len = temp->key_length;
-        }
-
-#if !LARGE_STACK_ARRAYS
-      free ((char *) table);
-#endif
-
-      /* Exit program if links exists and option[DUP] not set, since we can't continue */
-      if (total_duplicates)
-        {
-          if (option[DUP])
-            fprintf (stderr, "%d input keys have identical hash values, examine output carefully...\n",
-                             total_duplicates);
-          else
-            {
-              fprintf (stderr, "%d input keys have identical hash values,\ntry different key positions or use option -D.\n",
-                               total_duplicates);
-              exit (1);
-            }
-        }
-      /* Exit program if an empty string is used as key, since the comparison
-         expressions don't work correctly for looking up an empty string. */
-      if (min_key_len == 0)
-        {
-          fprintf (stderr, "Empty input key is not allowed.\nTo recognize an empty input key, your code should check for\nlen == 0 before calling the gperf generated lookup function.\n");
-          exit (1);
-        }
-      if (option[ALLCHARS])
-        option.set_keysig_size (max_key_len);
-    }
-}
-
-/* Recursively merges two sorted lists together to form one sorted list. The
-   ordering criteria is by frequency of occurrence of elements in the key set
-   or by the hash value.  This is a kludge, but permits nice sharing of
-   almost identical code without incurring the overhead of a function
-   call comparison. */
-
-List_Node *
-Key_List::merge (List_Node *list1, List_Node *list2)
-{
-  T (Trace t ("Key_List::merge");)
-  List_Node *result;
-  List_Node **resultp = &result;
-  for (;;)
-    {
-      if (!list1)
-        {
-          *resultp = list2;
-          break;
-        }
-      if (!list2)
-        {
-          *resultp = list1;
-          break;
-        }
-      if ((occurrence_sort && list1->occurrence < list2->occurrence)
-	    || (hash_sort && list1->hash_value > list2->hash_value))
-        {
-          *resultp = list2;
-          resultp = &list2->next; list2 = list1; list1 = *resultp;
-        }
-      else
-        {
-          *resultp = list1;
-          resultp = &list1->next; list1 = *resultp;
-        }
-    }
-  return result;
-}
-
-/* Applies the merge sort algorithm to recursively sort the key list by
-   frequency of occurrence of elements in the key set. */
-
-List_Node *
-Key_List::merge_sort (List_Node *head)
-{
-  T (Trace t ("Key_List::merge_sort");)
-  if (!head || !head->next)
-    return head;
-  else
-    {
-      List_Node *middle = head;
-      List_Node *temp   = head->next->next;
-
-      while (temp)
-        {
-          temp   = temp->next;
-          middle = middle->next;
-          if (temp)
-            temp = temp->next;
-        }
-
-      temp         = middle->next;
-      middle->next = 0;
-      return merge (merge_sort (head), merge_sort (temp));
-    }
-}
-
-/* Returns the frequency of occurrence of elements in the key set. */
-
-inline int
-Key_List::get_occurrence (List_Node *ptr)
-{
-  T (Trace t ("Key_List::get_occurrence");)
-  int value = 0;
-
-  const char *p = ptr->char_set;
-  unsigned int i = ptr->char_set_length;
-  for (; i > 0; p++, i--)
-    value += occurrences[(unsigned char)(*p)];
-
-  return value;
-}
-
-/* Enables the index location of all key set elements that are now
-   determined. */
-
-inline void
-Key_List::set_determined (List_Node *ptr)
-{
-  T (Trace t ("Key_List::set_determined");)
-
-  const char *p = ptr->char_set;
-  unsigned int i = ptr->char_set_length;
-  for (; i > 0; p++, i--)
-    determined[(unsigned char)(*p)] = 1;
-}
-
-/* Returns TRUE if PTR's key set is already completely determined. */
-
-inline int
-Key_List::already_determined (List_Node *ptr)
-{
-  T (Trace t ("Key_List::already_determined");)
-  int is_determined = 1;
-
-  const char *p = ptr->char_set;
-  unsigned int i = ptr->char_set_length;
-  for (; is_determined && i > 0; p++, i--)
-    is_determined = determined[(unsigned char)(*p)];
-
-  return is_determined;
-}
-
-/* Reorders the table by first sorting the list so that frequently occuring
-   keys appear first, and then the list is reorded so that keys whose values
-   are already determined will be placed towards the front of the list.  This
-   helps prune the search time by handling inevitable collisions early in the
-   search process.  See Cichelli's paper from Jan 1980 JACM for details.... */
-
-void
-Key_List::reorder (void)
-{
-  T (Trace t ("Key_List::reorder");)
-  List_Node *ptr;
-  for (ptr = head; ptr; ptr = ptr->next)
-    ptr->occurrence = get_occurrence (ptr);
-
-  hash_sort = 0;
-  occurrence_sort = 1;
-
-  for (ptr = head = merge_sort (head); ptr->next; ptr = ptr->next)
-    {
-      set_determined (ptr);
-
-      if (already_determined (ptr->next))
-        continue;
-      else
-        {
-          List_Node *trail_ptr = ptr->next;
-          List_Node *run_ptr   = trail_ptr->next;
-
-          for (; run_ptr; run_ptr = trail_ptr->next)
-            {
-
-              if (already_determined (run_ptr))
-                {
-                  trail_ptr->next = run_ptr->next;
-                  run_ptr->next   = ptr->next;
-                  ptr = ptr->next = run_ptr;
-                }
-              else
-                trail_ptr = run_ptr;
-            }
-        }
-    }
-}
-
-/* ============================ Output routines ============================ */
-
-/* The "const " qualifier. */
-static const char *const_always;
-
-/* The "const " qualifier, for read-only arrays. */
-static const char *const_readonly_array;
-
-/* The "const " qualifier, for the array type. */
-static const char *const_for_struct;
-
-/* Returns the smallest unsigned C type capable of holding integers up to N. */
-
-static const char *
-smallest_integral_type (int n)
-{
-  if (n <= UCHAR_MAX) return "unsigned char";
-  if (n <= USHRT_MAX) return "unsigned short";
-  return "unsigned int";
-}
-
-/* Returns the smallest signed C type capable of holding integers
-   from MIN to MAX. */
-
-static const char *
-smallest_integral_type (int min, int max)
-{
-  if (option[ANSIC] | option[CPLUSPLUS])
-    if (min >= SCHAR_MIN && max <= SCHAR_MAX) return "signed char";
-  if (min >= SHRT_MIN && max <= SHRT_MAX) return "short";
-  return "int";
-}
-
-/* A cast from `char' to a valid array index. */
-static const char *char_to_index;
-
-/* ------------------------------------------------------------------------- */
-
-/* Computes the maximum and minimum hash values.  Since the
-   list is already sorted by hash value all we need to do is
-   find the final item! */
-
-void
-Key_List::compute_min_max (void)
-{
-  T (Trace t ("Key_List::compute_min_max");)
-  List_Node *temp;
-  for (temp = head; temp->next; temp = temp->next)
-    ;
-
-  min_hash_value = head->hash_value;
-  max_hash_value = temp->hash_value;
-}
-
-/* ------------------------------------------------------------------------- */
-
-/* Returns the number of different hash values. */
-
-int
-Key_List::num_hash_values (void)
-{
-  T (Trace t ("Key_List::num_hash_values");)
-  int count = 1;
-  List_Node *temp;
-  int value;
-
-  for (temp = head, value = temp->hash_value; temp->next; )
-    {
-      temp = temp->next;
-      if (value != temp->hash_value)
-        {
-          value = temp->hash_value;
-          count++;
-        }
-    }
-  return count;
-}
-
-/* -------------------- Output_Constants and subclasses -------------------- */
-
-/* This class outputs an enumeration defining some constants. */
-
-struct Output_Constants
-{
-  virtual void output_start () = 0;
-  virtual void output_item (const char *name, int value) = 0;
-  virtual void output_end () = 0;
-  Output_Constants () {}
-  virtual ~Output_Constants () {}
-};
-
-/* This class outputs an enumeration in #define syntax. */
-
-struct Output_Defines : public Output_Constants
-{
-  virtual void output_start ();
-  virtual void output_item (const char *name, int value);
-  virtual void output_end ();
-  Output_Defines () {}
-  virtual ~Output_Defines () {}
-};
-
-void Output_Defines::output_start ()
-{
-  T (Trace t ("Output_Defines::output_start");)
-  printf ("\n");
-}
-
-void Output_Defines::output_item (const char *name, int value)
-{
-  T (Trace t ("Output_Defines::output_item");)
-  printf ("#define %s %d\n", name, value);
-}
-
-void Output_Defines::output_end ()
-{
-  T (Trace t ("Output_Defines::output_end");)
-}
-
-/* This class outputs an enumeration using `enum'. */
-
-struct Output_Enum : public Output_Constants
-{
-  virtual void output_start ();
-  virtual void output_item (const char *name, int value);
-  virtual void output_end ();
-  Output_Enum (const char *indent) : indentation (indent) {}
-  virtual ~Output_Enum () {}
-private:
-  const char *indentation;
-  int pending_comma;
-};
-
-void Output_Enum::output_start ()
-{
-  T (Trace t ("Output_Enum::output_start");)
-  printf ("%senum\n"
-          "%s  {\n",
-          indentation, indentation);
-  pending_comma = 0;
-}
-
-void Output_Enum::output_item (const char *name, int value)
-{
-  T (Trace t ("Output_Enum::output_item");)
-  if (pending_comma)
-    printf (",\n");
-  printf ("%s    %s = %d", indentation, name, value);
-  pending_comma = 1;
-}
-
-void Output_Enum::output_end ()
-{
-  T (Trace t ("Output_Enum::output_end");)
-  if (pending_comma)
-    printf ("\n");
-  printf ("%s  };\n\n", indentation);
-}
-
-/* Outputs the maximum and minimum hash values etc. */
-
-void
-Key_List::output_constants (struct Output_Constants& style)
-{
-  T (Trace t ("Key_List::output_constants");)
-
-  style.output_start ();
-  style.output_item ("TOTAL_KEYWORDS", total_keys);
-  style.output_item ("MIN_WORD_LENGTH", min_key_len);
-  style.output_item ("MAX_WORD_LENGTH", max_key_len);
-  style.output_item ("MIN_HASH_VALUE", min_hash_value);
-  style.output_item ("MAX_HASH_VALUE", max_hash_value);
-  style.output_end ();
-}
-
-/* ------------------------------------------------------------------------- */
-
-/* Outputs a keyword, as a string: enclosed in double quotes, escaping
-   backslashes, double quote and unprintable characters. */
-
-static void
-output_string (const char *key, int len)
-{
-  T (Trace t ("output_string");)
-
-  putchar ('"');
-  for (; len > 0; len--)
-    {
-      unsigned char c = (unsigned char) *key++;
-      if (isprint (c))
-        {
-          if (c == '"' || c == '\\')
-            putchar ('\\');
-          putchar (c);
-        }
-      else
-        {
-          /* Use octal escapes, not hexadecimal escapes, because some old
-             C compilers didn't understand hexadecimal escapes, and because
-             hexadecimal escapes are not limited to 2 digits, thus needing
-             special care if the following character happens to be a digit. */
-          putchar ('\\');
-          putchar ('0' + ((c >> 6) & 7));
-          putchar ('0' + ((c >> 3) & 7));
-          putchar ('0' + (c & 7));
-        }
-    }
-  putchar ('"');
-}
-
-/* ------------------------------------------------------------------------- */
-
-/* Outputs a type and a const specifier.
-   The output is terminated with a space. */
-
-static void
-output_const_type (const char *const_string, const char *type_string)
-{
-  if (type_string[strlen(type_string)-1] == '*')
-    printf ("%s %s", type_string, const_string);
-  else
-    printf ("%s%s ", const_string, type_string);
-}
-
-/* ----------------------- Output_Expr and subclasses ----------------------- */
-
-/* This class outputs a general expression. */
-
-struct Output_Expr
-{
-  virtual void output_expr () const = 0;
-  Output_Expr () {}
-  virtual ~Output_Expr () {}
-};
-
-/* This class outputs an expression formed by a single string. */
-
-struct Output_Expr1 : public Output_Expr
-{
-  virtual void output_expr () const;
-  Output_Expr1 (const char *piece1) : p1 (piece1) {}
-  virtual ~Output_Expr1 () {}
-private:
-  const char *p1;
-};
-
-void Output_Expr1::output_expr () const
-{
-  T (Trace t ("Output_Expr1::output_expr");)
-  printf ("%s", p1);
-}
-
-#if 0 /* unused */
-
-/* This class outputs an expression formed by the concatenation of two
-   strings. */
-
-struct Output_Expr2 : public Output_Expr
-{
-  virtual void output_expr () const;
-  Output_Expr2 (const char *piece1, const char *piece2)
-    : p1 (piece1), p2 (piece2) {}
-  virtual ~Output_Expr2 () {}
-private:
-  const char *p1;
-  const char *p2;
-};
-
-void Output_Expr2::output_expr () const
-{
-  T (Trace t ("Output_Expr2::output_expr");)
-  printf ("%s%s", p1, p2);
-}
-
-#endif
-
-/* --------------------- Output_Compare and subclasses --------------------- */
-
-/* This class outputs a comparison expression. */
-
-struct Output_Compare
-{
-  virtual void output_comparison (const Output_Expr& expr1,
-                                  const Output_Expr& expr2) const = 0;
-  Output_Compare () {}
-  virtual ~Output_Compare () {}
-};
-
-/* This class outputs a comparison using strcmp. */
-
-struct Output_Compare_Strcmp : public Output_Compare
-{
-  virtual void output_comparison (const Output_Expr& expr1,
-                                  const Output_Expr& expr2) const;
-  Output_Compare_Strcmp () {}
-  virtual ~Output_Compare_Strcmp () {}
-};
-
-void Output_Compare_Strcmp::output_comparison (const Output_Expr& expr1,
-                                               const Output_Expr& expr2) const
-{
-  T (Trace t ("Output_Compare_Strcmp::output_comparison");)
-  printf ("*");
-  expr1.output_expr ();
-  printf (" == *");
-  expr2.output_expr ();
-  printf (" && !strcmp (");
-  expr1.output_expr ();
-  printf (" + 1, ");
-  expr2.output_expr ();
-  printf (" + 1)");
-}
-
-/* This class outputs a comparison using strncmp.
-   Note that the length of expr1 will be available through the local variable
-   `len'. */
-
-struct Output_Compare_Strncmp : public Output_Compare
-{
-  virtual void output_comparison (const Output_Expr& expr1,
-                                  const Output_Expr& expr2) const;
-  Output_Compare_Strncmp () {}
-  virtual ~Output_Compare_Strncmp () {}
-};
-
-void Output_Compare_Strncmp::output_comparison (const Output_Expr& expr1,
-                                                const Output_Expr& expr2) const
-{
-  T (Trace t ("Output_Compare_Strncmp::output_comparison");)
-  printf ("*");
-  expr1.output_expr ();
-  printf (" == *");
-  expr2.output_expr ();
-  printf (" && !strncmp (");
-  expr1.output_expr ();
-  printf (" + 1, ");
-  expr2.output_expr ();
-  printf (" + 1, len - 1) && ");
-  expr2.output_expr ();
-  printf ("[len] == '\\0'");
-}
-
-/* This class outputs a comparison using memcmp.
-   Note that the length of expr1 (available through the local variable `len')
-   must be verified to be equal to the length of expr2 prior to this
-   comparison. */
-
-struct Output_Compare_Memcmp : public Output_Compare
-{
-  virtual void output_comparison (const Output_Expr& expr1,
-                                  const Output_Expr& expr2) const;
-  Output_Compare_Memcmp () {}
-  virtual ~Output_Compare_Memcmp () {}
-};
-
-void Output_Compare_Memcmp::output_comparison (const Output_Expr& expr1,
-                                               const Output_Expr& expr2) const
-{
-  T (Trace t ("Output_Compare_Memcmp::output_comparison");)
-  printf ("*");
-  expr1.output_expr ();
-  printf (" == *");
-  expr2.output_expr ();
-  printf (" && !memcmp (");
-  expr1.output_expr ();
-  printf (" + 1, ");
-  expr2.output_expr ();
-  printf (" + 1, len - 1)");
-}
-
-/* ------------------------------------------------------------------------- */
-
-/* Generates C code for the hash function that returns the
-   proper encoding for each key word. */
-
-void
-Key_List::output_hash_function (void)
-{
-  T (Trace t ("Key_List::output_hash_function");)
-  const int max_column  = 10;
-  int field_width;
-
-  /* Calculate maximum number of digits required for MAX_HASH_VALUE. */
-  field_width = 2;
-  for (int trunc = max_hash_value; (trunc /= 10) > 0;)
-    field_width++;
-
-  /* Output the function's head. */
-  if (option[CPLUSPLUS])
-    printf ("inline ");
-  else if (option[KRC] | option[C] | option[ANSIC])
-    printf ("#ifdef __GNUC__\n"
-            "__inline\n"
-            "#else\n"
-            "#ifdef __cplusplus\n"
-            "inline\n"
-            "#endif\n"
-            "#endif\n");
-
-  if (option[KRC] | option[C] | option[ANSIC])
-    printf ("static ");
-  printf ("unsigned int\n");
-  if (option[CPLUSPLUS])
-    printf ("%s::", option.get_class_name ());
-  printf ("%s ", option.get_hash_name ());
-  if (option[KRC] || option[C] || option [ANSIC] || option[CPLUSPLUS])
-    printf (option[KRC] ?
-	      "(str, len)\n"
-              "     register char *str;\n"
-              "     register unsigned int len;\n" :
-	    option[C] ?
-	      "(str, len)\n"
-              "     register const char *str;\n"
-              "     register unsigned int len;\n" :
-	      "(register const char *str, register unsigned int len)\n");
-
-  /* Note that when the hash function is called, it has already been verified
-     that  min_key_len <= len <= max_key_len. */
-
-  /* Output the function's body. */
-  printf ("{\n");
-
-  /* First the asso_values array. */
-  printf ("  static %s%s asso_values[] =\n"
-          "    {",
-          const_readonly_array,
-          smallest_integral_type (max_hash_value + 1));
-
-  for (int count = 0; count < ALPHA_SIZE; count++)
-    {
-      if (count > 0)
-        printf (",");
-      if (!(count % max_column))
-        printf ("\n     ");
-      printf ("%*d", field_width,
-              occurrences[count] ? asso_values[count] : max_hash_value + 1);
-    }
-
-  printf ("\n"
-          "    };\n");
-
-  /* Optimize special case of ``-k 1,$'' */
-  if (option[DEFAULTCHARS])
-    printf ("  return %sasso_values[%sstr[len - 1]] + asso_values[%sstr[0]];\n",
-            option[NOLENGTH] ? "" : "len + ",
-            char_to_index, char_to_index);
-  else
-    {
-      int key_pos;
-
-      option.reset ();
-
-      /* Get first (also highest) key position. */
-      key_pos = option.get ();
-
-      if (!option[ALLCHARS] && (key_pos == WORD_END || key_pos <= min_key_len))
-        {
-          /* We can perform additional optimizations here:
-             Write it out as a single expression. Note that the values
-             are added as `int's even though the asso_values array may
-             contain `unsigned char's or `unsigned short's. */
-
-          printf ("  return %s",
-                  option[NOLENGTH] ? "" : "len + ");
-
-          for (; key_pos != WORD_END; )
-            {
-              printf ("asso_values[%sstr[%d]]", char_to_index, key_pos - 1);
-              if ((key_pos = option.get ()) != EOS)
-                printf (" + ");
-              else
-                break;
-            }
-
-          if (key_pos == WORD_END)
-            printf ("asso_values[%sstr[len - 1]]", char_to_index);
-
-          printf (";\n");
-        }
-      else
-        {
-          /* We've got to use the correct, but brute force, technique. */
-          printf ("  register int hval = %s;\n\n"
-                  "  switch (%s)\n"
-                  "    {\n"
-                  "      default:\n",
-                  option[NOLENGTH] ? "0" : "len",
-                  option[NOLENGTH] ? "len" : "hval");
-
-          /* User wants *all* characters considered in hash. */
-          if (option[ALLCHARS])
-            {
-              for (int i = max_key_len; i > 0; i--)
-                printf ("      case %d:\n"
-                        "        hval += asso_values[%sstr[%d]];\n",
-                        i, char_to_index, i - 1);
-
-              printf ("        break;\n"
-                      "    }\n"
-                      "  return hval;\n");
-            }
-          else                  /* do the hard part... */
-            {
-              while (key_pos != WORD_END && key_pos > max_key_len)
-                if ((key_pos = option.get ()) == EOS)
-                  break;
-
-              if (key_pos != EOS && key_pos != WORD_END)
-                {
-                  int i = key_pos;
-                  do
-                    {
-                      for ( ; i >= key_pos; i--)
-                        printf ("      case %d:\n", i);
-
-                      printf ("        hval += asso_values[%sstr[%d]];\n",
-                              char_to_index, key_pos - 1);
-
-                      key_pos = option.get ();
-                    }
-                  while (key_pos != EOS && key_pos != WORD_END);
-
-                  for ( ; i >= min_key_len; i--)
-                    printf ("      case %d:\n", i);
-                }
-
-              printf ("        break;\n"
-                      "    }\n"
-                      "  return hval");
-              if (key_pos == WORD_END)
-                printf (" + asso_values[%sstr[len - 1]]", char_to_index);
-              printf (";\n");
-            }
-        }
-    }
-  printf ("}\n\n");
-}
-
-/* ------------------------------------------------------------------------- */
-
-/* Prints out a table of keyword lengths, for use with the
-   comparison code in generated function ``in_word_set''. */
-
-void
-Key_List::output_keylength_table (void)
-{
-  T (Trace t ("Key_List::output_keylength_table");)
-  const int  columns = 14;
-  int        index;
-  int        column;
-  const char *indent    = option[GLOBAL] ? "" : "  ";
-  List_Node *temp;
-
-  printf ("%sstatic %s%s lengthtable[] =\n%s  {",
-          indent, const_readonly_array,
-          smallest_integral_type (max_key_len),
-          indent);
-
-  /* Generate an array of lengths, similar to output_keyword_table. */
-
-  column = 0;
-  for (temp = head, index = 0; temp; temp = temp->next)
-    {
-      if (option[SWITCH] && !option[TYPE]
-          && !(temp->link
-               || (temp->next && temp->hash_value == temp->next->hash_value)))
-        continue;
-
-      if (index < temp->hash_value && !option[SWITCH] && !option[DUP])
-        {
-          /* Some blank entries. */
-          for ( ; index < temp->hash_value; index++)
-            {
-              if (index > 0)
-                printf (",");
-              if ((column++ % columns) == 0)
-                printf ("\n%s   ", indent);
-              printf ("%3d", 0);
-            }
-        }
-
-      if (index > 0)
-        printf (",");
-      if ((column++ % columns) == 0)
-        printf("\n%s   ", indent);
-      printf ("%3d", temp->key_length);
-
-      /* Deal with links specially. */
-      if (temp->link) // implies option[DUP]
-        for (List_Node *links = temp->link; links; links = links->link)
-          {
-            ++index;
-            printf (",");
-            if ((column++ % columns) == 0)
-              printf("\n%s   ", indent);
-            printf ("%3d", links->key_length);
-          }
-
-      index++;
-    }
-
-  printf ("\n%s  };\n", indent);
-  if (option[GLOBAL])
-    printf ("\n");
-}
-
-/* ------------------------------------------------------------------------- */
-
-static void
-output_keyword_entry (List_Node *temp, const char *indent)
-{
-  printf ("%s    ", indent);
-  if (option[TYPE])
-    printf ("{");
-  output_string (temp->key, temp->key_length);
-  if (option[TYPE])
-    {
-      if (strlen (temp->rest) > 0)
-        printf (",%s", temp->rest);
-      printf ("}");
-    }
-  if (option[DEBUG])
-    printf (" /* hash value = %d, index = %d */",
-            temp->hash_value, temp->index);
-}
-
-static void
-output_keyword_blank_entries (int count, const char *indent)
-{
-  int columns;
-  if (option[TYPE])
-    {
-      columns = 58 / (6 + strlen (option.get_initializer_suffix()));
-      if (columns == 0)
-        columns = 1;
-    }
-  else
-    {
-      columns = 9;
-    }
-  int column = 0;
-  for (int i = 0; i < count; i++)
-    {
-      if ((column % columns) == 0)
-        {
-          if (i > 0)
-            printf (",\n");
-          printf ("%s    ", indent);
-        }
-      else
-        {
-          if (i > 0)
-            printf (", ");
-        }
-      if (option[TYPE])
-        printf ("{\"\"%s}", option.get_initializer_suffix());
-      else
-        printf ("\"\"");
-      column++;
-    }
-}
-
-/* Prints out the array containing the key words for the hash function. */
-
-void
-Key_List::output_keyword_table (void)
-{
-  T (Trace t ("Key_List::output_keyword_table");)
-  const char *indent  = option[GLOBAL] ? "" : "  ";
-  int         index;
-  List_Node  *temp;
-
-  printf ("%sstatic ",
-          indent);
-  output_const_type (const_readonly_array, struct_tag);
-  printf ("%s[] =\n"
-          "%s  {\n",
-          option.get_wordlist_name (),
-          indent);
-
-  /* Generate an array of reserved words at appropriate locations. */
-
-  for (temp = head, index = 0; temp; temp = temp->next)
-    {
-      if (option[SWITCH] && !option[TYPE]
-          && !(temp->link
-               || (temp->next && temp->hash_value == temp->next->hash_value)))
-        continue;
-
-      if (index > 0)
-        printf (",\n");
-
-      if (index < temp->hash_value && !option[SWITCH] && !option[DUP])
-        {
-          /* Some blank entries. */
-          output_keyword_blank_entries (temp->hash_value - index, indent);
-          printf (",\n");
-          index = temp->hash_value;
-        }
-
-      temp->index = index;
-
-      output_keyword_entry (temp, indent);
-
-      /* Deal with links specially. */
-      if (temp->link) // implies option[DUP]
-        for (List_Node *links = temp->link; links; links = links->link)
-          {
-            links->index = ++index;
-            printf (",\n");
-            output_keyword_entry (links, indent);
-          }
-
-      index++;
-    }
-  if (index > 0)
-    printf ("\n");
-
-  printf ("%s  };\n\n", indent);
-}
-
-/* ------------------------------------------------------------------------- */
-
-/* Generates the large, sparse table that maps hash values into
-   the smaller, contiguous range of the keyword table. */
-
-void
-Key_List::output_lookup_array (void)
-{
-  T (Trace t ("Key_List::output_lookup_array");)
-  if (option[DUP])
-    {
-      const int DEFAULT_VALUE = -1;
-
-      /* Because of the way output_keyword_table works, every duplicate set is
-         stored contiguously in the wordlist array. */
-      struct duplicate_entry
-        {
-          int hash_value;  /* Hash value for this particular duplicate set. */
-          int index;       /* Index into the main keyword storage array. */
-          int count;       /* Number of consecutive duplicates at this index. */
-        };
-
-#if LARGE_STACK_ARRAYS
-      duplicate_entry duplicates[total_duplicates];
-      int lookup_array[max_hash_value + 1 + 2*total_duplicates];
-#else
-      // Note: we don't use new, because that invokes a custom operator new.
-      duplicate_entry *duplicates = (duplicate_entry *)
-        malloc (total_duplicates * sizeof(duplicate_entry) + 1);
-      int *lookup_array = (int *)
-        malloc ((max_hash_value + 1 + 2*total_duplicates) * sizeof(int));
-      if (duplicates == NULL || lookup_array == NULL)
-        abort();
-#endif
-      int lookup_array_size = max_hash_value + 1;
-      duplicate_entry *dup_ptr = &duplicates[0];
-      int *lookup_ptr = &lookup_array[max_hash_value + 1 + 2*total_duplicates];
-
-      while (lookup_ptr > lookup_array)
-        *--lookup_ptr = DEFAULT_VALUE;
-
-      /* Now dup_ptr = &duplicates[0] and lookup_ptr = &lookup_array[0]. */
-
-      for (List_Node *temp = head; temp; temp = temp->next)
-        {
-          int hash_value = temp->hash_value;
-          lookup_array[hash_value] = temp->index;
-          if (option[DEBUG])
-            fprintf (stderr, "keyword = %.*s, index = %d\n",
-                     temp->key_length, temp->key, temp->index);
-          if (temp->link
-              || (temp->next && hash_value == temp->next->hash_value))
-            {
-              /* Start a duplicate entry. */
-              dup_ptr->hash_value = hash_value;
-              dup_ptr->index      = temp->index;
-              dup_ptr->count      = 1;
-
-              for (;;)
-                {
-                  for (List_Node *ptr = temp->link; ptr; ptr = ptr->link)
-                    {
-                      dup_ptr->count++;
-                      if (option[DEBUG])
-                        fprintf (stderr,
-                                 "static linked keyword = %.*s, index = %d\n",
-                                 ptr->key_length, ptr->key, ptr->index);
-                    }
-
-                  if (!(temp->next && hash_value == temp->next->hash_value))
-                    break;
-
-                  temp = temp->next;
-
-                  dup_ptr->count++;
-                  if (option[DEBUG])
-                    fprintf (stderr, "dynamic linked keyword = %.*s, index = %d\n",
-                             temp->key_length, temp->key, temp->index);
-                }
-              assert (dup_ptr->count >= 2);
-              dup_ptr++;
-            }
-        }
-
-      while (dup_ptr > duplicates)
-        {
-          dup_ptr--;
-
-          if (option[DEBUG])
-            fprintf (stderr,
-                     "dup_ptr[%td]: hash_value = %d, index = %d, count = %d\n",
-                     dup_ptr - duplicates,
-                     dup_ptr->hash_value, dup_ptr->index, dup_ptr->count);
-
-          int i;
-          /* Start searching for available space towards the right part
-             of the lookup array. */
-          for (i = dup_ptr->hash_value; i < lookup_array_size-1; i++)
-            if (lookup_array[i] == DEFAULT_VALUE
-                && lookup_array[i + 1] == DEFAULT_VALUE)
-              goto found_i;
-          /* If we didn't find it to the right look to the left instead... */
-          for (i = dup_ptr->hash_value-1; i >= 0; i--)
-            if (lookup_array[i] == DEFAULT_VALUE
-                && lookup_array[i + 1] == DEFAULT_VALUE)
-              goto found_i;
-          /* Append to the end of lookup_array. */
-          i = lookup_array_size;
-          lookup_array_size += 2;
-        found_i:
-          /* Put in an indirection from dup_ptr->hash_value to i.
-             At i and i+1 store dup_ptr->index and dup_ptr->count. */
-          assert (lookup_array[dup_ptr->hash_value] == dup_ptr->index);
-          lookup_array[dup_ptr->hash_value] = - 1 - total_keys - i;
-          lookup_array[i] = - total_keys + dup_ptr->index;
-          lookup_array[i + 1] = - dup_ptr->count;
-          /* All these three values are <= -2, distinct from DEFAULT_VALUE. */
-        }
-
-      /* The values of the lookup array are now known. */
-
-      int min = INT_MAX;
-      int max = INT_MIN;
-      lookup_ptr = lookup_array + lookup_array_size;
-      while (lookup_ptr > lookup_array)
-        {
-          int val = *--lookup_ptr;
-          if (min > val)
-            min = val;
-          if (max < val)
-            max = val;
-        }
-
-      const char *indent = option[GLOBAL] ? "" : "  ";
-      printf ("%sstatic %s%s lookup[] =\n"
-              "%s  {",
-              indent, const_readonly_array, smallest_integral_type (min, max),
-              indent);
-
-      int field_width;
-      /* Calculate maximum number of digits required for MIN..MAX. */
-      {
-        field_width = 2;
-        for (int trunc = max; (trunc /= 10) > 0;)
-          field_width++;
-      }
-      if (min < 0)
-        {
-          int neg_field_width = 2;
-          for (int trunc = -min; (trunc /= 10) > 0;)
-            neg_field_width++;
-          neg_field_width++; /* account for the minus sign */
-          if (field_width < neg_field_width)
-            field_width = neg_field_width;
-        }
-
-      const int columns = 42 / field_width;
-      int column;
-
-      column = 0;
-      for (int i = 0; i < lookup_array_size; i++)
-        {
-          if (i > 0)
-            printf (",");
-          if ((column++ % columns) == 0)
-            printf("\n%s   ", indent);
-          printf ("%*d", field_width, lookup_array[i]);
-        }
-      printf ("\n%s  };\n\n", indent);
-
-#if !LARGE_STACK_ARRAYS
-      free ((char *) duplicates);
-      free ((char *) lookup_array);
-#endif
-    }
-}
-
-/* ------------------------------------------------------------------------- */
-
-/* Generate all the tables needed for the lookup function. */
-
-void
-Key_List::output_lookup_tables (void)
-{
-  T (Trace t ("Key_List::output_lookup_tables");)
-
-  if (option[SWITCH])
-    {
-      /* Use the switch in place of lookup table. */
-      if (option[LENTABLE] && (option[DUP] && total_duplicates > 0))
-        output_keylength_table ();
-      if (option[TYPE] || (option[DUP] && total_duplicates > 0))
-        output_keyword_table ();
-    }
-  else
-    {
-      /* Use the lookup table, in place of switch. */
-      if (option[LENTABLE])
-        output_keylength_table ();
-      output_keyword_table ();
-      output_lookup_array ();
-    }
-}
-
-/* ------------------------------------------------------------------------- */
-
-/* Output a single switch case (including duplicates). Advance list. */
-
-static List_Node *
-output_switch_case (List_Node *list, int indent, int *jumps_away)
-{
-  T (Trace t ("output_switch_case");)
-
-  if (option[DEBUG])
-    printf ("%*s/* hash value = %4d, keyword = \"%.*s\" */\n",
-            indent, "", list->hash_value, list->key_length, list->key);
-
-  if (option[DUP]
-      && (list->link
-          || (list->next && list->hash_value == list->next->hash_value)))
-    {
-      if (option[LENTABLE])
-        printf ("%*slengthptr = &lengthtable[%d];\n",
-                indent, "", list->index);
-      printf ("%*swordptr = &%s[%d];\n",
-              indent, "", option.get_wordlist_name (), list->index);
-
-      int count = 0;
-      for (List_Node *temp = list; ; temp = temp->next)
-        {
-          for (List_Node *links = temp; links; links = links->link)
-            count++;
-          if (!(temp->next && temp->hash_value == temp->next->hash_value))
-            break;
-        }
-
-      printf ("%*swordendptr = wordptr + %d;\n"
-              "%*sgoto multicompare;\n",
-              indent, "", count,
-              indent, "");
-      *jumps_away = 1;
-    }
-  else
-    {
-      if (option[LENTABLE])
-        {
-          printf ("%*sif (len == %d)\n"
-                  "%*s  {\n",
-                  indent, "", list->key_length,
-                  indent, "");
-          indent += 4;
-        }
-      printf ("%*sresword = ",
-              indent, "");
-      if (option[TYPE])
-        printf ("&%s[%d]", option.get_wordlist_name (), list->index);
-      else
-        output_string (list->key, list->key_length);
-      printf (";\n");
-      printf ("%*sgoto compare;\n",
-              indent, "");
-      if (option[LENTABLE])
-        {
-          indent -= 4;
-          printf ("%*s  }\n",
-                  indent, "");
-        }
-      else
-        *jumps_away = 1;
-    }
-
-  while (list->next && list->hash_value == list->next->hash_value)
-    list = list->next;
-  list = list->next;
-  return list;
-}
-
-/* Output a total of size cases, grouped into num_switches switch statements,
-   where 0 < num_switches <= size. */
-
-static void
-output_switches (List_Node *list, int num_switches, int size, int min_hash_value, int max_hash_value, int indent)
-{
-  T (Trace t ("output_switches");)
-
-  if (option[DEBUG])
-    printf ("%*s/* know %d <= key <= %d, contains %d cases */\n",
-            indent, "", min_hash_value, max_hash_value, size);
-
-  if (num_switches > 1)
-    {
-      int part1 = num_switches / 2;
-      int part2 = num_switches - part1;
-      int size1 = (int)((double)size / (double)num_switches * (double)part1 + 0.5);
-      int size2 = size - size1;
-
-      List_Node *temp = list;
-      for (int count = size1; count > 0; count--)
-        {
-          while (temp->hash_value == temp->next->hash_value)
-            temp = temp->next;
-          temp = temp->next;
-        }
-
-      printf ("%*sif (key < %d)\n"
-              "%*s  {\n",
-              indent, "", temp->hash_value,
-              indent, "");
-
-      output_switches (list, part1, size1, min_hash_value, temp->hash_value-1, indent+4);
-
-      printf ("%*s  }\n"
-              "%*selse\n"
-              "%*s  {\n",
-              indent, "", indent, "", indent, "");
-
-      output_switches (temp, part2, size2, temp->hash_value, max_hash_value, indent+4);
-
-      printf ("%*s  }\n",
-              indent, "");
-    }
-  else
-    {
-      /* Output a single switch. */
-      int lowest_case_value = list->hash_value;
-      if (size == 1)
-        {
-          int jumps_away = 0;
-          assert (min_hash_value <= lowest_case_value);
-          assert (lowest_case_value <= max_hash_value);
-          if (min_hash_value == max_hash_value)
-            output_switch_case (list, indent, &jumps_away);
-          else
-            {
-              printf ("%*sif (key == %d)\n"
-                      "%*s  {\n",
-                      indent, "", lowest_case_value,
-                      indent, "");
-              output_switch_case (list, indent+4, &jumps_away);
-              printf ("%*s  }\n",
-                      indent, "");
-            }
-        }
-      else
-        {
-          if (lowest_case_value == 0)
-            printf ("%*sswitch (key)\n", indent, "");
-          else
-            printf ("%*sswitch (key - %d)\n", indent, "", lowest_case_value);
-          printf ("%*s  {\n",
-                  indent, "");
-          for (; size > 0; size--)
-            {
-              int jumps_away = 0;
-              printf ("%*s    case %d:\n",
-                      indent, "", list->hash_value - lowest_case_value);
-              list = output_switch_case (list, indent+6, &jumps_away);
-              if (!jumps_away)
-                printf ("%*s      break;\n",
-                        indent, "");
-            }
-          printf ("%*s  }\n",
-                  indent, "");
-        }
-    }
-}
-
-/* Generates C code to perform the keyword lookup. */
-
-void
-Key_List::output_lookup_function_body (const Output_Compare& comparison)
-{
-  T (Trace t ("Key_List::output_lookup_function_body");)
-
-  printf ("  if (len <= MAX_WORD_LENGTH && len >= MIN_WORD_LENGTH)\n"
-          "    {\n"
-          "      register int key = %s (str, len);\n\n",
-          option.get_hash_name ());
-
-  if (option[SWITCH])
-    {
-      int switch_size = num_hash_values ();
-      int num_switches = option.get_total_switches ();
-      if (num_switches > switch_size)
-        num_switches = switch_size;
-
-      printf ("      if (key <= MAX_HASH_VALUE && key >= MIN_HASH_VALUE)\n"
-              "        {\n");
-      if (option[DUP])
-        {
-          if (option[LENTABLE])
-            printf ("          register %s%s *lengthptr;\n",
-                    const_always, smallest_integral_type (max_key_len));
-          printf ("          register ");
-          output_const_type (const_readonly_array, struct_tag);
-          printf ("*wordptr;\n");
-          printf ("          register ");
-          output_const_type (const_readonly_array, struct_tag);
-          printf ("*wordendptr;\n");
-        }
-      if (option[TYPE])
-        {
-          printf ("          register ");
-          output_const_type (const_readonly_array, struct_tag);
-          printf ("*resword;\n\n");
-        }
-      else
-        printf ("          register %sresword;\n\n",
-                struct_tag);
-
-      output_switches (head, num_switches, switch_size, min_hash_value, max_hash_value, 10);
-
-      if (option[DUP])
-        {
-          int indent = 8;
-          printf ("%*s  return 0;\n"
-                  "%*smulticompare:\n"
-                  "%*s  while (wordptr < wordendptr)\n"
-                  "%*s    {\n",
-                  indent, "", indent, "", indent, "", indent, "");
-          if (option[LENTABLE])
-            {
-              printf ("%*s      if (len == *lengthptr)\n"
-                      "%*s        {\n",
-                      indent, "", indent, "");
-              indent += 4;
-            }
-          printf ("%*s      register %schar *s = ",
-                  indent, "", const_always);
-          if (option[TYPE])
-            printf ("wordptr->%s", option.get_key_name ());
-          else
-            printf ("*wordptr");
-          printf (";\n\n"
-                  "%*s      if (",
-                  indent, "");
-          comparison.output_comparison (Output_Expr1 ("str"), Output_Expr1 ("s"));
-          printf (")\n"
-                  "%*s        return %s;\n",
-                  indent, "",
-                  option[TYPE] ? "wordptr" : "s");
-          if (option[LENTABLE])
-            {
-              indent -= 4;
-              printf ("%*s        }\n",
-                      indent, "");
-            }
-          if (option[LENTABLE])
-            printf ("%*s      lengthptr++;\n",
-                    indent, "");
-          printf ("%*s      wordptr++;\n"
-                  "%*s    }\n",
-                  indent, "", indent, "");
-        }
-      printf ("          return 0;\n"
-              "        compare:\n");
-      if (option[TYPE])
-        {
-          printf ("          {\n"
-                  "            register %schar *s = resword->%s;\n\n"
-                  "            if (",
-                  const_always, option.get_key_name ());
-          comparison.output_comparison (Output_Expr1 ("str"), Output_Expr1 ("s"));
-          printf (")\n"
-                  "              return resword;\n"
-                  "          }\n");
-        }
-      else
-        {
-          printf ("          if (");
-          comparison.output_comparison (Output_Expr1 ("str"), Output_Expr1 ("resword"));
-          printf (")\n"
-                  "            return resword;\n");
-        }
-      printf ("        }\n");
-    }
-  else
-    {
-      printf ("      if (key <= MAX_HASH_VALUE && key >= 0)\n");
-
-      if (option[DUP])
-        {
-          int indent = 8;
-          printf ("%*s{\n"
-                  "%*s  register int index = lookup[key];\n\n"
-                  "%*s  if (index >= 0)\n",
-                  indent, "", indent, "", indent, "");
-          if (option[LENTABLE])
-            {
-              printf ("%*s    {\n"
-                      "%*s      if (len == lengthtable[index])\n",
-                      indent, "", indent, "");
-              indent += 4;
-            }
-          printf ("%*s    {\n"
-                  "%*s      register %schar *s = %s[index]",
-                  indent, "",
-                  indent, "", const_always, option.get_wordlist_name ());
-          if (option[TYPE])
-            printf (".%s", option.get_key_name ());
-          printf (";\n\n"
-                  "%*s      if (",
-                  indent, "");
-          comparison.output_comparison (Output_Expr1 ("str"), Output_Expr1 ("s"));
-          printf (")\n"
-                  "%*s        return ",
-                  indent, "");
-          if (option[TYPE])
-            printf ("&%s[index]", option.get_wordlist_name ());
-          else
-            printf ("s");
-          printf (";\n"
-                  "%*s    }\n",
-                  indent, "");
-          if (option[LENTABLE])
-            {
-              indent -= 4;
-              printf ("%*s    }\n", indent, "");
-            }
-          if (total_duplicates > 0)
-            {
-              printf ("%*s  else if (index < -TOTAL_KEYWORDS)\n"
-                      "%*s    {\n"
-                      "%*s      register int offset = - 1 - TOTAL_KEYWORDS - index;\n",
-                      indent, "", indent, "", indent, "");
-              if (option[LENTABLE])
-                printf ("%*s      register %s%s *lengthptr = &lengthtable[TOTAL_KEYWORDS + lookup[offset]];\n",
-                        indent, "", const_always, smallest_integral_type (max_key_len));
-              printf ("%*s      register ",
-                      indent, "");
-              output_const_type (const_readonly_array, struct_tag);
-              printf ("*wordptr = &%s[TOTAL_KEYWORDS + lookup[offset]];\n",
-                      option.get_wordlist_name ());
-              printf ("%*s      register ",
-                      indent, "");
-              output_const_type (const_readonly_array, struct_tag);
-              printf ("*wordendptr = wordptr + -lookup[offset + 1];\n\n");
-              printf ("%*s      while (wordptr < wordendptr)\n"
-                      "%*s        {\n",
-                      indent, "", indent, "");
-              if (option[LENTABLE])
-                {
-                  printf ("%*s          if (len == *lengthptr)\n"
-                          "%*s            {\n",
-                          indent, "", indent, "");
-                  indent += 4;
-                }
-              printf ("%*s          register %schar *s = ",
-                      indent, "", const_always);
-              if (option[TYPE])
-                printf ("wordptr->%s", option.get_key_name ());
-              else
-                printf ("*wordptr");
-              printf (";\n\n"
-                      "%*s          if (",
-                      indent, "");
-              comparison.output_comparison (Output_Expr1 ("str"), Output_Expr1 ("s"));
-              printf (")\n"
-                      "%*s            return %s;\n",
-                      indent, "",
-                      option[TYPE] ? "wordptr" : "s");
-              if (option[LENTABLE])
-                {
-                  indent -= 4;
-                  printf ("%*s            }\n",
-                          indent, "");
-                }
-              if (option[LENTABLE])
-                printf ("%*s          lengthptr++;\n",
-                        indent, "");
-              printf ("%*s          wordptr++;\n"
-                      "%*s        }\n"
-                      "%*s    }\n",
-                      indent, "", indent, "", indent, "");
-            }
-          printf ("%*s}\n",
-                  indent, "");
-        }
-      else
-        {
-          int indent = 8;
-          if (option[LENTABLE])
-            {
-              printf ("%*sif (len == lengthtable[key])\n",
-                      indent, "");
-              indent += 2;
-            }
-
-          printf ("%*s{\n"
-                  "%*s  register %schar *s = %s[key]",
-                  indent, "",
-                  indent, "", const_always, option.get_wordlist_name ());
-
-          if (option[TYPE])
-            printf (".%s", option.get_key_name ());
-
-          printf (";\n\n"
-                  "%*s  if (",
-                  indent, "");
-          comparison.output_comparison (Output_Expr1 ("str"), Output_Expr1 ("s"));
-          printf (")\n"
-                  "%*s    return ",
-                  indent, "");
-          if (option[TYPE])
-            printf ("&%s[key]", option.get_wordlist_name ());
-          else
-            printf ("s");
-          printf (";\n"
-                  "%*s}\n",
-                  indent, "");
-        }
-    }
-  printf ("    }\n"
-          "  return 0;\n");
-}
-
-/* Generates C code for the lookup function. */
-
-void
-Key_List::output_lookup_function (void)
-{
-  T (Trace t ("Key_List::output_lookup_function");)
-
-  /* Output the function's head. */
-  if (option[KRC] | option[C] | option[ANSIC])
-    printf ("#ifdef __GNUC__\n"
-            "__inline\n"
-            "#endif\n");
-
-  printf ("%s%s\n",
-          const_for_struct, return_type);
-  if (option[CPLUSPLUS])
-    printf ("%s::", option.get_class_name ());
-  printf ("%s ", option.get_function_name ());
-  if (option[KRC] || option[C] || option[ANSIC] || option[CPLUSPLUS])
-    printf (option[KRC] ?
-	      "(str, len)\n"
-              "     register char *str;\n"
-              "     register unsigned int len;\n" :
-	    option[C] ?
-	      "(str, len)\n"
-              "     register const char *str;\n"
-              "     register unsigned int len;\n" :
-	    "(register const char *str, register unsigned int len)\n");
-
-  /* Output the function's body. */
-  printf ("{\n");
-
-  if (option[ENUM] && !option[GLOBAL])
-    {
-      Output_Enum style ("  ");
-      output_constants (style);
-    }
-
-  if (!option[GLOBAL])
-    output_lookup_tables ();
-
-  if (option[LENTABLE])
-    output_lookup_function_body (Output_Compare_Memcmp ());
-  else
-    {
-      if (option[COMP])
-        output_lookup_function_body (Output_Compare_Strncmp ());
-      else
-        output_lookup_function_body (Output_Compare_Strcmp ());
-    }
-
-  printf ("}\n");
-}
-
-/* ------------------------------------------------------------------------- */
-
-/* Generates the hash function and the key word recognizer function
-   based upon the user's Options. */
-
-void
-Key_List::output (void)
-{
-  T (Trace t ("Key_List::output");)
-
-  compute_min_max ();
-
-  if (option[C] | option[ANSIC] | option[CPLUSPLUS])
-    {
-      const_always = "const ";
-      const_readonly_array = (option[CONST] ? "const " : "");
-      const_for_struct = ((option[CONST] && option[TYPE]) ? "const " : "");
-    }
-  else
-    {
-      const_always = "";
-      const_readonly_array = "";
-      const_for_struct = "";
-    }
-
-  if (!option[TYPE])
-    {
-      return_type = (const_always[0] ? "const char *" : "char *");
-      struct_tag = (const_always[0] ? "const char *" : "char *");
-    }
-
-  char_to_index = (option[SEVENBIT] ? "" : "(unsigned char)");
-
-  printf ("/* ");
-  if (option[KRC])
-    printf ("KR-C");
-  else if (option[C])
-    printf ("C");
-  else if (option[ANSIC])
-    printf ("ANSI-C");
-  else if (option[CPLUSPLUS])
-    printf ("C++");
-  printf (" code produced by gperf version %s */\n", version_string);
-  Options::print_options ();
-
-  printf ("%s\n", include_src);
-
-  if (option[TYPE] && !option[NOTYPE]) /* Output type declaration now, reference it later on.... */
-    printf ("%s;\n", array_type);
-
-  if (option[INCLUDE])
-    printf ("#include <string.h>\n"); /* Declare strlen(), strcmp(), strncmp(). */
-
-  if (!option[ENUM])
-    {
-      Output_Defines style;
-      output_constants (style);
-    }
-  else if (option[GLOBAL])
-    {
-      Output_Enum style ("");
-      output_constants (style);
-    }
-
-  printf ("/* maximum key range = %d, duplicates = %d */\n\n",
-          max_hash_value - min_hash_value + 1, total_duplicates);
-
-  if (option[CPLUSPLUS])
-    printf ("class %s\n"
-            "{\n"
-            "private:\n"
-            "  static inline unsigned int %s (const char *str, unsigned int len);\n"
-            "public:\n"
-            "  static %s%s%s (const char *str, unsigned int len);\n"
-            "};\n"
-            "\n",
-            option.get_class_name (), option.get_hash_name (),
-            const_for_struct, return_type, option.get_function_name ());
-
-  output_hash_function ();
-
-  if (option[GLOBAL])
-    output_lookup_tables ();
-
-  output_lookup_function ();
-
-  if (additional_code)
-    for (int c; (c = getchar ()) != EOF; putchar (c))
-      ;
-
-  fflush (stdout);
-}
-
-/* ========================= End of Output routines ========================= */
-
-/* Sorts the keys by hash value. */
-
-void
-Key_List::sort (void)
-{
-  T (Trace t ("Key_List::sort");)
-  hash_sort       = 1;
-  occurrence_sort = 0;
-
-  head = merge_sort (head);
-}
-
-/* Dumps the key list to stderr stream. */
-
-void
-Key_List::dump ()
-{
-  T (Trace t ("Key_List::dump");)
-  int field_width = option.get_max_keysig_size ();
-
-  fprintf (stderr, "\nList contents are:\n(hash value, key length, index, %*s, keyword):\n",
-           field_width, "char_set");
-
-  for (List_Node *ptr = head; ptr; ptr = ptr->next)
-    fprintf (stderr, "%11d,%11d,%6d, %*.*s, %.*s\n",
-             ptr->hash_value, ptr->key_length, ptr->index,
-             field_width, ptr->char_set_length, ptr->char_set,
-             ptr->key_length, ptr->key);
-}
-
-/* Simple-minded constructor action here... */
-
-Key_List::Key_List (void)
-{
-  T (Trace t ("Key_List::Key_List");)
-  total_keys       = 1;
-  max_key_len      = INT_MIN;
-  min_key_len      = INT_MAX;
-  array_type       = 0;
-  return_type      = 0;
-  struct_tag       = 0;
-  head             = 0;
-  total_duplicates = 0;
-  additional_code  = 0;
-}
-
-/* Returns the length of entire key list. */
-
-int
-Key_List::keyword_list_length (void)
-{
-  T (Trace t ("Key_List::keyword_list_length");)
-  return list_len;
-}
-
-/* Returns length of longest key read. */
-
-int
-Key_List::max_key_length (void)
-{
-  T (Trace t ("Key_List::max_key_length");)
-  return max_key_len;
-}
-
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/src/key-list.h
--- a/head/contrib/gperf/src/key-list.h	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,96 +0,0 @@
-/* This may look like C code, but it is really -*- C++ -*- */
-
-/* Data and function member declarations for the keyword list class.
-
-   Copyright (C) 1989-1998 Free Software Foundation, Inc.
-   written by Douglas C. Schmidt (schmidt at ics.uci.edu)
-
-This file is part of GNU GPERF.
-
-GNU GPERF 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 1, or (at your option)
-any later version.
-
-GNU GPERF 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 GPERF; see the file COPYING.  If not, write to the Free
-Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111, USA.  */
-
-/* The key word list is a useful abstraction that keeps track of
-   various pieces of information that enable that fast generation
-   of the Gen_Perf.hash function.  A Key_List is a singly-linked
-   list of List_Nodes. */
-
-#ifndef key_list_h
-#define key_list_h 1
-
-#include "list-node.h"
-#include "vectors.h"
-#include "read-line.h"
-
-/* OSF/1 cxx needs these forward declarations. */
-struct Output_Constants;
-struct Output_Compare;
-
-class Key_List : private Read_Line, public Vectors
-{
-private:
-  const char *array_type;                            /* Pointer to the type for word list. */
-  const char *return_type;                           /* Pointer to return type for lookup function. */
-  const char *struct_tag;                            /* Shorthand for user-defined struct tag type. */
-  const char *include_src;                           /* C source code to be included verbatim. */
-  int         max_key_len;                           /* Maximum length of the longest keyword. */
-  int         min_key_len;                           /* Minimum length of the shortest keyword. */
-  int         min_hash_value;                        /* Minimum hash value for all keywords. */
-  int         max_hash_value;                        /* Maximum hash value for all keywords. */
-  int         occurrence_sort;                       /* True if sorting by occurrence. */
-  int         hash_sort;                             /* True if sorting by hash value. */
-  int         additional_code;                       /* True if any additional C code is included. */
-  int         list_len;                              /* Length of head's Key_List, not counting duplicates. */
-  int         total_keys;                            /* Total number of keys, counting duplicates. */
-  static int  determined[MAX_ALPHA_SIZE];            /* Used in function reorder, below. */
-  static int  get_occurrence (List_Node *ptr);
-#ifndef strcspn
-  static int  strcspn (const char *s, const char *reject);
-#endif
-  static int  already_determined (List_Node *ptr);
-  static void set_determined (List_Node *ptr);
-  void        compute_min_max (void);
-  int         num_hash_values (void);
-  void        output_constants (struct Output_Constants&);
-  void        output_hash_function (void);
-  void        output_keylength_table (void);
-  void        output_keyword_table (void);
-  void        output_lookup_array (void);
-  void        output_lookup_tables (void);
-  void        output_lookup_function_body (const struct Output_Compare&);
-  void        output_lookup_function (void);
-  void        set_output_types (void);
-  void        dump (void);
-  const char *get_array_type (void);
-  const char *save_include_src (void);
-  const char *get_special_input (char delimiter);
-  List_Node  *merge (List_Node *list1, List_Node *list2);
-  List_Node  *merge_sort (List_Node *head);
-
-protected:
-  List_Node  *head;                                  /* Points to the head of the linked list. */
-  int         total_duplicates;                      /* Total number of duplicate hash values. */
-
-public:
-              Key_List   (void);
-             ~Key_List  (void);
-  int         keyword_list_length (void);
-  int         max_key_length (void);
-  void        reorder (void);
-  void        sort (void);
-  void        read_keys (void);
-  void        output (void);
-};
-
-#endif
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/src/keyword-list.cc
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/contrib/gperf/src/keyword-list.cc	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,175 @@
+/* Keyword list.
+
+   Copyright (C) 2002 Free Software Foundation, Inc.
+   Written by Bruno Haible <bruno at clisp.org>.
+
+   This file is part of GNU GPERF.
+
+   GNU GPERF 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 GPERF 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; see the file COPYING.
+   If not, write to the Free Software Foundation, Inc.,
+   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
+
+/* Specification. */
+#include "keyword-list.h"
+
+#include <stddef.h>
+
+/* -------------------------- Keyword_List class --------------------------- */
+
+/* Constructor.  */
+Keyword_List::Keyword_List (Keyword *car)
+  : _cdr (NULL), _car (car)
+{
+}
+
+/* ------------------------- KeywordExt_List class ------------------------- */
+
+/* Constructor.  */
+KeywordExt_List::KeywordExt_List (KeywordExt *car)
+  : Keyword_List (car)
+{
+}
+
+/* ------------------------ Keyword_List functions ------------------------- */
+
+/* Copies a linear list, sharing the list elements.  */
+Keyword_List *
+copy_list (Keyword_List *list)
+{
+  Keyword_List *result;
+  Keyword_List **lastp = &result;
+  while (list != NULL)
+    {
+      Keyword_List *new_cons = new Keyword_List (list->first());
+      *lastp = new_cons;
+      lastp = &new_cons->rest();
+      list = list->rest();
+    }
+  *lastp = NULL;
+  return result;
+}
+
+/* Copies a linear list, sharing the list elements.  */
+KeywordExt_List *
+copy_list (KeywordExt_List *list)
+{
+  return static_cast<KeywordExt_List *> (copy_list (static_cast<Keyword_List *> (list)));
+}
+
+/* Deletes a linear list, keeping the list elements in memory.  */
+void
+delete_list (Keyword_List *list)
+{
+  while (list != NULL)
+    {
+      Keyword_List *rest = list->rest();
+      delete list;
+      list = rest;
+    }
+}
+
+/* Type of a comparison function.  */
+typedef bool (*Keyword_Comparison) (Keyword *keyword1, Keyword *keyword2);
+
+/* Merges two sorted lists together to form one sorted list.  */
+static Keyword_List *
+merge (Keyword_List *list1, Keyword_List *list2, Keyword_Comparison less)
+{
+  Keyword_List *result;
+  Keyword_List **resultp = &result;
+  for (;;)
+    {
+      if (!list1)
+        {
+          *resultp = list2;
+          break;
+        }
+      if (!list2)
+        {
+          *resultp = list1;
+          break;
+        }
+      if (less (list2->first(), list1->first()))
+        {
+          *resultp = list2;
+          resultp = &list2->rest();
+          /* We would have a stable sorting if the next line would read:
+             list2 = *resultp;  */
+          list2 = list1; list1 = *resultp;
+        }
+      else
+        {
+          *resultp = list1;
+          resultp = &list1->rest();
+          list1 = *resultp;
+        }
+    }
+  return result;
+}
+
+/* Sorts a linear list, given a comparison function.
+   Note: This uses a variant of mergesort that is *not* a stable sorting
+   algorithm.  */
+Keyword_List *
+mergesort_list (Keyword_List *list, Keyword_Comparison less)
+{
+  if (list == NULL || list->rest() == NULL)
+    /* List of length 0 or 1.  Nothing to do.  */
+    return list;
+  else
+    {
+      /* Determine a list node in the middle.  */
+      Keyword_List *middle = list;
+      for (Keyword_List *temp = list->rest();;)
+        {
+          temp = temp->rest();
+          if (temp == NULL)
+            break;
+          temp = temp->rest();
+          middle = middle->rest();
+          if (temp == NULL)
+            break;
+        }
+
+      /* Cut the list into two halves.
+         If the list has n elements, the left half has ceiling(n/2) elements
+         and the right half has floor(n/2) elements.  */
+      Keyword_List *right_half = middle->rest();
+      middle->rest() = NULL;
+
+      /* Sort the two halves, then merge them.  */
+      return merge (mergesort_list (list, less),
+                    mergesort_list (right_half, less),
+                    less);
+    }
+}
+
+KeywordExt_List *
+mergesort_list (KeywordExt_List *list,
+                bool (*less) (KeywordExt *keyword1, KeywordExt *keyword2))
+{
+  return
+    static_cast<KeywordExt_List *>
+      (mergesort_list (static_cast<Keyword_List *> (list),
+                       reinterpret_cast<Keyword_Comparison> (less)));
+}
+
+
+#ifndef __OPTIMIZE__
+
+#define INLINE /* not inline */
+#include "keyword-list.icc"
+#undef INLINE
+
+#endif /* not defined __OPTIMIZE__ */
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/src/keyword-list.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/contrib/gperf/src/keyword-list.h	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,85 @@
+/* This may look like C code, but it is really -*- C++ -*- */
+
+/* Keyword list.
+
+   Copyright (C) 2002 Free Software Foundation, Inc.
+   Written by Bruno Haible <bruno at clisp.org>.
+
+   This file is part of GNU GPERF.
+
+   GNU GPERF 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 GPERF 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; see the file COPYING.
+   If not, write to the Free Software Foundation, Inc.,
+   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
+
+#ifndef keyword_list_h
+#define keyword_list_h 1
+
+#include "keyword.h"
+
+/* List node of a linear list of Keyword.  */
+class Keyword_List
+{
+public:
+  /* Constructor.  */
+                        Keyword_List (Keyword *car);
+
+  /* Access to first element of list.  */
+  Keyword *             first () const;
+  /* Access to next element of list.  */
+  Keyword_List *&       rest ();
+
+protected:
+  Keyword_List *        _cdr;
+  Keyword * const       _car;
+};
+
+/* List node of a linear list of KeywordExt.  */
+class KeywordExt_List : public Keyword_List
+{
+public:
+  /* Constructor.  */
+                        KeywordExt_List (KeywordExt *car);
+
+  /* Access to first element of list.  */
+  KeywordExt *          first () const;
+  /* Access to next element of list.  */
+  KeywordExt_List *&    rest ();
+};
+
+/* Copies a linear list, sharing the list elements.  */
+extern Keyword_List * copy_list (Keyword_List *list);
+extern KeywordExt_List * copy_list (KeywordExt_List *list);
+
+/* Deletes a linear list, keeping the list elements in memory.  */
+extern void delete_list (Keyword_List *list);
+
+/* Sorts a linear list, given a comparison function.
+   Note: This uses a variant of mergesort that is *not* a stable sorting
+   algorithm.  */
+extern Keyword_List * mergesort_list (Keyword_List *list,
+                                      bool (*less) (Keyword *keyword1,
+                                                    Keyword *keyword2));
+extern KeywordExt_List * mergesort_list (KeywordExt_List *list,
+                                         bool (*less) (KeywordExt *keyword1,
+                                                       KeywordExt *keyword2));
+
+#ifdef __OPTIMIZE__
+
+#define INLINE inline
+#include "keyword-list.icc"
+#undef INLINE
+
+#endif
+
+#endif
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/src/keyword-list.icc
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/contrib/gperf/src/keyword-list.icc	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,53 @@
+/* Inline Functions for keyword-list.{h,cc}.
+
+   Copyright (C) 2002-2003 Free Software Foundation, Inc.
+   Written by Bruno Haible <bruno at clisp.org>.
+
+   This file is part of GNU GPERF.
+
+   GNU GPERF 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 GPERF 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; see the file COPYING.
+   If not, write to the Free Software Foundation, Inc.,
+   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
+
+/* -------------------------- Keyword_List class --------------------------- */
+
+/* Access to first element of list.  */
+INLINE Keyword *
+Keyword_List::first () const
+{
+  return _car;
+}
+
+/* Access to next element of list.  */
+INLINE Keyword_List *&
+Keyword_List::rest ()
+{
+  return _cdr;
+}
+
+/* ------------------------- KeywordExt_List class ------------------------- */
+
+/* Access to first element of list.  */
+INLINE KeywordExt *
+KeywordExt_List::first () const
+{
+  return static_cast<KeywordExt*>(_car);
+}
+
+/* Access to next element of list.  */
+INLINE KeywordExt_List *&
+KeywordExt_List::rest ()
+{
+  return *reinterpret_cast<KeywordExt_List**>(&_cdr);
+}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/src/keyword.cc
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/contrib/gperf/src/keyword.cc	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,161 @@
+/* Keyword data.
+   Copyright (C) 1989-1998, 2000, 2002 Free Software Foundation, Inc.
+   Written by Douglas C. Schmidt <schmidt at ics.uci.edu>
+   and Bruno Haible <bruno at clisp.org>.
+
+   This file is part of GNU GPERF.
+
+   GNU GPERF 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 GPERF 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; see the file COPYING.
+   If not, write to the Free Software Foundation, Inc.,
+   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
+
+/* Specification. */
+#include "keyword.h"
+
+#include <stddef.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include "positions.h"
+
+
+/* --------------------------- KeywordExt class --------------------------- */
+
+/* Sort a small set of 'unsigned int', base[0..len-1], in place.  */
+static inline void sort_char_set (unsigned int *base, int len)
+{
+  /* Bubble sort is sufficient here.  */
+  for (int i = 1; i < len; i++)
+    {
+      int j;
+      unsigned int tmp;
+
+      for (j = i, tmp = base[j]; j > 0 && tmp < base[j - 1]; j--)
+        base[j] = base[j - 1];
+
+      base[j] = tmp;
+    }
+}
+
+/* Initializes selchars and selchars_length.
+
+   General idea:
+     The hash function will be computed as
+         asso_values[allchars[key_pos[0]]] +
+         asso_values[allchars[key_pos[1]]] + ...
+     We compute selchars as the multiset
+         { allchars[key_pos[0]], allchars[key_pos[1]], ... }
+     so that the hash function becomes
+         asso_values[selchars[0]] + asso_values[selchars[1]] + ...
+   Furthermore we sort the selchars array, to ease detection of duplicates
+   later.
+
+   More in detail: The arguments alpha_unify (used for case-insensitive
+   hash functions) and alpha_inc (used to disambiguate permutations)
+   apply slight modifications. The hash function will be computed as
+       sum (j=0,1,...: k = key_pos[j]:
+            asso_values[alpha_unify[allchars[k]+alpha_inc[k]]])
+       + (allchars_length if !option[NOLENGTH], 0 otherwise).
+   We compute selchars as the multiset
+       { alpha_unify[allchars[k]+alpha_inc[k]] : j=0,1,..., k = key_pos[j] }
+   so that the hash function becomes
+       asso_values[selchars[0]] + asso_values[selchars[1]] + ...
+       + (allchars_length if !option[NOLENGTH], 0 otherwise).
+ */
+
+unsigned int *
+KeywordExt::init_selchars_low (const Positions& positions, const unsigned int *alpha_unify, const unsigned int *alpha_inc)
+{
+  /* Iterate through the list of positions, initializing selchars
+     (via ptr).  */
+  PositionIterator iter = positions.iterator(_allchars_length);
+
+  unsigned int *key_set = new unsigned int[iter.remaining()];
+  unsigned int *ptr = key_set;
+
+  for (int i; (i = iter.next ()) != PositionIterator::EOS; )
+    {
+      unsigned int c;
+      if (i == Positions::LASTCHAR)
+        /* Special notation for last KEY position, i.e. '$'.  */
+        c = static_cast<unsigned char>(_allchars[_allchars_length - 1]);
+      else if (i < _allchars_length)
+        {
+          /* Within range of KEY length, so we'll keep it.  */
+          c = static_cast<unsigned char>(_allchars[i]);
+          if (alpha_inc)
+            c += alpha_inc[i];
+        }
+      else
+        /* Out of range of KEY length, the iterator should not have
+           produced this.  */
+        abort ();
+      if (alpha_unify)
+        c = alpha_unify[c];
+      *ptr = c;
+      ptr++;
+    }
+
+  _selchars = key_set;
+  _selchars_length = ptr - key_set;
+
+  return key_set;
+}
+
+void
+KeywordExt::init_selchars_tuple (const Positions& positions, const unsigned int *alpha_unify)
+{
+  init_selchars_low (positions, alpha_unify, NULL);
+}
+
+void
+KeywordExt::init_selchars_multiset (const Positions& positions, const unsigned int *alpha_unify, const unsigned int *alpha_inc)
+{
+  unsigned int *selchars =
+    init_selchars_low (positions, alpha_unify, alpha_inc);
+
+  /* Sort the selchars elements alphabetically.  */
+  sort_char_set (selchars, _selchars_length);
+}
+
+/* Deletes selchars.  */
+void
+KeywordExt::delete_selchars ()
+{
+  delete[] const_cast<unsigned int *>(_selchars);
+}
+
+
+/* ------------------------- Keyword_Factory class ------------------------- */
+
+Keyword_Factory::Keyword_Factory ()
+{
+}
+
+Keyword_Factory::~Keyword_Factory ()
+{
+}
+
+
+/* ------------------------------------------------------------------------- */
+
+char empty_string[1] = "";
+
+
+#ifndef __OPTIMIZE__
+
+#define INLINE /* not inline */
+#include "keyword.icc"
+#undef INLINE
+
+#endif /* not defined __OPTIMIZE__ */
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/src/keyword.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/contrib/gperf/src/keyword.h	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,116 @@
+/* This may look like C code, but it is really -*- C++ -*- */
+
+/* Keyword data.
+
+   Copyright (C) 1989-1998, 2000, 2002 Free Software Foundation, Inc.
+   Written by Douglas C. Schmidt <schmidt at ics.uci.edu>
+   and Bruno Haible <bruno at clisp.org>.
+
+   This file is part of GNU GPERF.
+
+   GNU GPERF 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 GPERF 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; see the file COPYING.
+   If not, write to the Free Software Foundation, Inc.,
+   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
+
+#ifndef keyword_h
+#define keyword_h 1
+
+/* Class defined in "positions.h".  */
+class Positions;
+
+/* An instance of this class is a keyword, as specified in the input file.  */
+
+struct Keyword
+{
+  /* Constructor.  */
+                        Keyword (const char *allchars, int allchars_length,
+                                 const char *rest);
+
+  /* Data members defined immediately by the input file.  */
+  /* The keyword as a string, possibly containing NUL bytes.  */
+  const char *const     _allchars;
+  int const             _allchars_length;
+  /* Additional stuff seen on the same line of the input file.  */
+  const char *const     _rest;
+  /* Line number of this keyword in the input file.  */
+  unsigned int          _lineno;
+};
+
+/* A keyword, in the context of a given keyposition list.  */
+
+struct KeywordExt : public Keyword
+{
+  /* Constructor.  */
+                        KeywordExt (const char *allchars, int allchars_length,
+                                    const char *rest);
+
+  /* Data members depending on the keyposition list.  */
+  /* The selected characters that participate for the hash function,
+     selected according to the keyposition list, as a canonically reordered
+     multiset.  */
+  const unsigned int *  _selchars;
+  int                   _selchars_length;
+  /* Chained list of keywords having the same _selchars and
+     - if !option[NOLENGTH] - also the same _allchars_length.
+     Note that these duplicates are not members of the main keyword list.  */
+  KeywordExt *          _duplicate_link;
+
+  /* Methods depending on the keyposition list.  */
+  /* Initializes selchars and selchars_length, without reordering.  */
+  void                  init_selchars_tuple (const Positions& positions, const unsigned int *alpha_unify);
+  /* Initializes selchars and selchars_length, with reordering.  */
+  void                  init_selchars_multiset (const Positions& positions, const unsigned int *alpha_unify, const unsigned int *alpha_inc);
+  /* Deletes selchars.  */
+  void                  delete_selchars ();
+
+  /* Data members used by the algorithm.  */
+  int                   _hash_value; /* Hash value for the keyword.  */
+
+  /* Data members used by the output routines.  */
+  int                   _final_index;
+
+private:
+  unsigned int *        init_selchars_low (const Positions& positions, const unsigned int *alpha_unify, const unsigned int *alpha_inc);
+};
+
+/* An abstract factory for creating Keyword instances.
+   This factory is used to make the Input class independent of the concrete
+   class KeywordExt.  */
+
+class Keyword_Factory
+{
+public:
+  /* Constructor.  */
+                        Keyword_Factory ();
+  /* Destructor.  */
+  virtual               ~Keyword_Factory ();
+
+  /* Creates a new Keyword.  */
+  virtual /*abstract*/ Keyword *
+                        create_keyword (const char *allchars, int allchars_length,
+                                        const char *rest) = 0;
+};
+
+/* A statically allocated empty string.  */
+extern char empty_string[1];
+
+#ifdef __OPTIMIZE__
+
+#define INLINE inline
+#include "keyword.icc"
+#undef INLINE
+
+#endif
+
+#endif
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/src/keyword.icc
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/contrib/gperf/src/keyword.icc	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,42 @@
+/* Inline Functions for keyword.{h,cc}.
+
+   Copyright (C) 1989-1998, 2000, 2002 Free Software Foundation, Inc.
+   Written by Douglas C. Schmidt <schmidt at ics.uci.edu>
+   and Bruno Haible <bruno at clisp.org>.
+
+   This file is part of GNU GPERF.
+
+   GNU GPERF 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 GPERF 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; see the file COPYING.
+   If not, write to the Free Software Foundation, Inc.,
+   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
+
+/* ----------------------------- Keyword class ----------------------------- */
+
+/* Constructor.  */
+INLINE
+Keyword::Keyword (const char *allchars, int allchars_length, const char *rest)
+  : _allchars (allchars), _allchars_length (allchars_length), _rest (rest)
+{
+}
+
+
+/* --------------------------- KeywordExt class --------------------------- */
+
+/* Constructor.  */
+INLINE
+KeywordExt::KeywordExt (const char *allchars, int allchars_length, const char *rest)
+  : Keyword (allchars, allchars_length, rest),
+    _final_index (-1)
+{
+}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/src/list-node.cc
--- a/head/contrib/gperf/src/list-node.cc	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,102 +0,0 @@
-/* Creates and initializes a new list node.
-   Copyright (C) 1989-1998, 2000 Free Software Foundation, Inc.
-   written by Douglas C. Schmidt (schmidt at ics.uci.edu)
-
-This file is part of GNU GPERF.
-
-GNU GPERF 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 1, or (at your option)
-any later version.
-
-GNU GPERF 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 GPERF; see the file COPYING.  If not, write to the Free
-Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111, USA.  */
-
-#include "list-node.h"
-
-#include <stdio.h>
-#include <stdlib.h> /* declares exit() */
-#include "options.h"
-#include "trace.h"
-
-/* Sorts the key set alphabetically to speed up subsequent operations.
-   Uses insertion sort since the set is probably quite small. */
-
-inline void
-List_Node::set_sort (char *base, int len)
-{
-  T (Trace t ("List_Node::set_sort");)
-  int i, j;
-
-  for (i = 0, j = len - 1; i < j; i++)
-    {
-      char curr, tmp;
-
-      for (curr = i + 1, tmp = base[curr]; curr > 0 && tmp < base[curr-1]; curr--)
-        base[curr] = base[curr - 1];
-
-      base[curr] = tmp;
-
-    }
-}
-
-/* Initializes a List_Node.  This requires obtaining memory for the CHAR_SET
-   initializing them using the information stored in the KEY_POSITIONS array in Options,
-   and checking for simple errors.  It's important to note that KEY and REST are
-   both pointers to the different offsets into the same block of dynamic memory pointed
-   to by parameter K. The data member REST is used to store any additional fields
-   of the input file (it is set to the "" string if Option[TYPE] is not enabled).
-   This is useful if the user wishes to incorporate a lookup structure,
-   rather than just an array of keys.  Finally, KEY_NUMBER contains a count
-   of the total number of keys seen so far.  This is used to initialize
-   the INDEX field to some useful value. */
-
-List_Node::List_Node (const char *k, int len, const char *r):
-     link (0), next (0), key (k), key_length (len), rest (r), index (0)
-{
-  T (Trace t ("List_Node::List_Node");)
-  char *key_set = new char[(option[ALLCHARS] ? len : option.get_max_keysig_size ())];
-  char *ptr = key_set;
-  int i;
-
-  if (option[ALLCHARS])         /* Use all the character positions in the KEY. */
-    for (i = len; i > 0; k++, ptr++, i--)
-      ++occurrences[(unsigned char)(*ptr = *k)];
-  else                          /* Only use those character positions specified by the user. */
-    {
-      /* Iterate through the list of key_positions, initializing occurrences table
-         and char_set (via char * pointer ptr). */
-
-      for (option.reset (); (i = option.get ()) != EOS; )
-        {
-          if (i == WORD_END)            /* Special notation for last KEY position, i.e. '$'. */
-            *ptr = key[len - 1];
-          else if (i <= len)    /* Within range of KEY length, so we'll keep it. */
-            *ptr = key[i - 1];
-          else                  /* Out of range of KEY length, so we'll just skip it. */
-            continue;
-          ++occurrences[(unsigned char)(*ptr++)];
-        }
-
-      /* Didn't get any hits and user doesn't want to consider the
-        keylength, so there are essentially no usable hash positions! */
-      if (ptr == char_set && option[NOLENGTH])
-        {
-          fprintf (stderr, "Can't hash keyword %.*s with chosen key positions.\n",
-                   key_length, key);
-          exit (1);
-        }
-    }
-
-  /* Sort the KEY_SET items alphabetically. */
-  set_sort (key_set, ptr - key_set);
-
-  char_set = key_set;
-  char_set_length = ptr - key_set;
-}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/src/list-node.h
--- a/head/contrib/gperf/src/list-node.h	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,46 +0,0 @@
-/* This may look like C code, but it is really -*- C++ -*- */
-
-/* Data and function members for defining values and operations of a list node.
-
-   Copyright (C) 1989-1998, 2000 Free Software Foundation, Inc.
-   written by Douglas C. Schmidt (schmidt at ics.uci.edu)
-
-This file is part of GNU GPERF.
-
-GNU GPERF 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 1, or (at your option)
-any later version.
-
-GNU GPERF 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 GPERF; see the file COPYING.  If not, write to the Free
-Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111, USA.  */
-
-#ifndef list_node_h
-#define list_node_h 1
-
-#include "vectors.h"
-
-struct List_Node : private Vectors
-{
-  List_Node  *link;              /* TRUE if key has an identical KEY_SET as another key. */
-  List_Node  *next;              /* Points to next element on the list. */
-  const char *key;               /* Each keyword string stored here. */
-  int         key_length;        /* Length of the key. */
-  const char *rest;              /* Additional information for building hash function. */
-  const char *char_set;          /* Set of characters to hash, specified by user. */
-  int         char_set_length;   /* Length of char_set. */
-  int         hash_value;        /* Hash value for the key. */
-  int         occurrence;        /* A metric for frequency of key set occurrences. */
-  int         index;             /* Position of this node relative to other nodes. */
-
-              List_Node (const char *key, int len, const char *rest);
-  static void set_sort (char *base, int len);
-};
-
-#endif
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/src/main.cc
--- a/head/contrib/gperf/src/main.cc	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/contrib/gperf/src/main.cc	Tue Dec 06 20:26:16 2011 +0200
@@ -1,76 +1,155 @@
-/* Driver program for the Gen_Perf hash function generator
-   Copyright (C) 1989-1998, 2000 Free Software Foundation, Inc.
-   written by Douglas C. Schmidt (schmidt at ics.uci.edu)
+/* Driver program for the hash function generator
+   Copyright (C) 1989-1998, 2000, 2002-2003 Free Software Foundation, Inc.
+   Written by Douglas C. Schmidt <schmidt at ics.uci.edu>
+   and Bruno Haible <bruno at clisp.org>.
 
-This file is part of GNU GPERF.
+   This file is part of GNU GPERF.
 
-GNU GPERF 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 1, or (at your option)
-any later version.
+   GNU GPERF 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 GPERF 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.
+   GNU GPERF 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 GPERF; see the file COPYING.  If not, write to the Free
-Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111, USA.  */
-
-/* Simple driver program for the Gen_Perf.hash function generator.
-   Most of the hard work is done in class Gen_Perf and its class methods. */
-
-#include "config.h"
-#include <sys/types.h>
-#if LARGE_STACK_ARRAYS && defined(HAVE_GETRLIMIT) && defined(HAVE_SETRLIMIT)
-#ifdef HAVE_SYS_TIME_H
-#include <sys/time.h>
-#endif
-#ifdef HAVE_SYS_RESOURCE_H
-#include <sys/resource.h>
-#endif
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
-#endif
-#endif
+   You should have received a copy of the GNU General Public License
+   along with this program; see the file COPYING.
+   If not, write to the Free Software Foundation, Inc.,
+   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
 
 #include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
 #include "options.h"
-#include "gen-perf.h"
-#include "trace.h"
+#include "input.h"
+#include "search.h"
+#include "output.h"
+
+
+/* ------------------------------------------------------------------------- */
+
+/* This Keyword factory produces KeywordExt instances.  */
+
+class KeywordExt_Factory : public Keyword_Factory
+{
+virtual Keyword *       create_keyword (const char *allchars, int allchars_length,
+                                        const char *rest);
+};
+
+Keyword *
+KeywordExt_Factory::create_keyword (const char *allchars, int allchars_length, const char *rest)
+{
+  return new KeywordExt (allchars, allchars_length, rest);
+}
+
+/* ------------------------------------------------------------------------- */
 
 int
 main (int argc, char *argv[])
 {
-  T (Trace t ("main");)
+  int exitcode;
 
-#if LARGE_STACK_ARRAYS && defined(HAVE_GETRLIMIT) && defined(HAVE_SETRLIMIT) && defined(RLIMIT_STACK)
-  /* Get rid of any avoidable limit on stack size.  */
+  /* Set the Options.  Open the input file and assign stdin to it.  */
+  option.parse_options (argc, argv);
+
+  /* Open the input file.  */
+  if (option.get_input_file_name ())
+    if (!freopen (option.get_input_file_name (), "r", stdin))
+      {
+        fprintf (stderr, "Cannot open input file '%s'\n",
+                 option.get_input_file_name ());
+        exit (1);
+      }
+
   {
-    struct rlimit rlim;
-    if (getrlimit (RLIMIT_STACK, &rlim) == 0)
-      if (rlim.rlim_cur < rlim.rlim_max)
-        {
-          rlim.rlim_cur = rlim.rlim_max;
-          setrlimit (RLIMIT_STACK, &rlim);
-        }
+    /* Initialize the keyword list.  */
+    KeywordExt_Factory factory;
+    Input inputter (stdin, &factory);
+    inputter.read_input ();
+    /* We can cast the keyword list to KeywordExt_List* because its list
+       elements were created by KeywordExt_Factory.  */
+    KeywordExt_List* list = static_cast<KeywordExt_List*>(inputter._head);
+
+    {
+      /* Search for a good hash function.  */
+      Search searcher (list);
+      searcher.optimize ();
+      list = searcher._head;
+
+      /* Open the output file.  */
+      if (option.get_output_file_name ())
+        if (strcmp (option.get_output_file_name (), "-") != 0)
+          if (!freopen (option.get_output_file_name (), "w", stdout))
+            {
+              fprintf (stderr, "Cannot open output file '%s'\n",
+                       option.get_output_file_name ());
+              exit (1);
+            }
+
+      {
+        /* Output the hash function code.  */
+        Output outputter (searcher._head,
+                          inputter._struct_decl,
+                          inputter._struct_decl_lineno,
+                          inputter._return_type,
+                          inputter._struct_tag,
+                          inputter._verbatim_declarations,
+                          inputter._verbatim_declarations_end,
+                          inputter._verbatim_declarations_lineno,
+                          inputter._verbatim_code,
+                          inputter._verbatim_code_end,
+                          inputter._verbatim_code_lineno,
+                          inputter._charset_dependent,
+                          searcher._total_keys,
+                          searcher._max_key_len,
+                          searcher._min_key_len,
+                          searcher._key_positions,
+                          searcher._alpha_inc,
+                          searcher._total_duplicates,
+                          searcher._alpha_size,
+                          searcher._asso_values);
+        outputter.output ();
+
+        /* Check for write error on stdout.  */
+        exitcode = 0;
+        if (fflush (stdout) || ferror (stdout))
+          {
+            fprintf (stderr, "error while writing output file\n");
+            exitcode = 1;
+          }
+
+        /* Here we run the Output destructor.  */
+      }
+      /* Here we run the Search destructor.  */
+    }
+
+    /* Also delete the list that was allocated inside Input and reordered
+       inside Search.  */
+    for (KeywordExt_List *ptr = list; ptr; ptr = ptr->rest())
+      {
+        KeywordExt *keyword = ptr->first();
+        do
+          {
+            KeywordExt *next_keyword = keyword->_duplicate_link;
+            delete[] const_cast<unsigned int *>(keyword->_selchars);
+            if (keyword->_rest != empty_string)
+              delete[] const_cast<char*>(keyword->_rest);
+            if (!(keyword->_allchars >= inputter._input
+                  && keyword->_allchars < inputter._input_end))
+              delete[] const_cast<char*>(keyword->_allchars);
+            delete keyword;
+            keyword = next_keyword;
+          }
+        while (keyword != NULL);
+      }
+    delete_list (list);
+
+    /* Here we run the Input destructor.  */
   }
-#endif /* RLIMIT_STACK */
 
-  /* Sets the Options. */
-  option (argc, argv);
-
-  /* Initializes the key word list. */
-  Gen_Perf generate_table;
-
-  /* Generates and prints the Gen_Perf hash table. */
-  int status = generate_table ();
-
-  /* Check for write error on stdout. */
-  if (fflush (stdout) || ferror (stdout))
-    status = 1;
-
-  /* Don't use exit() here, it skips the destructors. */
-  return status;
+  /* Don't use exit() here, it skips the destructors.  */
+  return exitcode;
 }
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/src/new.cc
--- a/head/contrib/gperf/src/new.cc	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,87 +0,0 @@
-/* Defines a buffered memory allocation abstraction that reduces calls to
-   malloc.
-   Copyright (C) 1989-1998 Free Software Foundation, Inc.
-   written by Douglas C. Schmidt (schmidt at ics.uci.edu)
-
-This file is part of GNU GPERF.
-
-GNU GPERF 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 1, or (at your option)
-any later version.
-
-GNU GPERF 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 GPERF; see the file COPYING.  If not, write to the Free
-Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111, USA.  */
-
-#include "config.h"
-#include <stdio.h>
-#include <stdlib.h> /* declares malloc(), exit() */
-#include "trace.h"
-
-/* Determine default alignment.  If your C++ compiler does not
-   like this then try something like #define DEFAULT_ALIGNMENT 8. */
-struct fooalign {char x; double d;};
-const int ALIGNMENT = ((char *)&((struct fooalign *) 0)->d - (char *)0);
-
-/* Provide an abstraction that cuts down on the number of
-   calls to NEW by buffering the memory pool from which
-   strings are allocated. */
-
-void *
-operator new (size_t size)
-{
-  T (Trace t ("operator new");)
-  static char *buf_start = 0;          /* Large array used to reduce calls to NEW. */
-  static char *buf_end = 0;            /* Indicates end of BUF_START. */
-  static size_t buf_size = 4096;       /* Size of buffer pointed to by BUF_START. */
-         char *temp;
-
-  /* Align this on correct boundaries, just to be safe... */
-  size = ((size + ALIGNMENT - 1) / ALIGNMENT) * ALIGNMENT;
-
-  /* If we are about to overflow our buffer we'll just grab another
-     chunk of memory.  Since we never free the original memory it
-     doesn't matter that no one points to the beginning of that
-     chunk. Note we use a heuristic that grows the buffer either by
-     size of the request or by twice the previous size, whichever is
-     larger. */
-
-  if (buf_start + size >= buf_end)
-    {
-      buf_size *= 2;
-      if (buf_size < size)
-        buf_size = size;
-      if ((buf_start = (char *)malloc (buf_size)) != (char *)0)
-        buf_end = buf_start + buf_size;
-      else
-        {
-          fprintf (stderr, "Virtual memory exhausted in `operator new'\n");
-          exit (1);
-        }
-    }
-
-  temp = buf_start;
-  buf_start += size;
-  return temp;
-}
-
-/* We need this deletion operator in order to make the linker happy.
-   Because `operator new' and `operator delete' always come together.  */
-
-void
-operator delete (void *ptr)
-#ifdef HAVE_THROW_DECL
-  throw()
-#endif
-{
-  T (Trace t ("operator delete");)
-  // We cannot call free here, as it doesn't match the mallocs.
-  // free ((char *) ptr);
-  (void) ptr;
-}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/src/options.cc
--- a/head/contrib/gperf/src/options.cc	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/contrib/gperf/src/options.cc	Tue Dec 06 20:26:16 2011 +0200
@@ -1,151 +1,192 @@
 /* Handles parsing the Options provided to the user.
-   Copyright (C) 1989-1998, 2000 Free Software Foundation, Inc.
-   written by Douglas C. Schmidt (schmidt at ics.uci.edu)
+   Copyright (C) 1989-1998, 2000, 2002-2004, 2006-2007 Free Software Foundation, Inc.
+   Written by Douglas C. Schmidt <schmidt at ics.uci.edu>
+   and Bruno Haible <bruno at clisp.org>.
 
-This file is part of GNU GPERF.
+   This file is part of GNU GPERF.
 
-GNU GPERF 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 1, or (at your option)
-any later version.
+   GNU GPERF 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 GPERF 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.
+   GNU GPERF 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 GPERF; see the file COPYING.  If not, write to the Free
-Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111, USA.  */
+   You should have received a copy of the GNU General Public License
+   along with this program; see the file COPYING.
+   If not, write to the Free Software Foundation, Inc.,
+   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
+
+/* Specification. */
+#include "options.h"
 
 #include <stdio.h>
 #include <stdlib.h> /* declares atoi(), abs(), exit() */
 #include <string.h> /* declares strcmp() */
+#include <ctype.h>  /* declares isdigit() */
+#include <limits.h> /* defines CHAR_MAX */
 #include "getopt.h"
-#include "options.h"
-#include "iterator.h"
-#include "trace.h"
-#include "vectors.h"
 #include "version.h"
 
-/* Global option coordinator for the entire program. */
+/* Global option coordinator for the entire program.  */
 Options option;
 
-/* Records the program name. */
+/* Records the program name.  */
 const char *program_name;
 
-/* Size to jump on a collision. */
+/* Size to jump on a collision.  */
 static const int DEFAULT_JUMP_VALUE = 5;
 
-/* Default name for generated lookup function. */
-static const char *const DEFAULT_NAME = "in_word_set";
+/* Default name for generated lookup function.  */
+static const char *const DEFAULT_FUNCTION_NAME = "in_word_set";
 
-/* Default name for the key component. */
-static const char *const DEFAULT_KEY = "name";
+/* Default name for the key component.  */
+static const char *const DEFAULT_SLOT_NAME = "name";
 
-/* Default struct initializer suffix. */
+/* Default struct initializer suffix.  */
 static const char *const DEFAULT_INITIALIZER_SUFFIX = "";
 
-/* Default name for the generated class. */
+/* Default name for the generated class.  */
 static const char *const DEFAULT_CLASS_NAME = "Perfect_Hash";
 
-/* Default name for generated hash function. */
+/* Default name for generated hash function.  */
 static const char *const DEFAULT_HASH_NAME = "hash";
 
-/* Default name for generated hash table array. */
+/* Default name for generated hash table array.  */
 static const char *const DEFAULT_WORDLIST_NAME = "wordlist";
 
-/* Default delimiters that separate keywords from their attributes. */
-static const char *const DEFAULT_DELIMITERS = ",\n";
+/* Default name for generated length table array.  */
+static const char *const DEFAULT_LENGTHTABLE_NAME = "lengthtable";
 
-int Options::option_word;
-int Options::total_switches;
-int Options::total_keysig_size;
-int Options::size;
-int Options::key_pos;
-int Options::jump;
-int Options::initial_asso_value;
-int Options::argument_count;
-int Options::iterations;
-char **Options::argument_vector;
-const char *Options::function_name;
-const char *Options::key_name;
-const char *Options::initializer_suffix;
-const char *Options::class_name;
-const char *Options::hash_name;
-const char *Options::wordlist_name;
-const char *Options::delimiters;
-char Options::key_positions[MAX_KEY_POS];
+/* Default name for string pool.  */
+static const char *const DEFAULT_STRINGPOOL_NAME = "stringpool";
 
-/* Prints program usage to given stream. */
+/* Default delimiters that separate keywords from their attributes.  */
+static const char *const DEFAULT_DELIMITERS = ",";
+
+/* Prints program usage to given stream.  */
 
 void
-Options::short_usage (FILE * strm)
+Options::short_usage (FILE * stream)
 {
-  T (Trace t ("Options::short_usage");)
-  fprintf (strm, "Usage: %s [-cCdDef[num]F<initializers>GhH<hashname>i<init>Ijk<keys>K<keyname>lL<language>nN<function name>ors<size>S<switches>tTvW<wordlistname>Z<class name>7] [input-file]\n"
-                 "Try `%s --help' for more information.\n",
-                 program_name, program_name);
+  fprintf (stream,
+           "Try '%s --help' for more information.\n", program_name);
 }
 
 void
-Options::long_usage (FILE * strm)
+Options::long_usage (FILE * stream)
 {
-  T (Trace t ("Options::long_usage");)
-  fprintf (strm,
-           "GNU `gperf' generates perfect hash functions.\n"
-           "\n"
-           "Usage: %s [OPTION]... [INPUT-FILE]\n"
-           "\n"
+  fprintf (stream,
+           "GNU 'gperf' generates perfect hash functions.\n");
+  fprintf (stream, "\n");
+  fprintf (stream,
+           "Usage: %s [OPTION]... [INPUT-FILE]\n",
+           program_name);
+  fprintf (stream, "\n");
+  fprintf (stream,
            "If a long option shows an argument as mandatory, then it is mandatory\n"
-           "for the equivalent short option also.\n"
-           "\n"
-           "Input file interpretation:\n"
+           "for the equivalent short option also.\n");
+  fprintf (stream, "\n");
+  fprintf (stream,
+           "Output file location:\n");
+  fprintf (stream,
+           "      --output-file=FILE Write output to specified file.\n");
+  fprintf (stream,
+           "The results are written to standard output if no output file is specified\n"
+           "or if it is -.\n");
+  fprintf (stream, "\n");
+  fprintf (stream,
+           "Input file interpretation:\n");
+  fprintf (stream,
            "  -e, --delimiters=DELIMITER-LIST\n"
            "                         Allow user to provide a string containing delimiters\n"
            "                         used to separate keywords from their attributes.\n"
-           "                         Default is \",\\n\".\n"
+           "                         Default is \",\".\n");
+  fprintf (stream,
            "  -t, --struct-type      Allows the user to include a structured type\n"
            "                         declaration for generated code. Any text before %%%%\n"
            "                         is considered part of the type declaration. Key\n"
            "                         words and additional fields may follow this, one\n"
-           "                         group of fields per line.\n"
-           "\n"
-           "Language for the output code:\n"
+           "                         group of fields per line.\n");
+  fprintf (stream,
+           "      --ignore-case      Consider upper and lower case ASCII characters as\n"
+           "                         equivalent. Note that locale dependent case mappings\n"
+           "                         are ignored.\n");
+  fprintf (stream, "\n");
+  fprintf (stream,
+           "Language for the output code:\n");
+  fprintf (stream,
            "  -L, --language=LANGUAGE-NAME\n"
            "                         Generates code in the specified language. Languages\n"
            "                         handled are currently C++, ANSI-C, C, and KR-C. The\n"
-           "                         default is C.\n"
-           "\n"
-           "Details in the output code:\n"
+           "                         default is C.\n");
+  fprintf (stream, "\n");
+  fprintf (stream,
+           "Details in the output code:\n");
+  fprintf (stream,
            "  -K, --slot-name=NAME   Select name of the keyword component in the keyword\n"
-           "                         structure.\n"
+           "                         structure.\n");
+  fprintf (stream,
            "  -F, --initializer-suffix=INITIALIZERS\n"
            "                         Initializers for additional components in the keyword\n"
-           "                         structure.\n"
-           "  -H, --hash-fn-name=NAME\n"
+           "                         structure.\n");
+  fprintf (stream,
+           "  -H, --hash-function-name=NAME\n"
            "                         Specify name of generated hash function. Default is\n"
-           "                         `hash'.\n"
-           "  -N, --lookup-fn-name=NAME\n"
+           "                         'hash'.\n");
+  fprintf (stream,
+           "  -N, --lookup-function-name=NAME\n"
            "                         Specify name of generated lookup function. Default\n"
-           "                         name is `in_word_set'.\n"
+           "                         name is 'in_word_set'.\n");
+  fprintf (stream,
            "  -Z, --class-name=NAME  Specify name of generated C++ class. Default name is\n"
-           "                         `Perfect_Hash'.\n"
-           "  -7, --seven-bit        Assume 7-bit characters.\n"
+           "                         'Perfect_Hash'.\n");
+  fprintf (stream,
+           "  -7, --seven-bit        Assume 7-bit characters.\n");
+  fprintf (stream,
+           "  -l, --compare-lengths  Compare key lengths before trying a string\n"
+           "                         comparison. This is necessary if the keywords\n"
+           "                         contain NUL bytes. It also helps cut down on the\n"
+           "                         number of string comparisons made during the lookup.\n");
+  fprintf (stream,
            "  -c, --compare-strncmp  Generate comparison code using strncmp rather than\n"
-           "                         strcmp.\n"
+           "                         strcmp.\n");
+  fprintf (stream,
            "  -C, --readonly-tables  Make the contents of generated lookup tables\n"
-           "                         constant, i.e., readonly.\n"
+           "                         constant, i.e., readonly.\n");
+  fprintf (stream,
            "  -E, --enum             Define constant values using an enum local to the\n"
-           "                         lookup function rather than with defines.\n"
+           "                         lookup function rather than with defines.\n");
+  fprintf (stream,
            "  -I, --includes         Include the necessary system include file <string.h>\n"
-           "                         at the beginning of the code.\n"
-           "  -G, --global           Generate the static table of keywords as a static\n"
+           "                         at the beginning of the code.\n");
+  fprintf (stream,
+           "  -G, --global-table     Generate the static table of keywords as a static\n"
            "                         global variable, rather than hiding it inside of the\n"
-           "                         lookup function (which is the default behavior).\n"
+           "                         lookup function (which is the default behavior).\n");
+  fprintf (stream,
+           "  -P, --pic              Optimize the generated table for inclusion in shared\n"
+           "                         libraries.  This reduces the startup time of programs\n"
+           "                         using a shared library containing the generated code.\n");
+  fprintf (stream,
+           "  -Q, --string-pool-name=NAME\n"
+           "                         Specify name of string pool generated by option --pic.\n"
+           "                         Default name is 'stringpool'.\n");
+  fprintf (stream,
+           "      --null-strings     Use NULL strings instead of empty strings for empty\n"
+           "                         keyword table entries.\n");
+  fprintf (stream,
            "  -W, --word-array-name=NAME\n"
            "                         Specify name of word list array. Default name is\n"
-           "                         `wordlist'.\n"
+           "                         'wordlist'.\n");
+  fprintf (stream,
+           "      --length-table-name=NAME\n"
+           "                         Specify name of length table array. Default name is\n"
+           "                         'lengthtable'.\n");
+  fprintf (stream,
            "  -S, --switch=COUNT     Causes the generated C code to use a switch\n"
            "                         statement scheme, rather than an array lookup table.\n"
            "                         This can lead to a reduction in both time and space\n"
@@ -155,13 +196,16 @@
            "                         elements, a value of 2 generates 2 tables with 1/2\n"
            "                         the elements in each table, etc. If COUNT is very\n"
            "                         large, say 1000000, the generated C code does a\n"
-           "                         binary search.\n"
+           "                         binary search.\n");
+  fprintf (stream,
            "  -T, --omit-struct-type\n"
            "                         Prevents the transfer of the type declaration to the\n"
            "                         output file. Use this option if the type is already\n"
-           "                         defined elsewhere.\n"
-           "\n"
-           "Algorithm employed by gperf:\n"
+           "                         defined elsewhere.\n");
+  fprintf (stream, "\n");
+  fprintf (stream,
+           "Algorithm employed by gperf:\n");
+  fprintf (stream,
            "  -k, --key-positions=KEYS\n"
            "                         Select the key positions used in the hash function.\n"
            "                         The allowable choices range between 1-%d, inclusive.\n"
@@ -169,79 +213,93 @@
            "                         used, and key positions may occur in any order.\n"
            "                         Also, the meta-character '*' causes the generated\n"
            "                         hash function to consider ALL key positions, and $\n"
-           "                         indicates the ``final character'' of a key, e.g.,\n"
-           "                         $,1,2,4,6-10.\n"
-           "  -l, --compare-strlen   Compare key lengths before trying a string\n"
-           "                         comparison. This helps cut down on the number of\n"
-           "                         string comparisons made during the lookup.\n"
+           "                         indicates the \"final character\" of a key, e.g.,\n"
+           "                         $,1,2,4,6-10.\n",
+           Positions::MAX_KEY_POS);
+  fprintf (stream,
            "  -D, --duplicates       Handle keywords that hash to duplicate values. This\n"
-           "                         is useful for certain highly redundant keyword sets.\n"
-           "  -f, --fast=ITERATIONS  Generate the gen-perf.hash function ``fast''. This\n"
-           "                         decreases gperf's running time at the cost of\n"
-           "                         minimizing generated table size. The numeric\n"
-           "                         argument represents the number of times to iterate\n"
-           "                         when resolving a collision. `0' means ``iterate by\n"
-           "                         the number of keywords''.\n"
+           "                         is useful for certain highly redundant keyword sets.\n");
+  fprintf (stream,
+           "  -m, --multiple-iterations=ITERATIONS\n"
+           "                         Perform multiple choices of the -i and -j values,\n"
+           "                         and choose the best results. This increases the\n"
+           "                         running time by a factor of ITERATIONS but does a\n"
+           "                         good job minimizing the generated table size.\n");
+  fprintf (stream,
            "  -i, --initial-asso=N   Provide an initial value for the associate values\n"
            "                         array. Default is 0. Setting this value larger helps\n"
-           "                         inflate the size of the final table.\n"
-           "  -j, --jump=JUMP-VALUE  Affects the ``jump value'', i.e., how far to advance\n"
+           "                         inflate the size of the final table.\n");
+  fprintf (stream,
+           "  -j, --jump=JUMP-VALUE  Affects the \"jump value\", i.e., how far to advance\n"
            "                         the associated character value upon collisions. Must\n"
-           "                         be an odd number, default is %d.\n"
+           "                         be an odd number, default is %d.\n",
+           DEFAULT_JUMP_VALUE);
+  fprintf (stream,
            "  -n, --no-strlen        Do not include the length of the keyword when\n"
-           "                         computing the hash function.\n"
-           "  -o, --occurrence-sort  Reorders input keys by frequency of occurrence of\n"
-           "                         the key sets. This should decrease the search time\n"
-           "                         dramatically.\n"
+           "                         computing the hash function.\n");
+  fprintf (stream,
            "  -r, --random           Utilizes randomness to initialize the associated\n"
-           "                         values table.\n"
+           "                         values table.\n");
+  fprintf (stream,
            "  -s, --size-multiple=N  Affects the size of the generated hash table. The\n"
-           "                         numeric argument N indicates ``how many times larger\n"
-           "                         or smaller'' the associated value range should be,\n"
+           "                         numeric argument N indicates \"how many times larger\n"
+           "                         or smaller\" the associated value range should be,\n"
            "                         in relationship to the number of keys, e.g. a value\n"
-           "                         of 3 means ``allow the maximum associated value to\n"
+           "                         of 3 means \"allow the maximum associated value to\n"
            "                         be about 3 times larger than the number of input\n"
-           "                         keys.'' Conversely, a value of -3 means ``make the\n"
+           "                         keys\". Conversely, a value of 1/3 means \"make the\n"
            "                         maximum associated value about 3 times smaller than\n"
-           "                         the number of input keys. A larger table should\n"
+           "                         the number of input keys\". A larger table should\n"
            "                         decrease the time required for an unsuccessful\n"
            "                         search, at the expense of extra table space. Default\n"
-           "                         value is 1.\n"
-           "\n"
+           "                         value is 1.\n");
+  fprintf (stream, "\n");
+  fprintf (stream,
            "Informative output:\n"
            "  -h, --help             Print this message.\n"
            "  -v, --version          Print the gperf version number.\n"
            "  -d, --debug            Enables the debugging option (produces verbose\n"
-           "                         output to the standard error).\n"
-           "\n"
-           "Report bugs to <bug-gnu-utils at gnu.org>.\n"
-           , program_name, MAX_KEY_POS - 1, DEFAULT_JUMP_VALUE);
+           "                         output to the standard error).\n");
+  fprintf (stream, "\n");
+  fprintf (stream,
+           "Report bugs to <bug-gnu-gperf at gnu.org>.\n");
 }
 
-/* Output command-line Options. */
+/* Prints the given options.  */
 
 void
-Options::print_options (void)
+Options::print_options () const
 {
-  T (Trace t ("Options::print_options");)
-  int i;
-
   printf ("/* Command-line: ");
 
-  for (i = 0; i < argument_count; i++)
+  for (int i = 0; i < _argument_count; i++)
     {
-      const char *arg = argument_vector[i];
+      const char *arg = _argument_vector[i];
 
-      /* Escape arg if it contains shell metacharacters. */
+      /* Escape arg if it contains shell metacharacters.  */
       if (*arg == '-')
         {
           putchar (*arg);
           arg++;
-          if ((*arg >= 'A' && *arg <= 'Z') || (*arg >= 'a' && *arg <= 'z'))
+          if (*arg >= 'A' && *arg <= 'Z' || *arg >= 'a' && *arg <= 'z')
             {
               putchar (*arg);
               arg++;
             }
+          else if (*arg == '-')
+            {
+              do
+                {
+                  putchar (*arg);
+                  arg++;
+                }
+              while (*arg >= 'A' && *arg <= 'Z' || *arg >= 'a' && *arg <= 'z' || *arg == '-');
+              if (*arg == '=')
+                {
+                  putchar (*arg);
+                  arg++;
+                }
+            }
         }
       if (strpbrk (arg, "\t\n !\"#$&'()*;<>?[\\]`{|}~") != NULL)
         {
@@ -250,7 +308,7 @@
               putchar ('"');
               for (; *arg; arg++)
                 {
-                  if (*arg == '\"' || *arg == '\\' || *arg == '$')
+                  if (*arg == '\"' || *arg == '\\' || *arg == '$' || *arg == '`')
                     putchar ('\\');
                   putchar (*arg);
                 }
@@ -277,389 +335,653 @@
   printf (" */");
 }
 
-/* Sorts the key positions *IN REVERSE ORDER!!*
-   This makes further routines more efficient.  Especially when generating code.
-   Uses a simple Insertion Sort since the set is probably ordered.
-   Returns 1 if there are no duplicates, 0 otherwise. */
+/* ------------------------------------------------------------------------- */
 
-inline int
-Options::key_sort (char *base, int len)
+/* Parses a string denoting key positions.  */
+
+class PositionStringParser
 {
-  T (Trace t ("Options::key_sort");)
-  int i, j;
+public:
+  /* Initializes a key position string parser for string STR.  */
+                        PositionStringParser (const char *str,
+                                              int low_bound, int high_bound,
+                                              int end_word_marker, int error_value, int end_marker);
+  /* Returns the next key position from the given string.  */
+  int                   nextPosition ();
+private:
+  /* A pointer to the string provided by the user.  */
+  const char *          _str;
+  /* Smallest possible value, inclusive.  */
+  int const             _low_bound;
+  /* Greatest possible value, inclusive.  */
+  int const             _high_bound;
+  /* A value marking the abstract "end of word" ( usually '$').  */
+  int const             _end_word_marker;
+  /* Error value returned when input is syntactically erroneous.  */
+  int const             _error_value;
+  /* Value returned after last key is processed.  */
+  int const             _end_marker;
+  /* Intermediate state for producing a range of positions.  */
+  bool                  _in_range;           /* True while producing a range of positions.  */
+  int                   _range_upper_bound;  /* Upper bound (inclusive) of the range.  */
+  int                   _range_curr_value;   /* Last value returned.  */
+};
 
-  for (i = 0, j = len - 1; i < j; i++)
-    {
-      int curr, tmp;
-
-      for (curr = i + 1,tmp = base[curr]; curr > 0 && tmp >= base[curr - 1]; curr--)
-        if ((base[curr] = base[curr - 1]) == tmp) /* oh no, a duplicate!!! */
-          return 0;
-
-      base[curr] = tmp;
-    }
-
-  return 1;
+/* Initializes a key position strng parser for string STR.  */
+PositionStringParser::PositionStringParser (const char *str,
+                                            int low_bound, int high_bound,
+                                            int end_word_marker, int error_value, int end_marker)
+  : _str (str),
+    _low_bound (low_bound),
+    _high_bound (high_bound),
+    _end_word_marker (end_word_marker),
+    _error_value (error_value),
+    _end_marker (end_marker),
+    _in_range (false)
+{
 }
 
-/* Sets the default Options. */
+/* Returns the next key position from the given string.  */
+int
+PositionStringParser::nextPosition ()
+{
+  if (_in_range)
+    {
+      /* We are inside a range.  Return the next value from the range.  */
+      if (++_range_curr_value >= _range_upper_bound)
+        _in_range = false;
+      return _range_curr_value;
+    }
+  else
+    {
+      /* Continue parsing the given string.  */
+      while (*_str)
+        switch (*_str)
+          {
+          case ',':
+            /* Skip the comma.  */
+            _str++;
+            break;
+          case '$':
+            /* Valid key position.  */
+            _str++;
+            return _end_word_marker;
+          case '0': case '1': case '2': case '3': case '4':
+          case '5': case '6': case '7': case '8': case '9':
+            /* Valid key position.  */
+            {
+              int curr_value;
+              for (curr_value = 0; isdigit (static_cast<unsigned char>(*_str)); _str++)
+                curr_value = curr_value * 10 + (*_str - '0');
 
-Options::Options (void)
-{
-  T (Trace t ("Options::Options");)
-  key_positions[0]    = WORD_START;
-  key_positions[1]    = WORD_END;
-  key_positions[2]    = EOS;
-  total_keysig_size  = 2;
-  delimiters          = DEFAULT_DELIMITERS;
-  jump                = DEFAULT_JUMP_VALUE;
-  option_word         = DEFAULTCHARS | C;
-  function_name       = DEFAULT_NAME;
-  key_name            = DEFAULT_KEY;
-  initializer_suffix  = DEFAULT_INITIALIZER_SUFFIX;
-  hash_name           = DEFAULT_HASH_NAME;
-  wordlist_name       = DEFAULT_WORDLIST_NAME;
-  class_name          = DEFAULT_CLASS_NAME;
-  total_switches      = size = 1;
-  initial_asso_value  = iterations = 0;
+              if (*_str == '-')
+                {
+                  _str++;
+                  /* Starting a range of key positions.  */
+                  _in_range = true;
+
+                  for (_range_upper_bound = 0;
+                       isdigit (static_cast<unsigned char>(*_str));
+                       _str++)
+                    _range_upper_bound = _range_upper_bound * 10 + (*_str - '0');
+
+                  /* Verify range's upper bound.  */
+                  if (!(_range_upper_bound > curr_value && _range_upper_bound <= _high_bound))
+                    return _error_value;
+                  _range_curr_value = curr_value;
+                }
+
+              /* Verify range's lower bound.  */
+              if (!(curr_value >= _low_bound && curr_value <= _high_bound))
+                return _error_value;
+              return curr_value;
+            }
+          default:
+            /* Invalid syntax.  */
+            return _error_value;
+          }
+
+      return _end_marker;
+    }
 }
 
-/* Dumps option status when debug is set. */
+/* ------------------------------------------------------------------------- */
 
-Options::~Options (void)
+/* Sets the default Options.  */
+
+Options::Options ()
+  : _option_word (C),
+    _input_file_name (NULL),
+    _output_file_name (NULL),
+    _language (NULL),
+    _jump (DEFAULT_JUMP_VALUE),
+    _initial_asso_value (0),
+    _asso_iterations (0),
+    _total_switches (1),
+    _size_multiple (1),
+    _function_name (DEFAULT_FUNCTION_NAME),
+    _slot_name (DEFAULT_SLOT_NAME),
+    _initializer_suffix (DEFAULT_INITIALIZER_SUFFIX),
+    _class_name (DEFAULT_CLASS_NAME),
+    _hash_name (DEFAULT_HASH_NAME),
+    _wordlist_name (DEFAULT_WORDLIST_NAME),
+    _lengthtable_name (DEFAULT_LENGTHTABLE_NAME),
+    _stringpool_name (DEFAULT_STRINGPOOL_NAME),
+    _delimiters (DEFAULT_DELIMITERS),
+    _key_positions ()
 {
-  T (Trace t ("Options::~Options");)
-  if (option_word & DEBUG)
+}
+
+/* Dumps option status when debugging is enabled.  */
+
+Options::~Options ()
+{
+  if (_option_word & DEBUG)
     {
-      char *ptr;
-
       fprintf (stderr, "\ndumping Options:"
-               "\nDEBUG is.......: %s"
-               "\nORDER is.......: %s"
                "\nTYPE is........: %s"
-               "\nRANDOM is......: %s"
-               "\nDEFAULTCHARS is: %s"
-               "\nSWITCH is......: %s"
-               "\nNOLENGTH is....: %s"
-               "\nLENTABLE is....: %s"
-               "\nDUP is.........: %s"
-               "\nFAST is........: %s"
-               "\nCOMP is........: %s"
-               "\nNOTYPE is......: %s"
-               "\nGLOBAL is......: %s"
-               "\nCONST is.......: %s"
+               "\nUPPERLOWER is..: %s"
                "\nKRC is.........: %s"
                "\nC is...........: %s"
                "\nANSIC is.......: %s"
                "\nCPLUSPLUS is...: %s"
+               "\nSEVENBIT is....: %s"
+               "\nLENTABLE is....: %s"
+               "\nCOMP is........: %s"
+               "\nCONST is.......: %s"
                "\nENUM is........: %s"
                "\nINCLUDE is.....: %s"
-               "\nSEVENBIT is....: %s"
-               "\niterations = %d"
+               "\nGLOBAL is......: %s"
+               "\nNULLSTRINGS is.: %s"
+               "\nSHAREDLIB is...: %s"
+               "\nSWITCH is......: %s"
+               "\nNOTYPE is......: %s"
+               "\nDUP is.........: %s"
+               "\nNOLENGTH is....: %s"
+               "\nRANDOM is......: %s"
+               "\nDEBUG is.......: %s"
                "\nlookup function name = %s"
                "\nhash function name = %s"
                "\nword list name = %s"
-               "\nkey name = %s"
+               "\nlength table name = %s"
+               "\nstring pool name = %s"
+               "\nslot name = %s"
                "\ninitializer suffix = %s"
+               "\nasso_values iterations = %d"
                "\njump value = %d"
-               "\nmax associated value = %d"
+               "\nhash table size multiplier = %g"
                "\ninitial associated value = %d"
                "\ndelimiters = %s"
                "\nnumber of switch statements = %d\n",
-               option_word & DEBUG ? "enabled" : "disabled",
-               option_word & ORDER ? "enabled" : "disabled",
-               option_word & TYPE ? "enabled" : "disabled",
-               option_word & RANDOM ? "enabled" : "disabled",
-               option_word & DEFAULTCHARS ? "enabled" : "disabled",
-               option_word & SWITCH ? "enabled" : "disabled",
-               option_word & NOLENGTH ? "enabled" : "disabled",
-               option_word & LENTABLE ? "enabled" : "disabled",
-               option_word & DUP ? "enabled" : "disabled",
-               option_word & FAST ? "enabled" : "disabled",
-               option_word & COMP ? "enabled" : "disabled",
-               option_word & NOTYPE ? "enabled" : "disabled",
-               option_word & GLOBAL ? "enabled" : "disabled",
-               option_word & CONST ? "enabled" : "disabled",
-               option_word & KRC ? "enabled" : "disabled",
-               option_word & C ? "enabled" : "disabled",
-               option_word & ANSIC ? "enabled" : "disabled",
-               option_word & CPLUSPLUS ? "enabled" : "disabled",
-               option_word & ENUM ? "enabled" : "disabled",
-               option_word & INCLUDE ? "enabled" : "disabled",
-               option_word & SEVENBIT ? "enabled" : "disabled",
-               iterations,
-               function_name, hash_name, wordlist_name, key_name,
-               initializer_suffix, jump, size - 1, initial_asso_value,
-               delimiters, total_switches);
-      if (option_word & ALLCHARS)
+               _option_word & TYPE ? "enabled" : "disabled",
+               _option_word & UPPERLOWER ? "enabled" : "disabled",
+               _option_word & KRC ? "enabled" : "disabled",
+               _option_word & C ? "enabled" : "disabled",
+               _option_word & ANSIC ? "enabled" : "disabled",
+               _option_word & CPLUSPLUS ? "enabled" : "disabled",
+               _option_word & SEVENBIT ? "enabled" : "disabled",
+               _option_word & LENTABLE ? "enabled" : "disabled",
+               _option_word & COMP ? "enabled" : "disabled",
+               _option_word & CONST ? "enabled" : "disabled",
+               _option_word & ENUM ? "enabled" : "disabled",
+               _option_word & INCLUDE ? "enabled" : "disabled",
+               _option_word & GLOBAL ? "enabled" : "disabled",
+               _option_word & NULLSTRINGS ? "enabled" : "disabled",
+               _option_word & SHAREDLIB ? "enabled" : "disabled",
+               _option_word & SWITCH ? "enabled" : "disabled",
+               _option_word & NOTYPE ? "enabled" : "disabled",
+               _option_word & DUP ? "enabled" : "disabled",
+               _option_word & NOLENGTH ? "enabled" : "disabled",
+               _option_word & RANDOM ? "enabled" : "disabled",
+               _option_word & DEBUG ? "enabled" : "disabled",
+               _function_name, _hash_name, _wordlist_name, _lengthtable_name,
+               _stringpool_name, _slot_name, _initializer_suffix,
+               _asso_iterations, _jump, _size_multiple, _initial_asso_value,
+               _delimiters, _total_switches);
+      if (_key_positions.is_useall())
         fprintf (stderr, "all characters are used in the hash function\n");
+      else
+        {
+          fprintf (stderr, "maximum keysig size = %d\nkey positions are: \n",
+                   _key_positions.get_size());
 
-      fprintf (stderr, "maximum keysig size = %d\nkey positions are: \n",
-               total_keysig_size);
-
-      for (ptr = key_positions; *ptr != EOS; ptr++)
-        if (*ptr == WORD_END)
-          fprintf (stderr, "$\n");
-        else
-          fprintf (stderr, "%d\n", *ptr);
+          PositionIterator iter = _key_positions.iterator();
+          for (int pos; (pos = iter.next()) != PositionIterator::EOS; )
+            if (pos == Positions::LASTCHAR)
+              fprintf (stderr, "$\n");
+            else
+              fprintf (stderr, "%d\n", pos + 1);
+        }
 
       fprintf (stderr, "finished dumping Options\n");
     }
 }
 
 
-/* Parses the command line Options and sets appropriate flags in option_word. */
+/* Sets the output language, if not already set.  */
+void
+Options::set_language (const char *language)
+{
+  if (_language == NULL)
+    {
+      _language = language;
+      _option_word &= ~(KRC | C | ANSIC | CPLUSPLUS);
+      if (!strcmp (language, "KR-C"))
+        _option_word |= KRC;
+      else if (!strcmp (language, "C"))
+        _option_word |= C;
+      else if (!strcmp (language, "ANSI-C"))
+        _option_word |= ANSIC;
+      else if (!strcmp (language, "C++"))
+        _option_word |= CPLUSPLUS;
+      else
+        {
+          fprintf (stderr, "unsupported language option %s, defaulting to C\n",
+                   language);
+          _option_word |= C;
+        }
+    }
+}
+
+/* Sets the total number of switch statements, if not already set.  */
+void
+Options::set_total_switches (int total_switches)
+{
+  if (!(_option_word & SWITCH))
+    {
+      _option_word |= SWITCH;
+      _total_switches = total_switches;
+    }
+}
+
+/* Sets the generated function name, if not already set.  */
+void
+Options::set_function_name (const char *name)
+{
+  if (_function_name == DEFAULT_FUNCTION_NAME)
+    _function_name = name;
+}
+
+/* Sets the keyword key name, if not already set.  */
+void
+Options::set_slot_name (const char *name)
+{
+  if (_slot_name == DEFAULT_SLOT_NAME)
+    _slot_name = name;
+}
+
+/* Sets the struct initializer suffix, if not already set.  */
+void
+Options::set_initializer_suffix (const char *initializers)
+{
+  if (_initializer_suffix == DEFAULT_INITIALIZER_SUFFIX)
+    _initializer_suffix = initializers;
+}
+
+/* Sets the generated class name, if not already set.  */
+void
+Options::set_class_name (const char *name)
+{
+  if (_class_name == DEFAULT_CLASS_NAME)
+    _class_name = name;
+}
+
+/* Sets the hash function name, if not already set.  */
+void
+Options::set_hash_name (const char *name)
+{
+  if (_hash_name == DEFAULT_HASH_NAME)
+    _hash_name = name;
+}
+
+/* Sets the hash table array name, if not already set.  */
+void
+Options::set_wordlist_name (const char *name)
+{
+  if (_wordlist_name == DEFAULT_WORDLIST_NAME)
+    _wordlist_name = name;
+}
+
+/* Sets the length table array name, if not already set.  */
+void
+Options::set_lengthtable_name (const char *name)
+{
+  if (_lengthtable_name == DEFAULT_LENGTHTABLE_NAME)
+    _lengthtable_name = name;
+}
+
+/* Sets the string pool name, if not already set.  */
+void
+Options::set_stringpool_name (const char *name)
+{
+  if (_stringpool_name == DEFAULT_STRINGPOOL_NAME)
+    _stringpool_name = name;
+}
+
+/* Sets the delimiters string, if not already set.  */
+void
+Options::set_delimiters (const char *delimiters)
+{
+  if (_delimiters == DEFAULT_DELIMITERS)
+    _delimiters = delimiters;
+}
+
+
+/* Parses the command line Options and sets appropriate flags in option_word.  */
 
 static const struct option long_options[] =
 {
-  { "delimiters", required_argument, 0, 'e' },
-  { "struct-type", no_argument, 0, 't' },
-  { "language", required_argument, 0, 'L' },
-  { "slot-name", required_argument, 0, 'K' },
-  { "initializer-suffix", required_argument, 0, 'F' },
-  { "hash-fn-name", required_argument, 0, 'H' },
-  { "lookup-fn-name", required_argument, 0, 'N' },
-  { "class-name", required_argument, 0, 'Z' },
-  { "seven-bit", no_argument, 0, '7' },
-  { "compare-strncmp", no_argument, 0, 'c' },
-  { "readonly-tables", no_argument, 0, 'C' },
-  { "enum", no_argument, 0, 'E' },
-  { "includes", no_argument, 0, 'I' },
-  { "global", no_argument, 0, 'G' },
-  { "word-array-name", required_argument, 0, 'W' },
-  { "switch", required_argument, 0, 'S' },
-  { "omit-struct-type", no_argument, 0, 'T' },
-  { "key-positions", required_argument, 0, 'k' },
-  { "compare-strlen", no_argument, 0, 'l' },
-  { "duplicates", no_argument, 0, 'D' },
-  { "fast", required_argument, 0, 'f' },
-  { "initial-asso", required_argument, 0, 'i' },
-  { "jump", required_argument, 0, 'j' },
-  { "no-strlen", no_argument, 0, 'n' },
-  { "occurrence-sort", no_argument, 0, 'o' },
-  { "random", no_argument, 0, 'r' },
-  { "size-multiple", required_argument, 0, 's' },
-  { "help", no_argument, 0, 'h' },
-  { "version", no_argument, 0, 'v' },
-  { "debug", no_argument, 0, 'd' },
-  { 0, no_argument, 0, 0 }
+  { "output-file", required_argument, NULL, CHAR_MAX + 1 },
+  { "ignore-case", no_argument, NULL, CHAR_MAX + 2 },
+  { "delimiters", required_argument, NULL, 'e' },
+  { "struct-type", no_argument, NULL, 't' },
+  { "language", required_argument, NULL, 'L' },
+  { "slot-name", required_argument, NULL, 'K' },
+  { "initializer-suffix", required_argument, NULL, 'F' },
+  { "hash-fn-name", required_argument, NULL, 'H' }, /* backward compatibility */
+  { "hash-function-name", required_argument, NULL, 'H' },
+  { "lookup-fn-name", required_argument, NULL, 'N' }, /* backward compatibility */
+  { "lookup-function-name", required_argument, NULL, 'N' },
+  { "class-name", required_argument, NULL, 'Z' },
+  { "seven-bit", no_argument, NULL, '7' },
+  { "compare-strncmp", no_argument, NULL, 'c' },
+  { "readonly-tables", no_argument, NULL, 'C' },
+  { "enum", no_argument, NULL, 'E' },
+  { "includes", no_argument, NULL, 'I' },
+  { "global-table", no_argument, NULL, 'G' },
+  { "word-array-name", required_argument, NULL, 'W' },
+  { "length-table-name", required_argument, NULL, CHAR_MAX + 4 },
+  { "switch", required_argument, NULL, 'S' },
+  { "omit-struct-type", no_argument, NULL, 'T' },
+  { "key-positions", required_argument, NULL, 'k' },
+  { "compare-strlen", no_argument, NULL, 'l' }, /* backward compatibility */
+  { "compare-lengths", no_argument, NULL, 'l' },
+  { "duplicates", no_argument, NULL, 'D' },
+  { "fast", required_argument, NULL, 'f' },
+  { "initial-asso", required_argument, NULL, 'i' },
+  { "jump", required_argument, NULL, 'j' },
+  { "multiple-iterations", required_argument, NULL, 'm' },
+  { "no-strlen", no_argument, NULL, 'n' },
+  { "occurrence-sort", no_argument, NULL, 'o' },
+  { "optimized-collision-resolution", no_argument, NULL, 'O' },
+  { "pic", no_argument, NULL, 'P' },
+  { "string-pool-name", required_argument, NULL, 'Q' },
+  { "null-strings", no_argument, NULL, CHAR_MAX + 3 },
+  { "random", no_argument, NULL, 'r' },
+  { "size-multiple", required_argument, NULL, 's' },
+  { "help", no_argument, NULL, 'h' },
+  { "version", no_argument, NULL, 'v' },
+  { "debug", no_argument, NULL, 'd' },
+  { NULL, no_argument, NULL, 0 }
 };
 
 void
-Options::operator() (int argc, char *argv[])
+Options::parse_options (int argc, char *argv[])
 {
-  T (Trace t ("Options::operator()");)
-  int    option_char;
+  int option_char;
 
   program_name = argv[0];
-  argument_count  = argc;
-  argument_vector = argv;
+  _argument_count  = argc;
+  _argument_vector = argv;
 
   while ((option_char =
-            getopt_long (argument_count, argument_vector,
-                         "adcCDe:Ef:F:gGhH:i:Ij:k:K:lL:nN:oprs:S:tTvW:Z:7",
-                         long_options, (int *)0))
+            getopt_long (_argument_count, _argument_vector,
+                         "acCdDe:Ef:F:gGhH:i:Ij:k:K:lL:m:nN:oOpPQ:rs:S:tTvW:Z:7",
+                         long_options, NULL))
          != -1)
     {
       switch (option_char)
         {
-        case 'a':               /* Generated code uses the ANSI prototype format. */
-          break;                /* This is now the default. */
-        case 'c':               /* Generate strncmp rather than strcmp. */
+        case 'a':               /* Generated code uses the ANSI prototype format.  */
+          break;                /* This is now the default.  */
+        case 'c':               /* Generate strncmp rather than strcmp.  */
           {
-            option_word |= COMP;
+            _option_word |= COMP;
             break;
           }
-        case 'C':               /* Make the generated tables readonly (const). */
+        case 'C':               /* Make the generated tables readonly (const).  */
           {
-            option_word |= CONST;
+            _option_word |= CONST;
             break;
           }
-        case 'd':               /* Enable debugging option. */
+        case 'd':               /* Enable debugging option.  */
           {
-            option_word |= DEBUG;
+            _option_word |= DEBUG;
             fprintf (stderr, "Starting program %s, version %s, with debugging on.\n",
                              program_name, version_string);
             break;
           }
-        case 'D':               /* Enable duplicate option. */
+        case 'D':               /* Enable duplicate option.  */
           {
-            option_word |= DUP;
+            _option_word |= DUP;
             break;
           }
-        case 'e': /* Allows user to provide keyword/attribute separator */
+        case 'e':               /* Specify keyword/attribute separator */
           {
-            option.delimiters = /*getopt*/optarg;
+            _delimiters = /*getopt*/optarg;
             break;
           }
         case 'E':
           {
-            option_word |= ENUM;
+            _option_word |= ENUM;
             break;
           }
-        case 'f':               /* Generate the hash table ``fast.'' */
+        case 'f':               /* Generate the hash table "fast".  */
+          break;                /* Not needed any more.  */
+        case 'F':
           {
-            option_word |= FAST;
-            if ((iterations = atoi (/*getopt*/optarg)) < 0)
-              {
-                fprintf (stderr, "iterations value must not be negative, assuming 0\n");
-                iterations = 0;
-              }
+            _initializer_suffix = /*getopt*/optarg;
             break;
           }
-        case 'F':
+        case 'g':               /* Use the 'inline' keyword for generated sub-routines, ifdef __GNUC__.  */
+          break;                /* This is now the default.  */
+        case 'G':               /* Make the keyword table a global variable.  */
           {
-            initializer_suffix = /*getopt*/optarg;
+            _option_word |= GLOBAL;
             break;
           }
-        case 'g':               /* Use the ``inline'' keyword for generated sub-routines, ifdef __GNUC__. */
-          break;                /* This is now the default. */
-        case 'G':               /* Make the keyword table a global variable. */
-          {
-            option_word |= GLOBAL;
-            break;
-          }
-        case 'h':               /* Displays a list of helpful Options to the user. */
+        case 'h':               /* Displays a list of helpful Options to the user.  */
           {
             long_usage (stdout);
             exit (0);
           }
-        case 'H':               /* Sets the name for the hash function */
+        case 'H':               /* Sets the name for the hash function.  */
           {
-            hash_name = /*getopt*/optarg;
+            _hash_name = /*getopt*/optarg;
             break;
           }
-        case 'i':               /* Sets the initial value for the associated values array. */
+        case 'i':               /* Sets the initial value for the associated values array.  */
           {
-            if ((initial_asso_value = atoi (/*getopt*/optarg)) < 0)
-              fprintf (stderr, "Initial value %d should be non-zero, ignoring and continuing.\n", initial_asso_value);
+            if ((_initial_asso_value = atoi (/*getopt*/optarg)) < 0)
+              fprintf (stderr, "Initial value %d should be non-zero, ignoring and continuing.\n", _initial_asso_value);
             if (option[RANDOM])
               fprintf (stderr, "warning, -r option superceeds -i, ignoring -i option and continuing\n");
             break;
           }
-        case 'I':               /* Enable #include statements. */
+        case 'I':               /* Enable #include statements.  */
           {
-            option_word |= INCLUDE;
+            _option_word |= INCLUDE;
             break;
           }
-        case 'j':               /* Sets the jump value, must be odd for later algorithms. */
+        case 'j':               /* Sets the jump value, must be odd for later algorithms.  */
           {
-            if ((jump = atoi (/*getopt*/optarg)) < 0)
+            if ((_jump = atoi (/*getopt*/optarg)) < 0)
               {
-                fprintf (stderr, "Jump value %d must be a positive number.\n", jump);
+                fprintf (stderr, "Jump value %d must be a positive number.\n", _jump);
                 short_usage (stderr);
                 exit (1);
               }
-            else if (jump && ((jump % 2) == 0))
-              fprintf (stderr, "Jump value %d should be odd, adding 1 and continuing...\n", jump++);
+            else if (_jump && ((_jump % 2) == 0))
+              fprintf (stderr, "Jump value %d should be odd, adding 1 and continuing...\n", _jump++);
             break;
           }
-        case 'k':               /* Sets key positions used for hash function. */
+        case 'k':               /* Sets key positions used for hash function.  */
           {
-            const int BAD_VALUE = -1;
+            _option_word |= POSITIONS;
+            const int BAD_VALUE = -3;
+            const int EOS = PositionIterator::EOS;
             int       value;
-            Iterator  expand (/*getopt*/optarg, 1, MAX_KEY_POS - 1, WORD_END, BAD_VALUE, EOS);
+            PositionStringParser sparser (/*getopt*/optarg, 1, Positions::MAX_KEY_POS, Positions::LASTCHAR, BAD_VALUE, EOS);
 
             if (/*getopt*/optarg [0] == '*') /* Use all the characters for hashing!!!! */
-              option_word = (option_word & ~DEFAULTCHARS) | ALLCHARS;
+              _key_positions.set_useall(true);
             else
               {
-                char *key_pos;
+                _key_positions.set_useall(false);
+                int *key_positions = _key_positions.pointer();
+                int *key_pos;
 
-                for (key_pos = key_positions; (value = expand ()) != EOS; key_pos++)
-                  if (value == BAD_VALUE)
-                    {
-                      fprintf (stderr, "Illegal key value or range, use 1,2,3-%d,'$' or '*'.\n",
-                                       MAX_KEY_POS - 1);
-                      short_usage (stderr);
-                      exit (1);
-                    }
-                  else
-                    *key_pos = value;;
+                for (key_pos = key_positions; (value = sparser.nextPosition()) != EOS; key_pos++)
+                  {
+                    if (value == BAD_VALUE)
+                      {
+                        fprintf (stderr, "Invalid position value or range, use 1,2,3-%d,'$' or '*'.\n",
+                                         Positions::MAX_KEY_POS);
+                        short_usage (stderr);
+                        exit (1);
+                      }
+                    if (key_pos - key_positions == Positions::MAX_SIZE)
+                      {
+                        /* More than Positions::MAX_SIZE key positions.
+                           Since all key positions are in the range
+                           0..Positions::MAX_KEY_POS-1 or == Positions::LASTCHAR,
+                           there must be duplicates.  */
+                        fprintf (stderr, "Duplicate key positions selected\n");
+                        short_usage (stderr);
+                        exit (1);
+                      }
+                    if (value != Positions::LASTCHAR)
+                      /* We use 0-based indices in the class Positions.  */
+                      value = value - 1;
+                    *key_pos = value;
+                  }
 
-                *key_pos = EOS;
-
-                if (! (total_keysig_size = (key_pos - key_positions)))
+                unsigned int total_keysig_size = key_pos - key_positions;
+                if (total_keysig_size == 0)
                   {
-                    fprintf (stderr, "No keys selected.\n");
+                    fprintf (stderr, "No key positions selected.\n");
                     short_usage (stderr);
                     exit (1);
                   }
-                else if (! key_sort (key_positions, total_keysig_size))
+                _key_positions.set_size (total_keysig_size);
+
+                /* Sorts the key positions *IN REVERSE ORDER!!*
+                   This makes further routines more efficient.  Especially
+                   when generating code.  */
+                if (! _key_positions.sort())
                   {
-                    fprintf (stderr, "Duplicate keys selected\n");
+                    fprintf (stderr, "Duplicate key positions selected\n");
                     short_usage (stderr);
                     exit (1);
                   }
-
-                if (total_keysig_size != 2
-                    || (key_positions[0] != 1 || key_positions[1] != WORD_END))
-                  option_word &= ~DEFAULTCHARS;
               }
             break;
           }
-        case 'K':               /* Make this the keyname for the keyword component field. */
+        case 'K':               /* Make this the keyname for the keyword component field.  */
           {
-            key_name = /*getopt*/optarg;
+            _slot_name = /*getopt*/optarg;
             break;
           }
-        case 'l':               /* Create length table to avoid extra string compares. */
+        case 'l':               /* Create length table to avoid extra string compares.  */
           {
-            option_word |= LENTABLE;
+            _option_word |= LENTABLE;
             break;
           }
-        case 'L':               /* Deal with different generated languages. */
+        case 'L':               /* Deal with different generated languages.  */
           {
-            option_word &= ~(KRC | C | ANSIC | CPLUSPLUS);
-            if (!strcmp (/*getopt*/optarg, "KR-C"))
-              option_word |= KRC;
-            else if (!strcmp (/*getopt*/optarg, "C"))
-              option_word |= C;
-            else if (!strcmp (/*getopt*/optarg, "ANSI-C"))
-              option_word |= ANSIC;
-            else if (!strcmp (/*getopt*/optarg, "C++"))
-              option_word |= CPLUSPLUS;
-            else
+            _language = NULL;
+            set_language (/*getopt*/optarg);
+            break;
+          }
+        case 'm':               /* Multiple iterations for finding good asso_values.  */
+          {
+            if ((_asso_iterations = atoi (/*getopt*/optarg)) < 0)
               {
-                fprintf (stderr, "unsupported language option %s, defaulting to C\n", /*getopt*/optarg);
-                option_word |= C;
+                fprintf (stderr, "asso_iterations value must not be negative, assuming 0\n");
+                _asso_iterations = 0;
               }
             break;
           }
-        case 'n':               /* Don't include the length when computing hash function. */
+        case 'n':               /* Don't include the length when computing hash function.  */
           {
-            option_word |= NOLENGTH;
+            _option_word |= NOLENGTH;
             break;
           }
-        case 'N':               /* Make generated lookup function name be optarg */
+        case 'N':               /* Make generated lookup function name be optarg.  */
           {
-            function_name = /*getopt*/optarg;
+            _function_name = /*getopt*/optarg;
             break;
           }
-        case 'o':               /* Order input by frequency of key set occurrence. */
+        case 'o':               /* Order input by frequency of key set occurrence.  */
+          break;                /* Not needed any more.  */
+        case 'O':               /* Optimized choice during collision resolution.  */
+          break;                /* Not needed any more.  */
+        case 'p':               /* Generated lookup function a pointer instead of int.  */
+          break;                /* This is now the default.  */
+        case 'P':               /* Optimize for position-independent code.  */
           {
-            option_word |= ORDER;
+            _option_word |= SHAREDLIB;
             break;
           }
-        case 'p':               /* Generated lookup function a pointer instead of int. */
-          break;                /* This is now the default. */
-        case 'r':               /* Utilize randomness to initialize the associated values table. */
+        case 'Q':               /* Sets the name for the string pool.  */
           {
-            option_word |= RANDOM;
-            if (option.initial_asso_value != 0)
-              fprintf (stderr, "warning, -r option superceeds -i, disabling -i option and continuing\n");
+            _stringpool_name = /*getopt*/optarg;
             break;
           }
-        case 's':               /* Range of associated values, determines size of final table. */
+        case 'r':               /* Utilize randomness to initialize the associated values table.  */
           {
-            if (abs (size = atoi (/*getopt*/optarg)) > 50)
-              fprintf (stderr, "%d is excessive, did you really mean this?! (try `%s --help' for help)\n", size, program_name);
+            _option_word |= RANDOM;
+            if (_initial_asso_value != 0)
+              fprintf (stderr, "warning, -r option supersedes -i, disabling -i option and continuing\n");
             break;
           }
-        case 'S':               /* Generate switch statement output, rather than lookup table. */
+        case 's':               /* Range of associated values, determines size of final table.  */
           {
-            option_word |= SWITCH;
-            if ((option.total_switches = atoi (/*getopt*/optarg)) <= 0)
+            float numerator;
+            float denominator = 1;
+            bool invalid = false;
+            char *endptr;
+
+            numerator = strtod (/*getopt*/optarg, &endptr);
+            if (endptr == /*getopt*/optarg)
+              invalid = true;
+            else if (*endptr != '\0')
+              {
+                if (*endptr == '/')
+                  {
+                    char *denomptr = endptr + 1;
+                    denominator = strtod (denomptr, &endptr);
+                    if (endptr == denomptr || *endptr != '\0')
+                      invalid = true;
+                  }
+                else
+                  invalid = true;
+              }
+            if (invalid)
+              {
+                fprintf (stderr, "Invalid value for option -s.\n");
+                short_usage (stderr);
+                exit (1);
+              }
+            _size_multiple = numerator / denominator;
+            /* Backward compatibility: -3 means 1/3.  */
+            if (_size_multiple < 0)
+              _size_multiple = 1 / (-_size_multiple);
+            /* Catch stupid users.  */
+            if (_size_multiple == 0)
+              _size_multiple = 1;
+            /* Warnings.  */
+            if (_size_multiple > 50)
+              fprintf (stderr, "Size multiple %g is excessive, did you really mean this?! (try '%s --help' for help)\n", _size_multiple, program_name);
+            else if (_size_multiple < 0.01f)
+              fprintf (stderr, "Size multiple %g is extremely small, did you really mean this?! (try '%s --help' for help)\n", _size_multiple, program_name);
+            break;
+          }
+        case 'S':               /* Generate switch statement output, rather than lookup table.  */
+          {
+            _option_word |= SWITCH;
+            _total_switches = atoi (/*getopt*/optarg);
+            if (_total_switches <= 0)
               {
                 fprintf (stderr, "number of switches %s must be a positive number\n", /*getopt*/optarg);
                 short_usage (stderr);
@@ -667,33 +989,59 @@
               }
             break;
           }
-        case 't':               /* Enable the TYPE mode, allowing arbitrary user structures. */
+        case 't':               /* Enable the TYPE mode, allowing arbitrary user structures.  */
           {
-            option_word |= TYPE;
+            _option_word |= TYPE;
             break;
           }
-        case 'T':   /* Don't print structure definition. */
+        case 'T':               /* Don't print structure definition.  */
           {
-            option_word |= NOTYPE;
+            _option_word |= NOTYPE;
             break;
           }
-        case 'v':               /* Print out the version and quit. */
+        case 'v':               /* Print out the version and quit.  */
           fprintf (stdout, "GNU gperf %s\n", version_string);
+          fprintf (stdout, "Copyright (C) %s Free Software Foundation, Inc.\n\
+This is free software; see the source for copying conditions.  There is NO\n\
+warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\
+",
+                   "1989-1998, 2000-2004, 2006-2007");
+          fprintf (stdout, "Written by %s and %s.\n",
+                   "Douglas C. Schmidt", "Bruno Haible");
           exit (0);
-        case 'W':               /* Sets the name for the hash table array */
+        case 'W':               /* Sets the name for the hash table array.  */
           {
-            wordlist_name = /*getopt*/optarg;
+            _wordlist_name = /*getopt*/optarg;
             break;
           }
-        case 'Z':               /* Set the class name. */
+        case 'Z':               /* Set the class name.  */
           {
-            class_name = /*getopt*/optarg;
+            _class_name = /*getopt*/optarg;
             break;
           }
-        case '7':               /* Assume 7-bit characters. */
+        case '7':               /* Assume 7-bit characters.  */
           {
-            option_word |= SEVENBIT;
-            Vectors::ALPHA_SIZE = 128;
+            _option_word |= SEVENBIT;
+            break;
+          }
+        case CHAR_MAX + 1:      /* Set the output file name.  */
+          {
+            _output_file_name = /*getopt*/optarg;
+            break;
+          }
+        case CHAR_MAX + 2:      /* Case insignificant.  */
+          {
+            _option_word |= UPPERLOWER;
+            break;
+          }
+        case CHAR_MAX + 3:      /* Use NULL instead of "".  */
+          {
+            _option_word |= NULLSTRINGS;
+            break;
+          }
+        case CHAR_MAX + 4:      /* Sets the name for the length table array.  */
+          {
+            _lengthtable_name = /*getopt*/optarg;
             break;
           }
         default:
@@ -703,14 +1051,10 @@
 
     }
 
-  if (argv[/*getopt*/optind] && ! freopen (argv[/*getopt*/optind], "r", stdin))
-    {
-      fprintf (stderr, "Cannot open keyword file `%s'\n", argv[/*getopt*/optind]);
-      short_usage (stderr);
-      exit (1);
-    }
+  if (/*getopt*/optind < argc)
+    _input_file_name = argv[/*getopt*/optind++];
 
-  if (++/*getopt*/optind < argc)
+  if (/*getopt*/optind < argc)
     {
       fprintf (stderr, "Extra trailing arguments to %s.\n", program_name);
       short_usage (stderr);
@@ -718,6 +1062,8 @@
     }
 }
 
+/* ------------------------------------------------------------------------- */
+
 #ifndef __OPTIMIZE__
 
 #define INLINE /* not inline */
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/src/options.h
--- a/head/contrib/gperf/src/options.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/contrib/gperf/src/options.h	Tue Dec 06 20:26:16 2011 +0200
@@ -2,154 +2,292 @@
 
 /* Handles parsing the Options provided to the user.
 
-   Copyright (C) 1989-1998, 2000 Free Software Foundation, Inc.
-   written by Douglas C. Schmidt (schmidt at ics.uci.edu)
+   Copyright (C) 1989-1998, 2000, 2002-2004 Free Software Foundation, Inc.
+   Written by Douglas C. Schmidt <schmidt at ics.uci.edu>
+   and Bruno Haible <bruno at clisp.org>.
 
-This file is part of GNU GPERF.
+   This file is part of GNU GPERF.
 
-GNU GPERF 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 1, or (at your option)
-any later version.
+   GNU GPERF 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 GPERF 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.
+   GNU GPERF 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 GPERF; see the file COPYING.  If not, write to the Free
-Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111, USA.  */
+   You should have received a copy of the GNU General Public License
+   along with this program; see the file COPYING.
+   If not, write to the Free Software Foundation, Inc.,
+   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
 
 /* This module provides a uniform interface to the various options available
-   to a user of the gperf hash function generator.  In addition to the
-   run-time options, found in the Option_Type below, there is also the
-   hash table Size and the Keys to be used in the hashing.
-   The overall design of this module was an experiment in using C++
-   classes as a mechanism to enhance centralization of option and
-   and error handling, which tend to get out of hand in a C program. */
+   to a user of the gperf hash function generator.  */
 
 #ifndef options_h
 #define options_h 1
 
 #include <stdio.h>
+#include "positions.h"
 
-/* Enumerate the potential debugging Options. */
+/* Enumeration of the possible boolean options.  */
 
 enum Option_Type
 {
-  DEBUG        = 01,            /* Enable debugging (prints diagnostics to stderr). */
-  ORDER        = 02,            /* Apply ordering heuristic to speed-up search time. */
-  ALLCHARS     = 04,            /* Use all characters in hash function. */
-  TYPE         = 010,           /* Handle user-defined type structured keyword input. */
-  RANDOM       = 020,           /* Randomly initialize the associated values table. */
-  DEFAULTCHARS = 040,           /* Make default char positions be 1,$ (end of keyword). */
-  SWITCH       = 0100,          /* Generate switch output to save space. */
-  NOLENGTH     = 0200,          /* Don't include keyword length in hash computations. */
-  LENTABLE     = 0400,          /* Generate a length table for string comparison. */
-  DUP          = 01000,         /* Handle duplicate hash values for keywords. */
-  FAST         = 02000,         /* Generate the hash function ``fast.'' */
-  NOTYPE       = 04000,         /* Don't include user-defined type definition in output -- it's already defined elsewhere. */
-  COMP         = 010000,        /* Generate strncmp rather than strcmp. */
-  GLOBAL       = 020000,        /* Make the keyword table a global variable. */
-  CONST        = 040000,        /* Make the generated tables readonly (const). */
-  KRC          = 0100000,       /* Generate K&R C code: no prototypes, no const. */
-  C            = 0200000,       /* Generate C code: no prototypes, but const (user can #define it away). */
-  ANSIC        = 0400000,       /* Generate ISO/ANSI C code: prototypes and const, but no class. */
-  CPLUSPLUS    = 01000000,      /* Generate C++ code: prototypes, const, class, inline, enum. */
-  ENUM         = 02000000,      /* Use enum for constants. */
-  INCLUDE      = 04000000,      /* Generate #include statements. */
-  SEVENBIT     = 010000000      /* Assume 7-bit, not 8-bit, characters. */
+  /* --- Input file interpretation --- */
+
+  /* Handle user-defined type structured keyword input.  */
+  TYPE         = 1 << 0,
+
+  /* Ignore case of ASCII characters.  */
+  UPPERLOWER   = 1 << 1,
+
+  /* --- Language for the output code --- */
+
+  /* Generate K&R C code: no prototypes, no const.  */
+  KRC          = 1 << 2,
+
+  /* Generate C code: no prototypes, but const (user can #define it away).  */
+  C            = 1 << 3,
+
+  /* Generate ISO/ANSI C code: prototypes and const, but no class.  */
+  ANSIC        = 1 << 4,
+
+  /* Generate C++ code: prototypes, const, class, inline, enum.  */
+  CPLUSPLUS    = 1 << 5,
+
+  /* --- Details in the output code --- */
+
+  /* Assume 7-bit, not 8-bit, characters.  */
+  SEVENBIT     = 1 << 6,
+
+  /* Generate a length table for string comparison.  */
+  LENTABLE     = 1 << 7,
+
+  /* Generate strncmp rather than strcmp.  */
+  COMP         = 1 << 8,
+
+  /* Make the generated tables readonly (const).  */
+  CONST        = 1 << 9,
+
+  /* Use enum for constants.  */
+  ENUM         = 1 << 10,
+
+  /* Generate #include statements.  */
+  INCLUDE      = 1 << 11,
+
+  /* Make the keyword table a global variable.  */
+  GLOBAL       = 1 << 12,
+
+  /* Use NULL strings instead of empty strings for empty table entries.  */
+  NULLSTRINGS  = 1 << 13,
+
+  /* Optimize for position-independent code.  */
+  SHAREDLIB    = 1 << 14,
+
+  /* Generate switch output to save space.  */
+  SWITCH       = 1 << 15,
+
+  /* Don't include user-defined type definition in output -- it's already
+     defined elsewhere.  */
+  NOTYPE       = 1 << 16,
+
+  /* --- Algorithm employed by gperf --- */
+
+  /* Use the given key positions.  */
+  POSITIONS    = 1 << 17,
+
+  /* Handle duplicate hash values for keywords.  */
+  DUP          = 1 << 18,
+
+  /* Don't include keyword length in hash computations.  */
+  NOLENGTH     = 1 << 19,
+
+  /* Randomly initialize the associated values table.  */
+  RANDOM       = 1 << 20,
+
+  /* --- Informative output --- */
+
+  /* Enable debugging (prints diagnostics to stderr).  */
+  DEBUG        = 1 << 21
 };
 
-/* Define some useful constants (these don't really belong here, but I'm
-   not sure where else to put them!).  These should be consts, but g++
-   doesn't seem to do the right thing with them at the moment... ;-( */
-
-enum
-{
-  MAX_KEY_POS = 128 - 1,    /* Max size of each word's key set. */
-  WORD_START = 1,           /* Signals the start of a word. */
-  WORD_END = 0,             /* Signals the end of a word. */
-  EOS = MAX_KEY_POS         /* Signals end of the key list. */
-};
-
-/* Class manager for gperf program Options. */
+/* Class manager for gperf program Options.  */
 
 class Options
 {
 public:
-                      Options (void);
-                     ~Options (void);
-  int                 operator[] (Option_Type option);
-  void                operator() (int argc, char *argv[]);
-  void                operator= (enum Option_Type);
-  void                operator!= (enum Option_Type);
-  static void         print_options (void);
-  static void         set_asso_max (int r);
-  static int          get_asso_max (void);
-  static void         reset (void);
-  static int          get (void);
-  static int          get_iterations (void);
-  static int          get_max_keysig_size (void);
-  static void         set_keysig_size (int);
-  static int          get_jump (void);
-  static int          initial_value (void);
-  static int          get_total_switches (void);
-  static const char  *get_function_name (void);
-  static const char  *get_key_name (void);
-  static const char  *get_initializer_suffix (void);
-  static const char  *get_class_name (void);
-  static const char  *get_hash_name (void);
-  static const char  *get_wordlist_name (void);
-  static const char  *get_delimiter (void);
+  /* Constructor.  */
+                        Options ();
+
+  /* Destructor.  */
+                        ~Options ();
+
+  /* Parses the options given in the command-line arguments.  */
+  void                  parse_options (int argc, char *argv[]);
+
+  /* Prints the given options.  */
+  void                  print_options () const;
+
+  /* Accessors.  */
+
+  /* Tests a given boolean option.  Returns true if set, false otherwise.  */
+  bool                  operator[] (Option_Type option) const;
+  /* Sets a given boolean option.  */
+  void                  set (Option_Type option);
+
+  /* Returns the input file name.  */
+  const char *          get_input_file_name () const;
+
+  /* Returns the output file name.  */
+  const char *          get_output_file_name () const;
+
+  /* Sets the output language, if not already set.  */
+  void                  set_language (const char *language);
+
+  /* Returns the jump value.  */
+  int                   get_jump () const;
+
+  /* Returns the initial associated character value.  */
+  int                   get_initial_asso_value () const;
+
+  /* Returns the number of iterations for finding good asso_values.  */
+  int                   get_asso_iterations () const;
+
+  /* Returns the total number of switch statements to generate.  */
+  int                   get_total_switches () const;
+  /* Sets the total number of switch statements, if not already set.  */
+  void                  set_total_switches (int total_switches);
+
+  /* Returns the factor by which to multiply the generated table's size.  */
+  float                 get_size_multiple () const;
+
+  /* Returns the generated function name.  */
+  const char *          get_function_name () const;
+  /* Sets the generated function name, if not already set.  */
+  void                  set_function_name (const char *name);
+
+  /* Returns the keyword key name.  */
+  const char *          get_slot_name () const;
+  /* Sets the keyword key name, if not already set.  */
+  void                  set_slot_name (const char *name);
+
+  /* Returns the struct initializer suffix.  */
+  const char *          get_initializer_suffix () const;
+  /* Sets the struct initializer suffix, if not already set.  */
+  void                  set_initializer_suffix (const char *initializers);
+
+  /* Returns the generated class name.  */
+  const char *          get_class_name () const;
+  /* Sets the generated class name, if not already set.  */
+  void                  set_class_name (const char *name);
+
+  /* Returns the hash function name.  */
+  const char *          get_hash_name () const;
+  /* Sets the hash function name, if not already set.  */
+  void                  set_hash_name (const char *name);
+
+  /* Returns the hash table array name.  */
+  const char *          get_wordlist_name () const;
+  /* Sets the hash table array name, if not already set.  */
+  void                  set_wordlist_name (const char *name);
+
+  /* Returns the length table array name.  */
+  const char *          get_lengthtable_name () const;
+  /* Sets the length table array name, if not already set.  */
+  void                  set_lengthtable_name (const char *name);
+
+  /* Returns the string pool name.  */
+  const char *          get_stringpool_name () const;
+  /* Sets the string pool name, if not already set.  */
+  void                  set_stringpool_name (const char *name);
+
+  /* Returns the string used to delimit keywords from other attributes.  */
+  const char *          get_delimiters () const;
+  /* Sets the delimiters string, if not already set.  */
+  void                  set_delimiters (const char *delimiters);
+
+  /* Returns key positions.  */
+  const Positions&      get_key_positions () const;
 
 private:
-  static int          option_word;                        /* Holds the user-specified Options. */
-  static int          total_switches;                     /* Number of switch statements to generate. */
-  static int          total_keysig_size;                  /* Total number of distinct key_positions. */
-  static int          size;                               /* Range of the hash table. */
-  static int          key_pos;                            /* Tracks current key position for Iterator. */
-  static int          jump;                               /* Jump length when trying alternative values. */
-  static int          initial_asso_value;                 /* Initial value for asso_values table. */
-  static int          argument_count;                     /* Records count of command-line arguments. */
-  static int          iterations;                         /* Amount to iterate when a collision occurs. */
-  static char       **argument_vector;                    /* Stores a pointer to command-line vector. */
-  static const char  *function_name;                      /* Names used for generated lookup function. */
-  static const char  *key_name;                           /* Name used for keyword key. */
-  static const char  *initializer_suffix;                 /* Suffix for empty struct initializers. */
-  static const char  *class_name;                         /* Name used for generated C++ class. */
-  static const char  *hash_name;                          /* Name used for generated hash function. */
-  static const char  *wordlist_name;                      /* Name used for hash table array. */
-  static const char  *delimiters;                         /* Separates keywords from other attributes. */
-  static char         key_positions[MAX_KEY_POS];         /* Contains user-specified key choices. */
-  static int          key_sort (char *base, int len);     /* Sorts key positions in REVERSE order. */
-  static void         short_usage (FILE * strm);          /* Prints proper program usage. */
-  static void         long_usage (FILE * strm);           /* Prints proper program usage. */
+  /* Prints program usage to given stream.  */
+  static void           short_usage (FILE * stream);
+
+  /* Prints program usage to given stream.  */
+  static void           long_usage (FILE * stream);
+
+  /* Records count of command-line arguments.  */
+  int                   _argument_count;
+
+  /* Stores a pointer to command-line argument vector.  */
+  char **               _argument_vector;
+
+  /* Holds the boolean options.  */
+  int                   _option_word;
+
+  /* Name of input file.  */
+  char *                _input_file_name;
+
+  /* Name of output file.  */
+  char *                _output_file_name;
+
+  /* The output language.  */
+  const char *          _language;
+
+  /* Jump length when trying alternative values.  */
+  int                   _jump;
+
+  /* Initial value for asso_values table.  */
+  int                   _initial_asso_value;
+
+  /* Number of attempts at finding good asso_values.  */
+  int                   _asso_iterations;
+
+  /* Number of switch statements to generate.  */
+  int                   _total_switches;
+
+  /* Factor by which to multiply the generated table's size.  */
+  float                 _size_multiple;
+
+  /* Names used for generated lookup function.  */
+  const char *          _function_name;
+
+  /* Name used for keyword key.  */
+  const char *          _slot_name;
+
+  /* Suffix for empty struct initializers.  */
+  const char *          _initializer_suffix;
+
+  /* Name used for generated C++ class.  */
+  const char *          _class_name;
+
+  /* Name used for generated hash function.  */
+  const char *          _hash_name;
+
+  /* Name used for hash table array.  */
+  const char *          _wordlist_name;
+
+  /* Name used for length table array.  */
+  const char *          _lengthtable_name;
+
+  /* Name used for the string pool.  */
+  const char *          _stringpool_name;
+
+  /* Separates keywords from other attributes.  */
+  const char *          _delimiters;
+
+  /* Contains user-specified key choices.  */
+  Positions             _key_positions;
 };
 
-/* Global option coordinator for the entire program. */
+/* Global option coordinator for the entire program.  */
 extern Options option;
 
-/* Set to 1 if your want to stack-allocate some large arrays.
-   This requires compiler support for variable-size arrays on the stack
-   (not ANSI). */
-#ifndef LARGE_STACK_ARRAYS
-#if defined(__GNUG__) && !defined(__STRICT_ANSI__)
-#define LARGE_STACK_ARRAYS 1
-#else
-#define LARGE_STACK_ARRAYS 0
-#endif
-#endif
-
-/* Set to 1 if the stack is large enough for holding a text line. */
-#ifndef LARGE_STACK
-#define LARGE_STACK 1
-#endif
-
 #ifdef __OPTIMIZE__
 
-#include "trace.h"
 #define INLINE inline
 #include "options.icc"
 #undef INLINE
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/src/options.icc
--- a/head/contrib/gperf/src/options.icc	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/contrib/gperf/src/options.icc	Tue Dec 06 20:26:16 2011 +0200
@@ -1,183 +1,157 @@
 /* Inline Functions for options.{h,cc}.
 
-   Copyright (C) 1989-1998, 2000 Free Software Foundation, Inc.
-   written by Douglas C. Schmidt (schmidt at ics.uci.edu)
+   Copyright (C) 1989-1998, 2000, 2002-2004 Free Software Foundation, Inc.
+   Written by Douglas C. Schmidt <schmidt at ics.uci.edu>
+   and Bruno Haible <bruno at clisp.org>.
 
-This file is part of GNU GPERF.
+   This file is part of GNU GPERF.
 
-GNU GPERF 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 1, or (at your option)
-any later version.
+   GNU GPERF 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 GPERF 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.
+   GNU GPERF 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 GPERF; see the file COPYING.  If not, write to the Free
-Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111, USA.  */
+   You should have received a copy of the GNU General Public License
+   along with this program; see the file COPYING.
+   If not, write to the Free Software Foundation, Inc.,
+   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
 
-// This needs:
-//#include "trace.h"
+/* ----------------------------- Class Options ----------------------------- */
 
-/* TRUE if option enable, else FALSE. */
-INLINE int
-Options::operator[] (Option_Type option)
+/* Tests a given boolean option.  Returns true if set, false otherwise.  */
+INLINE bool
+Options::operator[] (Option_Type option) const
 {
-  T (Trace t ("Options::operator[]");)
-  return option_word & option;
+  return _option_word & option;
 }
 
-/* Enables option OPT. */
+/* Sets a given boolean option.  */
 INLINE void
-Options::operator = (enum Option_Type opt)
+Options::set (Option_Type option)
 {
-  T (Trace t ("Options::operator=");)
-  option_word |= opt;
+  _option_word |= option;
 }
 
-/* Disables option OPT. */
-INLINE void
-Options::operator != (enum Option_Type opt)
+/* Returns the input file name.  */
+INLINE const char *
+Options::get_input_file_name () const
 {
-  T (Trace t ("Options::operator!=");)
-  option_word &= ~opt;
+  return _input_file_name;
 }
 
-/* Initializes the key Iterator. */
-INLINE void
-Options::reset (void)
+/* Returns the output file name.  */
+INLINE const char *
+Options::get_output_file_name () const
 {
-  T (Trace t ("Options::reset");)
-  key_pos = 0;
+  return _output_file_name;
 }
 
-/* Returns current key_position and advance index. */
+/* Returns the jump value.  */
 INLINE int
-Options::get (void)
+Options::get_jump () const
 {
-  T (Trace t ("Options::get");)
-  return key_positions[key_pos++];
+  return _jump;
 }
 
-/* Sets the size of the table size. */
-INLINE void
-Options::set_asso_max (int r)
+/* Returns the initial associated character value.  */
+INLINE int
+Options::get_initial_asso_value () const
 {
-  T (Trace t ("Options::set_asso_max");)
-  size = r;
+  return _initial_asso_value;
 }
 
-/* Returns the size of the table size. */
+/* Returns the number of iterations for finding finding good asso_values.  */
 INLINE int
-Options::get_asso_max (void)
+Options::get_asso_iterations () const
 {
-  T (Trace t ("Options::get_asso_max");)
-  return size;
+  return _asso_iterations;
 }
 
-/* Returns total distinct key positions. */
+/* Returns the total number of switch statements to generate.  */
 INLINE int
-Options::get_max_keysig_size (void)
+Options::get_total_switches () const
 {
-  T (Trace t ("Options::get_max_keysig_size");)
-  return total_keysig_size;
+  return _total_switches;
 }
 
-/* Sets total distinct key positions. */
-INLINE void
-Options::set_keysig_size (int size)
+/* Returns the factor by which to multiply the generated table's size.  */
+INLINE float
+Options::get_size_multiple () const
 {
-  T (Trace t ("Options::set_keysig_size");)
-  total_keysig_size = size;
+  return _size_multiple;
 }
 
-/* Returns the jump value. */
-INLINE int
-Options::get_jump (void)
+/* Returns the generated function name.  */
+INLINE const char *
+Options::get_function_name () const
 {
-  T (Trace t ("Options::get_jump");)
-  return jump;
+  return _function_name;
 }
 
-/* Returns the generated function name. */
+/* Returns the keyword key name.  */
 INLINE const char *
-Options::get_function_name (void)
+Options::get_slot_name () const
 {
-  T (Trace t ("Options::get_function_name");)
-  return function_name;
+  return _slot_name;
 }
 
-/* Returns the keyword key name. */
+/* Returns the struct initializer suffix.  */
 INLINE const char *
-Options::get_key_name (void)
+Options::get_initializer_suffix () const
 {
-  T (Trace t ("Options::get_key_name");)
-  return key_name;
+  return _initializer_suffix;
 }
 
-/* Returns the struct initializer suffix. */
+/* Returns the generated class name.  */
 INLINE const char *
-Options::get_initializer_suffix (void)
+Options::get_class_name () const
 {
-  T (Trace t ("Options::get_initializer_suffix");)
-  return initializer_suffix;
+  return _class_name;
 }
 
-/* Returns the hash function name. */
+/* Returns the hash function name.  */
 INLINE const char *
-Options::get_hash_name (void)
+Options::get_hash_name () const
 {
-  T (Trace t ("Options::get_hash_name");)
-  return hash_name;
+  return _hash_name;
 }
 
-/* Returns the hash table array name. */
+/* Returns the hash table array name.  */
 INLINE const char *
-Options::get_wordlist_name (void)
+Options::get_wordlist_name () const
 {
-  T (Trace t ("Options::get_wordlist_name");)
-  return wordlist_name;
+  return _wordlist_name;
 }
 
-/* Returns the generated class name. */
+/* Returns the length table array name.  */
 INLINE const char *
-Options::get_class_name (void)
+Options::get_lengthtable_name () const
 {
-  T (Trace t ("Options::get_class_name");)
-  return class_name;
+  return _lengthtable_name;
 }
 
-/* Returns the initial associated character value. */
-INLINE int
-Options::initial_value (void)
+/* Returns the string pool name.  */
+INLINE const char *
+Options::get_stringpool_name () const
 {
-  T (Trace t ("Options::initial_value");)
-  return initial_asso_value;
+  return _stringpool_name;
 }
 
-/* Returns the iterations value. */
-INLINE int
-Options::get_iterations (void)
+/* Returns the string used to delimit keywords from other attributes.  */
+INLINE const char *
+Options::get_delimiters () const
 {
-  T (Trace t ("Options::get_iterations");)
-  return iterations;
+  return _delimiters;
 }
 
-/* Returns the string used to delimit keywords from other attributes. */
-INLINE const char *
-Options::get_delimiter ()
+/* Returns key positions.  */
+INLINE const Positions&
+Options::get_key_positions () const
 {
-  T (Trace t ("Options::get_delimiter");)
-  return delimiters;
+  return _key_positions;
 }
-
-/* Gets the total number of switch statements to generate. */
-INLINE int
-Options::get_total_switches ()
-{
-  T (Trace t ("Options::get_total_switches");)
-  return total_switches;
-}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/src/output.cc
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/contrib/gperf/src/output.cc	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,2100 @@
+/* Output routines.
+   Copyright (C) 1989-1998, 2000, 2002-2004, 2006-2007 Free Software Foundation, Inc.
+   Written by Douglas C. Schmidt <schmidt at ics.uci.edu>
+   and Bruno Haible <bruno at clisp.org>.
+
+   This file is part of GNU GPERF.
+
+   GNU GPERF 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 GPERF 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; see the file COPYING.
+   If not, write to the Free Software Foundation, Inc.,
+   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
+
+/* Specification. */
+#include "output.h"
+
+#include <stdio.h>
+#include <string.h> /* declares strncpy(), strchr() */
+#include <ctype.h>  /* declares isprint() */
+#include <assert.h> /* defines assert() */
+#include <limits.h> /* defines SCHAR_MAX etc. */
+#include "options.h"
+#include "version.h"
+
+/* The "const " qualifier.  */
+static const char *const_always;
+
+/* The "const " qualifier, for read-only arrays.  */
+static const char *const_readonly_array;
+
+/* The "const " qualifier, for the array type.  */
+static const char *const_for_struct;
+
+/* Returns the smallest unsigned C type capable of holding integers
+   up to N.  */
+
+static const char *
+smallest_integral_type (int n)
+{
+  if (n <= UCHAR_MAX) return "unsigned char";
+  if (n <= USHRT_MAX) return "unsigned short";
+  return "unsigned int";
+}
+
+/* Returns the smallest signed C type capable of holding integers
+   from MIN to MAX.  */
+
+static const char *
+smallest_integral_type (int min, int max)
+{
+  if (option[ANSIC] | option[CPLUSPLUS])
+    if (min >= SCHAR_MIN && max <= SCHAR_MAX) return "signed char";
+  if (min >= SHRT_MIN && max <= SHRT_MAX) return "short";
+  return "int";
+}
+
+/* ------------------------------------------------------------------------- */
+
+/* Constructor.
+   Note about the keyword list starting at head:
+   - The list is ordered by increasing _hash_value.  This has been achieved
+     by Search::sort().
+   - Duplicates, i.e. keywords with the same _selchars set, are chained
+     through the _duplicate_link pointer.  Only one representative per
+     duplicate equivalence class remains on the linear keyword list.
+   - Accidental duplicates, i.e. keywords for which the _asso_values[] search
+     couldn't achieve different hash values, cannot occur on the linear
+     keyword list.  Search::optimize would catch this mistake.
+ */
+Output::Output (KeywordExt_List *head, const char *struct_decl,
+                unsigned int struct_decl_lineno, const char *return_type,
+                const char *struct_tag, const char *verbatim_declarations,
+                const char *verbatim_declarations_end,
+                unsigned int verbatim_declarations_lineno,
+                const char *verbatim_code, const char *verbatim_code_end,
+                unsigned int verbatim_code_lineno, bool charset_dependent,
+                int total_keys, int max_key_len, int min_key_len,
+                const Positions& positions, const unsigned int *alpha_inc,
+                int total_duplicates, unsigned int alpha_size,
+                const int *asso_values)
+  : _head (head), _struct_decl (struct_decl),
+    _struct_decl_lineno (struct_decl_lineno), _return_type (return_type),
+    _struct_tag (struct_tag),
+    _verbatim_declarations (verbatim_declarations),
+    _verbatim_declarations_end (verbatim_declarations_end),
+    _verbatim_declarations_lineno (verbatim_declarations_lineno),
+    _verbatim_code (verbatim_code),
+    _verbatim_code_end (verbatim_code_end),
+    _verbatim_code_lineno (verbatim_code_lineno),
+    _charset_dependent (charset_dependent),
+    _total_keys (total_keys),
+    _max_key_len (max_key_len), _min_key_len (min_key_len),
+    _key_positions (positions), _alpha_inc (alpha_inc),
+    _total_duplicates (total_duplicates), _alpha_size (alpha_size),
+    _asso_values (asso_values)
+{
+}
+
+/* ------------------------------------------------------------------------- */
+
+/* Computes the minimum and maximum hash values, and stores them
+   in _min_hash_value and _max_hash_value.  */
+
+void
+Output::compute_min_max ()
+{
+  /* Since the list is already sorted by hash value all we need to do is
+     to look at the first and the last element of the list.  */
+
+  _min_hash_value = _head->first()->_hash_value;
+
+  KeywordExt_List *temp;
+  for (temp = _head; temp->rest(); temp = temp->rest())
+    ;
+  _max_hash_value = temp->first()->_hash_value;
+}
+
+/* ------------------------------------------------------------------------- */
+
+/* Returns the number of different hash values.  */
+
+int
+Output::num_hash_values () const
+{
+  /* Since the list is already sorted by hash value and doesn't contain
+     duplicates, we can simply count the number of keywords on the list.  */
+  int count = 0;
+  for (KeywordExt_List *temp = _head; temp; temp = temp->rest())
+    count++;
+  return count;
+}
+
+/* -------------------- Output_Constants and subclasses -------------------- */
+
+/* This class outputs an enumeration defining some constants.  */
+
+struct Output_Constants
+{
+  virtual void          output_start () = 0;
+  virtual void          output_item (const char *name, int value) = 0;
+  virtual void          output_end () = 0;
+                        Output_Constants () {}
+  virtual               ~Output_Constants () {}
+};
+
+/* This class outputs an enumeration in #define syntax.  */
+
+struct Output_Defines : public Output_Constants
+{
+  virtual void          output_start ();
+  virtual void          output_item (const char *name, int value);
+  virtual void          output_end ();
+                        Output_Defines () {}
+  virtual               ~Output_Defines () {}
+};
+
+void Output_Defines::output_start ()
+{
+  printf ("\n");
+}
+
+void Output_Defines::output_item (const char *name, int value)
+{
+  printf ("#define %s %d\n", name, value);
+}
+
+void Output_Defines::output_end ()
+{
+}
+
+/* This class outputs an enumeration using 'enum'.  */
+
+struct Output_Enum : public Output_Constants
+{
+  virtual void          output_start ();
+  virtual void          output_item (const char *name, int value);
+  virtual void          output_end ();
+                        Output_Enum (const char *indent)
+                          : _indentation (indent) {}
+  virtual               ~Output_Enum () {}
+private:
+  const char *_indentation;
+  bool _pending_comma;
+};
+
+void Output_Enum::output_start ()
+{
+  printf ("%senum\n"
+          "%s  {\n",
+          _indentation, _indentation);
+  _pending_comma = false;
+}
+
+void Output_Enum::output_item (const char *name, int value)
+{
+  if (_pending_comma)
+    printf (",\n");
+  printf ("%s    %s = %d", _indentation, name, value);
+  _pending_comma = true;
+}
+
+void Output_Enum::output_end ()
+{
+  if (_pending_comma)
+    printf ("\n");
+  printf ("%s  };\n\n", _indentation);
+}
+
+/* Outputs the maximum and minimum hash values etc.  */
+
+void
+Output::output_constants (struct Output_Constants& style) const
+{
+  style.output_start ();
+  style.output_item ("TOTAL_KEYWORDS", _total_keys);
+  style.output_item ("MIN_WORD_LENGTH", _min_key_len);
+  style.output_item ("MAX_WORD_LENGTH", _max_key_len);
+  style.output_item ("MIN_HASH_VALUE", _min_hash_value);
+  style.output_item ("MAX_HASH_VALUE", _max_hash_value);
+  style.output_end ();
+}
+
+/* ------------------------------------------------------------------------- */
+
+/* We use a downcase table because when called repeatedly, the code
+       gperf_downcase[c]
+   is faster than
+       if (c >= 'A' && c <= 'Z')
+         c += 'a' - 'A';
+ */
+#define USE_DOWNCASE_TABLE 1
+
+#if USE_DOWNCASE_TABLE
+
+/* Output gperf's ASCII-downcase table.  */
+
+static void
+output_upperlower_table ()
+{
+  unsigned int c;
+
+  printf ("#ifndef GPERF_DOWNCASE\n"
+          "#define GPERF_DOWNCASE 1\n"
+          "static unsigned char gperf_downcase[256] =\n"
+          "  {");
+  for (c = 0; c < 256; c++)
+    {
+      if ((c % 15) == 0)
+        printf ("\n   ");
+      printf (" %3d", c >= 'A' && c <= 'Z' ? c + 'a' - 'A' : c);
+      if (c < 255)
+        printf (",");
+    }
+  printf ("\n"
+          "  };\n"
+          "#endif\n\n");
+}
+
+#endif
+
+/* Output gperf's ASCII-case insensitive strcmp replacement.  */
+
+static void
+output_upperlower_strcmp ()
+{
+  printf ("#ifndef GPERF_CASE_STRCMP\n"
+          "#define GPERF_CASE_STRCMP 1\n"
+          "static int\n"
+          "gperf_case_strcmp ");
+  printf (option[KRC] ?
+               "(s1, s2)\n"
+          "     register char *s1;\n"
+          "     register char *s2;\n" :
+          option[C] ?
+               "(s1, s2)\n"
+          "     register const char *s1;\n"
+          "     register const char *s2;\n" :
+          option[ANSIC] | option[CPLUSPLUS] ?
+               "(register const char *s1, register const char *s2)\n" :
+          "");
+  #if USE_DOWNCASE_TABLE
+  printf ("{\n"
+          "  for (;;)\n"
+          "    {\n"
+          "      unsigned char c1 = gperf_downcase[(unsigned char)*s1++];\n"
+          "      unsigned char c2 = gperf_downcase[(unsigned char)*s2++];\n"
+          "      if (c1 != 0 && c1 == c2)\n"
+          "        continue;\n"
+          "      return (int)c1 - (int)c2;\n"
+          "    }\n"
+          "}\n");
+  #else
+  printf ("{\n"
+          "  for (;;)\n"
+          "    {\n"
+          "      unsigned char c1 = *s1++;\n"
+          "      unsigned char c2 = *s2++;\n"
+          "      if (c1 >= 'A' && c1 <= 'Z')\n"
+          "        c1 += 'a' - 'A';\n"
+          "      if (c2 >= 'A' && c2 <= 'Z')\n"
+          "        c2 += 'a' - 'A';\n"
+          "      if (c1 != 0 && c1 == c2)\n"
+          "        continue;\n"
+          "      return (int)c1 - (int)c2;\n"
+          "    }\n"
+          "}\n");
+  #endif
+  printf ("#endif\n\n");
+}
+
+/* Output gperf's ASCII-case insensitive strncmp replacement.  */
+
+static void
+output_upperlower_strncmp ()
+{
+  printf ("#ifndef GPERF_CASE_STRNCMP\n"
+          "#define GPERF_CASE_STRNCMP 1\n"
+          "static int\n"
+          "gperf_case_strncmp ");
+  printf (option[KRC] ?
+               "(s1, s2, n)\n"
+          "     register char *s1;\n"
+          "     register char *s2;\n"
+          "     register unsigned int n;\n" :
+          option[C] ?
+               "(s1, s2, n)\n"
+          "     register const char *s1;\n"
+          "     register const char *s2;\n"
+          "     register unsigned int n;\n" :
+          option[ANSIC] | option[CPLUSPLUS] ?
+               "(register const char *s1, register const char *s2, register unsigned int n)\n" :
+          "");
+  #if USE_DOWNCASE_TABLE
+  printf ("{\n"
+          "  for (; n > 0;)\n"
+          "    {\n"
+          "      unsigned char c1 = gperf_downcase[(unsigned char)*s1++];\n"
+          "      unsigned char c2 = gperf_downcase[(unsigned char)*s2++];\n"
+          "      if (c1 != 0 && c1 == c2)\n"
+          "        {\n"
+          "          n--;\n"
+          "          continue;\n"
+          "        }\n"
+          "      return (int)c1 - (int)c2;\n"
+          "    }\n"
+          "  return 0;\n"
+          "}\n");
+  #else
+  printf ("{\n"
+          "  for (; n > 0;)\n"
+          "    {\n"
+          "      unsigned char c1 = *s1++;\n"
+          "      unsigned char c2 = *s2++;\n"
+          "      if (c1 >= 'A' && c1 <= 'Z')\n"
+          "        c1 += 'a' - 'A';\n"
+          "      if (c2 >= 'A' && c2 <= 'Z')\n"
+          "        c2 += 'a' - 'A';\n"
+          "      if (c1 != 0 && c1 == c2)\n"
+          "        {\n"
+          "          n--;\n"
+          "          continue;\n"
+          "        }\n"
+          "      return (int)c1 - (int)c2;\n"
+          "    }\n"
+          "  return 0;\n"
+          "}\n");
+  #endif
+  printf ("#endif\n\n");
+}
+
+/* Output gperf's ASCII-case insensitive memcmp replacement.  */
+
+static void
+output_upperlower_memcmp ()
+{
+  printf ("#ifndef GPERF_CASE_MEMCMP\n"
+          "#define GPERF_CASE_MEMCMP 1\n"
+          "static int\n"
+          "gperf_case_memcmp ");
+  printf (option[KRC] ?
+               "(s1, s2, n)\n"
+          "     register char *s1;\n"
+          "     register char *s2;\n"
+          "     register unsigned int n;\n" :
+          option[C] ?
+               "(s1, s2, n)\n"
+          "     register const char *s1;\n"
+          "     register const char *s2;\n"
+          "     register unsigned int n;\n" :
+          option[ANSIC] | option[CPLUSPLUS] ?
+               "(register const char *s1, register const char *s2, register unsigned int n)\n" :
+          "");
+  #if USE_DOWNCASE_TABLE
+  printf ("{\n"
+          "  for (; n > 0;)\n"
+          "    {\n"
+          "      unsigned char c1 = gperf_downcase[(unsigned char)*s1++];\n"
+          "      unsigned char c2 = gperf_downcase[(unsigned char)*s2++];\n"
+          "      if (c1 == c2)\n"
+          "        {\n"
+          "          n--;\n"
+          "          continue;\n"
+          "        }\n"
+          "      return (int)c1 - (int)c2;\n"
+          "    }\n"
+          "  return 0;\n"
+          "}\n");
+  #else
+  printf ("{\n"
+          "  for (; n > 0;)\n"
+          "    {\n"
+          "      unsigned char c1 = *s1++;\n"
+          "      unsigned char c2 = *s2++;\n"
+          "      if (c1 >= 'A' && c1 <= 'Z')\n"
+          "        c1 += 'a' - 'A';\n"
+          "      if (c2 >= 'A' && c2 <= 'Z')\n"
+          "        c2 += 'a' - 'A';\n"
+          "      if (c1 == c2)\n"
+          "        {\n"
+          "          n--;\n"
+          "          continue;\n"
+          "        }\n"
+          "      return (int)c1 - (int)c2;\n"
+          "    }\n"
+          "  return 0;\n"
+          "}\n");
+  #endif
+  printf ("#endif\n\n");
+}
+
+/* ------------------------------------------------------------------------- */
+
+/* Outputs a keyword, as a string: enclosed in double quotes, escaping
+   backslashes, double quote and unprintable characters.  */
+
+static void
+output_string (const char *key, int len)
+{
+  putchar ('"');
+  for (; len > 0; len--)
+    {
+      unsigned char c = static_cast<unsigned char>(*key++);
+      if (isprint (c))
+        {
+          if (c == '"' || c == '\\')
+            putchar ('\\');
+          putchar (c);
+        }
+      else
+        {
+          /* Use octal escapes, not hexadecimal escapes, because some old
+             C compilers didn't understand hexadecimal escapes, and because
+             hexadecimal escapes are not limited to 2 digits, thus needing
+             special care if the following character happens to be a digit.  */
+          putchar ('\\');
+          putchar ('0' + ((c >> 6) & 7));
+          putchar ('0' + ((c >> 3) & 7));
+          putchar ('0' + (c & 7));
+        }
+    }
+  putchar ('"');
+}
+
+/* ------------------------------------------------------------------------- */
+
+/* Outputs a #line directive, referring to the given line number.  */
+
+static void
+output_line_directive (unsigned int lineno)
+{
+  const char *file_name = option.get_input_file_name ();
+  if (file_name != NULL)
+    {
+      printf ("#line %u ", lineno);
+      output_string (file_name, strlen (file_name));
+      printf ("\n");
+    }
+}
+
+/* ------------------------------------------------------------------------- */
+
+/* Outputs a type and a const specifier (i.e. "const " or "").
+   The output is terminated with a space.  */
+
+static void
+output_const_type (const char *const_string, const char *type_string)
+{
+  if (type_string[strlen(type_string)-1] == '*')
+    /* For pointer types, put the 'const' after the type.  */
+    printf ("%s %s", type_string, const_string);
+  else
+    /* For scalar or struct types, put the 'const' before the type.  */
+    printf ("%s%s ", const_string, type_string);
+}
+
+/* ----------------------- Output_Expr and subclasses ----------------------- */
+
+/* This class outputs a general expression.  */
+
+struct Output_Expr
+{
+  virtual void          output_expr () const = 0;
+                        Output_Expr () {}
+  virtual               ~Output_Expr () {}
+};
+
+/* This class outputs an expression formed by a single string.  */
+
+struct Output_Expr1 : public Output_Expr
+{
+  virtual void          output_expr () const;
+                        Output_Expr1 (const char *piece1) : _p1 (piece1) {}
+  virtual               ~Output_Expr1 () {}
+private:
+  const char *_p1;
+};
+
+void Output_Expr1::output_expr () const
+{
+  printf ("%s", _p1);
+}
+
+#if 0 /* unused */
+
+/* This class outputs an expression formed by the concatenation of two
+   strings.  */
+
+struct Output_Expr2 : public Output_Expr
+{
+  virtual void          output_expr () const;
+                        Output_Expr2 (const char *piece1, const char *piece2)
+                          : _p1 (piece1), _p2 (piece2) {}
+  virtual               ~Output_Expr2 () {}
+private:
+  const char *_p1;
+  const char *_p2;
+};
+
+void Output_Expr2::output_expr () const
+{
+  printf ("%s%s", _p1, _p2);
+}
+
+#endif
+
+/* --------------------- Output_Compare and subclasses --------------------- */
+
+/* This class outputs a comparison expression.  */
+
+struct Output_Compare
+{
+  /* Outputs the comparison expression.
+     expr1 outputs a simple expression of type 'const char *' referring to
+     the string being looked up.  expr2 outputs a simple expression of type
+     'const char *' referring to the constant string stored in the gperf
+     generated hash table.  */
+  virtual void          output_comparison (const Output_Expr& expr1,
+                                           const Output_Expr& expr2) const = 0;
+  /* Outputs the comparison expression for the first byte.
+     Returns true if the this comparison is complete.  */
+  bool                  output_firstchar_comparison (const Output_Expr& expr1,
+                                                     const Output_Expr& expr2) const;
+                        Output_Compare () {}
+  virtual               ~Output_Compare () {}
+};
+
+bool Output_Compare::output_firstchar_comparison (const Output_Expr& expr1,
+                                                  const Output_Expr& expr2) const
+{
+  /* First, we emit a comparison of the first byte of the two strings.
+     This catches most cases where the string being looked up is not in the
+     hash table but happens to have the same hash code as an element of the
+     hash table.  */
+  if (option[UPPERLOWER])
+    {
+      /* Incomplete comparison, just for speedup.  */
+      printf ("(((unsigned char)*");
+      expr1.output_expr ();
+      printf (" ^ (unsigned char)*");
+      expr2.output_expr ();
+      printf (") & ~32) == 0");
+      return false;
+    }
+  else
+    {
+      /* Complete comparison.  */
+      printf ("*");
+      expr1.output_expr ();
+      printf (" == *");
+      expr2.output_expr ();
+      return true;
+    }
+}
+
+/* This class outputs a comparison using strcmp.  */
+
+struct Output_Compare_Strcmp : public Output_Compare
+{
+  virtual void          output_comparison (const Output_Expr& expr1,
+                                           const Output_Expr& expr2) const;
+                        Output_Compare_Strcmp () {}
+  virtual               ~Output_Compare_Strcmp () {}
+};
+
+void Output_Compare_Strcmp::output_comparison (const Output_Expr& expr1,
+                                               const Output_Expr& expr2) const
+{
+  bool firstchar_done = output_firstchar_comparison (expr1, expr2);
+  printf (" && !");
+  if (option[UPPERLOWER])
+    printf ("gperf_case_");
+  printf ("strcmp (");
+  if (firstchar_done)
+    {
+      expr1.output_expr ();
+      printf (" + 1, ");
+      expr2.output_expr ();
+      printf (" + 1");
+    }
+  else
+    {
+      expr1.output_expr ();
+      printf (", ");
+      expr2.output_expr ();
+    }
+  printf (")");
+}
+
+/* This class outputs a comparison using strncmp.
+   Note that the length of expr1 will be available through the local variable
+   'len'.  */
+
+struct Output_Compare_Strncmp : public Output_Compare
+{
+  virtual void          output_comparison (const Output_Expr& expr1,
+                                           const Output_Expr& expr2) const;
+                        Output_Compare_Strncmp () {}
+  virtual               ~Output_Compare_Strncmp () {}
+};
+
+void Output_Compare_Strncmp::output_comparison (const Output_Expr& expr1,
+                                                const Output_Expr& expr2) const
+{
+  bool firstchar_done = output_firstchar_comparison (expr1, expr2);
+  printf (" && !");
+  if (option[UPPERLOWER])
+    printf ("gperf_case_");
+  printf ("strncmp (");
+  if (firstchar_done)
+    {
+      expr1.output_expr ();
+      printf (" + 1, ");
+      expr2.output_expr ();
+      printf (" + 1, len - 1");
+    }
+  else
+    {
+      expr1.output_expr ();
+      printf (", ");
+      expr2.output_expr ();
+      printf (", len");
+    }
+  printf (") && ");
+  expr2.output_expr ();
+  printf ("[len] == '\\0'");
+}
+
+/* This class outputs a comparison using memcmp.
+   Note that the length of expr1 (available through the local variable 'len')
+   must be verified to be equal to the length of expr2 prior to this
+   comparison.  */
+
+struct Output_Compare_Memcmp : public Output_Compare
+{
+  virtual void          output_comparison (const Output_Expr& expr1,
+                                           const Output_Expr& expr2) const;
+                        Output_Compare_Memcmp () {}
+  virtual               ~Output_Compare_Memcmp () {}
+};
+
+void Output_Compare_Memcmp::output_comparison (const Output_Expr& expr1,
+                                               const Output_Expr& expr2) const
+{
+  bool firstchar_done = output_firstchar_comparison (expr1, expr2);
+  printf (" && !");
+  if (option[UPPERLOWER])
+    printf ("gperf_case_");
+  printf ("memcmp (");
+  if (firstchar_done)
+    {
+      expr1.output_expr ();
+      printf (" + 1, ");
+      expr2.output_expr ();
+      printf (" + 1, len - 1");
+    }
+  else
+    {
+      expr1.output_expr ();
+      printf (", ");
+      expr2.output_expr ();
+      printf (", len");
+    }
+  printf (")");
+}
+
+/* ------------------------------------------------------------------------- */
+
+/* Generates a C expression for an asso_values[] reference.  */
+
+void
+Output::output_asso_values_ref (int pos) const
+{
+  printf ("asso_values[");
+  /* Always cast to unsigned char.  This is necessary when the alpha_inc
+     is nonzero, and also avoids a gcc warning "subscript has type 'char'".  */
+  printf ("(unsigned char)");
+  if (pos == Positions::LASTCHAR)
+    printf ("str[len - 1]");
+  else
+    {
+      printf ("str[%d]", pos);
+      if (_alpha_inc[pos])
+        printf ("+%u", _alpha_inc[pos]);
+    }
+  printf ("]");
+}
+
+/* Generates C code for the hash function that returns the
+   proper encoding for each keyword.
+   The hash function has the signature
+     unsigned int <hash> (const char *str, unsigned int len).  */
+
+void
+Output::output_hash_function () const
+{
+  /* Output the function's head.  */
+  if (option[CPLUSPLUS])
+    printf ("inline ");
+  else if (option[KRC] | option[C] | option[ANSIC])
+    printf ("#ifdef __GNUC__\n"
+            "__inline\n"
+            "#else\n"
+            "#ifdef __cplusplus\n"
+            "inline\n"
+            "#endif\n"
+            "#endif\n");
+
+  if (/* The function does not use the 'str' argument?  */
+      _key_positions.get_size() == 0
+      || /* The function uses 'str', but not the 'len' argument?  */
+         (option[NOLENGTH]
+          && _key_positions[0] < _min_key_len
+          && _key_positions[_key_positions.get_size() - 1] != Positions::LASTCHAR))
+    /* Pacify lint.  */
+    printf ("/*ARGSUSED*/\n");
+
+  if (option[KRC] | option[C] | option[ANSIC])
+    printf ("static ");
+  printf ("unsigned int\n");
+  if (option[CPLUSPLUS])
+    printf ("%s::", option.get_class_name ());
+  printf ("%s ", option.get_hash_name ());
+  printf (option[KRC] ?
+                 "(str, len)\n"
+            "     register char *str;\n"
+            "     register unsigned int len;\n" :
+          option[C] ?
+                 "(str, len)\n"
+            "     register const char *str;\n"
+            "     register unsigned int len;\n" :
+          option[ANSIC] | option[CPLUSPLUS] ?
+                 "(register const char *str, register unsigned int len)\n" :
+          "");
+
+  /* Note that when the hash function is called, it has already been verified
+     that  min_key_len <= len <= max_key_len.  */
+
+  /* Output the function's body.  */
+  printf ("{\n");
+
+  /* First the asso_values array.  */
+  if (_key_positions.get_size() > 0)
+    {
+      printf ("  static %s%s asso_values[] =\n"
+              "    {",
+              const_readonly_array,
+              smallest_integral_type (_max_hash_value + 1));
+
+      const int columns = 10;
+
+      /* Calculate maximum number of digits required for MAX_HASH_VALUE.  */
+      int field_width = 2;
+      for (int trunc = _max_hash_value; (trunc /= 10) > 0;)
+        field_width++;
+
+      for (unsigned int count = 0; count < _alpha_size; count++)
+        {
+          if (count > 0)
+            printf (",");
+          if ((count % columns) == 0)
+            printf ("\n     ");
+          printf ("%*d", field_width, _asso_values[count]);
+        }
+
+      printf ("\n"
+              "    };\n");
+    }
+
+  if (_key_positions.get_size() == 0)
+    {
+      /* Trivial case: No key positions at all.  */
+      printf ("  return %s;\n",
+              option[NOLENGTH] ? "0" : "len");
+    }
+  else
+    {
+      /* Iterate through the key positions.  Remember that Positions::sort()
+         has sorted them in decreasing order, with Positions::LASTCHAR coming
+         last.  */
+      PositionIterator iter = _key_positions.iterator(_max_key_len);
+      int key_pos;
+
+      /* Get the highest key position.  */
+      key_pos = iter.next ();
+
+      if (key_pos == Positions::LASTCHAR || key_pos < _min_key_len)
+        {
+          /* We can perform additional optimizations here:
+             Write it out as a single expression. Note that the values
+             are added as 'int's even though the asso_values array may
+             contain 'unsigned char's or 'unsigned short's.  */
+
+          printf ("  return %s",
+                  option[NOLENGTH] ? "" : "len + ");
+
+          if (_key_positions.get_size() == 2
+              && _key_positions[0] == 0
+              && _key_positions[1] == Positions::LASTCHAR)
+            /* Optimize special case of "-k 1,$".  */
+            {
+              output_asso_values_ref (Positions::LASTCHAR);
+              printf (" + ");
+              output_asso_values_ref (0);
+            }
+          else
+            {
+              for (; key_pos != Positions::LASTCHAR; )
+                {
+                  output_asso_values_ref (key_pos);
+                  if ((key_pos = iter.next ()) != PositionIterator::EOS)
+                    printf (" + ");
+                  else
+                    break;
+                }
+
+              if (key_pos == Positions::LASTCHAR)
+                output_asso_values_ref (Positions::LASTCHAR);
+            }
+
+          printf (";\n");
+        }
+      else
+        {
+          /* We've got to use the correct, but brute force, technique.  */
+          printf ("  register int hval = %s;\n\n"
+                  "  switch (%s)\n"
+                  "    {\n"
+                  "      default:\n",
+                  option[NOLENGTH] ? "0" : "len",
+                  option[NOLENGTH] ? "len" : "hval");
+
+          while (key_pos != Positions::LASTCHAR && key_pos >= _max_key_len)
+            if ((key_pos = iter.next ()) == PositionIterator::EOS)
+              break;
+
+          if (key_pos != PositionIterator::EOS && key_pos != Positions::LASTCHAR)
+            {
+              int i = key_pos;
+              do
+                {
+                  if (i > key_pos)
+                    printf ("      /*FALLTHROUGH*/\n"); /* Pacify lint.  */
+                  for ( ; i > key_pos; i--)
+                    printf ("      case %d:\n", i);
+
+                  printf ("        hval += ");
+                  output_asso_values_ref (key_pos);
+                  printf (";\n");
+
+                  key_pos = iter.next ();
+                }
+              while (key_pos != PositionIterator::EOS && key_pos != Positions::LASTCHAR);
+
+              if (i >= _min_key_len)
+                printf ("      /*FALLTHROUGH*/\n"); /* Pacify lint.  */
+              for ( ; i >= _min_key_len; i--)
+                printf ("      case %d:\n", i);
+            }
+
+          printf ("        break;\n"
+                  "    }\n"
+                  "  return hval");
+          if (key_pos == Positions::LASTCHAR)
+            {
+              printf (" + ");
+              output_asso_values_ref (Positions::LASTCHAR);
+            }
+          printf (";\n");
+        }
+    }
+  printf ("}\n\n");
+}
+
+/* ------------------------------------------------------------------------- */
+
+/* Prints out a table of keyword lengths, for use with the
+   comparison code in generated function 'in_word_set'.
+   Only called if option[LENTABLE].  */
+
+void
+Output::output_keylength_table () const
+{
+  const int columns = 14;
+  const char * const indent = option[GLOBAL] ? "" : "  ";
+
+  printf ("%sstatic %s%s %s[] =\n"
+          "%s  {",
+          indent, const_readonly_array,
+          smallest_integral_type (_max_key_len),
+          option.get_lengthtable_name (),
+          indent);
+
+  /* Generate an array of lengths, similar to output_keyword_table.  */
+  int index;
+  int column;
+  KeywordExt_List *temp;
+
+  column = 0;
+  for (temp = _head, index = 0; temp; temp = temp->rest())
+    {
+      KeywordExt *keyword = temp->first();
+
+      /* If generating a switch statement, and there is no user defined type,
+         we generate non-duplicates directly in the code.  Only duplicates go
+         into the table.  */
+      if (option[SWITCH] && !option[TYPE] && !keyword->_duplicate_link)
+        continue;
+
+      if (index < keyword->_hash_value && !option[SWITCH] && !option[DUP])
+        {
+          /* Some blank entries.  */
+          for ( ; index < keyword->_hash_value; index++)
+            {
+              if (index > 0)
+                printf (",");
+              if ((column++ % columns) == 0)
+                printf ("\n%s   ", indent);
+              printf ("%3d", 0);
+            }
+        }
+
+      if (index > 0)
+        printf (",");
+      if ((column++ % columns) == 0)
+        printf("\n%s   ", indent);
+      printf ("%3d", keyword->_allchars_length);
+      index++;
+
+      /* Deal with duplicates specially.  */
+      if (keyword->_duplicate_link) // implies option[DUP]
+        for (KeywordExt *links = keyword->_duplicate_link; links; links = links->_duplicate_link)
+          {
+            printf (",");
+            if ((column++ % columns) == 0)
+              printf("\n%s   ", indent);
+            printf ("%3d", links->_allchars_length);
+            index++;
+          }
+    }
+
+  printf ("\n%s  };\n", indent);
+  if (option[GLOBAL])
+    printf ("\n");
+}
+
+/* ------------------------------------------------------------------------- */
+
+/* Prints out the string pool, containing the strings of the keyword table.
+   Only called if option[SHAREDLIB].  */
+
+void
+Output::output_string_pool () const
+{
+  const char * const indent = option[TYPE] || option[GLOBAL] ? "" : "  ";
+  int index;
+  KeywordExt_List *temp;
+
+  printf ("%sstruct %s_t\n"
+          "%s  {\n",
+          indent, option.get_stringpool_name (), indent);
+  for (temp = _head, index = 0; temp; temp = temp->rest())
+    {
+      KeywordExt *keyword = temp->first();
+
+      /* If generating a switch statement, and there is no user defined type,
+         we generate non-duplicates directly in the code.  Only duplicates go
+         into the table.  */
+      if (option[SWITCH] && !option[TYPE] && !keyword->_duplicate_link)
+        continue;
+
+      if (!option[SWITCH] && !option[DUP])
+        index = keyword->_hash_value;
+
+      printf ("%s    char %s_str%d[sizeof(",
+              indent, option.get_stringpool_name (), index);
+      output_string (keyword->_allchars, keyword->_allchars_length);
+      printf (")];\n");
+
+      /* Deal with duplicates specially.  */
+      if (keyword->_duplicate_link) // implies option[DUP]
+        for (KeywordExt *links = keyword->_duplicate_link; links; links = links->_duplicate_link)
+          if (!(links->_allchars_length == keyword->_allchars_length
+                && memcmp (links->_allchars, keyword->_allchars,
+                           keyword->_allchars_length) == 0))
+            {
+              index++;
+              printf ("%s    char %s_str%d[sizeof(",
+                      indent, option.get_stringpool_name (), index);
+              output_string (links->_allchars, links->_allchars_length);
+              printf (")];\n");
+            }
+
+      index++;
+    }
+  printf ("%s  };\n",
+          indent);
+
+  printf ("%sstatic %sstruct %s_t %s_contents =\n"
+          "%s  {\n",
+          indent, const_readonly_array, option.get_stringpool_name (),
+          option.get_stringpool_name (), indent);
+  for (temp = _head, index = 0; temp; temp = temp->rest())
+    {
+      KeywordExt *keyword = temp->first();
+
+      /* If generating a switch statement, and there is no user defined type,
+         we generate non-duplicates directly in the code.  Only duplicates go
+         into the table.  */
+      if (option[SWITCH] && !option[TYPE] && !keyword->_duplicate_link)
+        continue;
+
+      if (index > 0)
+        printf (",\n");
+
+      if (!option[SWITCH] && !option[DUP])
+        index = keyword->_hash_value;
+
+      printf ("%s    ",
+              indent);
+      output_string (keyword->_allchars, keyword->_allchars_length);
+
+      /* Deal with duplicates specially.  */
+      if (keyword->_duplicate_link) // implies option[DUP]
+        for (KeywordExt *links = keyword->_duplicate_link; links; links = links->_duplicate_link)
+          if (!(links->_allchars_length == keyword->_allchars_length
+                && memcmp (links->_allchars, keyword->_allchars,
+                           keyword->_allchars_length) == 0))
+            {
+              index++;
+              printf (",\n");
+              printf ("%s    ",
+                      indent);
+              output_string (links->_allchars, links->_allchars_length);
+            }
+
+      index++;
+    }
+  if (index > 0)
+    printf ("\n");
+  printf ("%s  };\n",
+          indent);
+  printf ("%s#define %s ((%schar *) &%s_contents)\n",
+          indent, option.get_stringpool_name (), const_always,
+          option.get_stringpool_name ());
+  if (option[GLOBAL])
+    printf ("\n");
+}
+
+/* ------------------------------------------------------------------------- */
+
+static void
+output_keyword_entry (KeywordExt *temp, int stringpool_index, const char *indent)
+{
+  if (option[TYPE])
+    output_line_directive (temp->_lineno);
+  printf ("%s    ", indent);
+  if (option[TYPE])
+    printf ("{");
+  if (option[SHAREDLIB])
+    printf ("(int)(long)&((struct %s_t *)0)->%s_str%d",
+            option.get_stringpool_name (), option.get_stringpool_name (),
+            stringpool_index);
+  else
+    output_string (temp->_allchars, temp->_allchars_length);
+  if (option[TYPE])
+    {
+      if (strlen (temp->_rest) > 0)
+        printf (",%s", temp->_rest);
+      printf ("}");
+    }
+  if (option[DEBUG])
+    printf (" /* hash value = %d, index = %d */",
+            temp->_hash_value, temp->_final_index);
+}
+
+static void
+output_keyword_blank_entries (int count, const char *indent)
+{
+  int columns;
+  if (option[TYPE])
+    {
+      columns = 58 / (4 + (option[SHAREDLIB] ? 2 : option[NULLSTRINGS] ? 8 : 2)
+                        + strlen (option.get_initializer_suffix()));
+      if (columns == 0)
+        columns = 1;
+    }
+  else
+    {
+      columns = (option[SHAREDLIB] ? 9 : option[NULLSTRINGS] ? 4 : 9);
+    }
+  int column = 0;
+  for (int i = 0; i < count; i++)
+    {
+      if ((column % columns) == 0)
+        {
+          if (i > 0)
+            printf (",\n");
+          printf ("%s    ", indent);
+        }
+      else
+        {
+          if (i > 0)
+            printf (", ");
+        }
+      if (option[TYPE])
+        printf ("{");
+      if (option[SHAREDLIB])
+        printf ("-1");
+      else
+        {
+          if (option[NULLSTRINGS])
+            printf ("(char*)0");
+          else
+            printf ("\"\"");
+        }
+      if (option[TYPE])
+        printf ("%s}", option.get_initializer_suffix());
+      column++;
+    }
+}
+
+/* Prints out the array containing the keywords for the hash function.  */
+
+void
+Output::output_keyword_table () const
+{
+  const char *indent  = option[GLOBAL] ? "" : "  ";
+  int index;
+  KeywordExt_List *temp;
+
+  printf ("%sstatic ",
+          indent);
+  output_const_type (const_readonly_array, _wordlist_eltype);
+  printf ("%s[] =\n"
+          "%s  {\n",
+          option.get_wordlist_name (),
+          indent);
+
+  /* Generate an array of reserved words at appropriate locations.  */
+
+  for (temp = _head, index = 0; temp; temp = temp->rest())
+    {
+      KeywordExt *keyword = temp->first();
+
+      /* If generating a switch statement, and there is no user defined type,
+         we generate non-duplicates directly in the code.  Only duplicates go
+         into the table.  */
+      if (option[SWITCH] && !option[TYPE] && !keyword->_duplicate_link)
+        continue;
+
+      if (index > 0)
+        printf (",\n");
+
+      if (index < keyword->_hash_value && !option[SWITCH] && !option[DUP])
+        {
+          /* Some blank entries.  */
+          output_keyword_blank_entries (keyword->_hash_value - index, indent);
+          printf (",\n");
+          index = keyword->_hash_value;
+        }
+
+      keyword->_final_index = index;
+
+      output_keyword_entry (keyword, index, indent);
+
+      /* Deal with duplicates specially.  */
+      if (keyword->_duplicate_link) // implies option[DUP]
+        for (KeywordExt *links = keyword->_duplicate_link; links; links = links->_duplicate_link)
+          {
+            links->_final_index = ++index;
+            printf (",\n");
+            int stringpool_index =
+              (links->_allchars_length == keyword->_allchars_length
+               && memcmp (links->_allchars, keyword->_allchars,
+                          keyword->_allchars_length) == 0
+               ? keyword->_final_index
+               : links->_final_index);
+            output_keyword_entry (links, stringpool_index, indent);
+          }
+
+      index++;
+    }
+  if (index > 0)
+    printf ("\n");
+
+  printf ("%s  };\n\n", indent);
+}
+
+/* ------------------------------------------------------------------------- */
+
+/* Generates the large, sparse table that maps hash values into
+   the smaller, contiguous range of the keyword table.  */
+
+void
+Output::output_lookup_array () const
+{
+  if (option[DUP])
+    {
+      const int DEFAULT_VALUE = -1;
+
+      /* Because of the way output_keyword_table works, every duplicate set is
+         stored contiguously in the wordlist array.  */
+      struct duplicate_entry
+        {
+          int hash_value; /* Hash value for this particular duplicate set.  */
+          int index;      /* Index into the main keyword storage array.  */
+          int count;      /* Number of consecutive duplicates at this index.  */
+        };
+
+      duplicate_entry *duplicates = new duplicate_entry[_total_duplicates];
+      int *lookup_array = new int[_max_hash_value + 1 + 2*_total_duplicates];
+      int lookup_array_size = _max_hash_value + 1;
+      duplicate_entry *dup_ptr = &duplicates[0];
+      int *lookup_ptr = &lookup_array[_max_hash_value + 1 + 2*_total_duplicates];
+
+      while (lookup_ptr > lookup_array)
+        *--lookup_ptr = DEFAULT_VALUE;
+
+      /* Now dup_ptr = &duplicates[0] and lookup_ptr = &lookup_array[0].  */
+
+      for (KeywordExt_List *temp = _head; temp; temp = temp->rest())
+        {
+          int hash_value = temp->first()->_hash_value;
+          lookup_array[hash_value] = temp->first()->_final_index;
+          if (option[DEBUG])
+            fprintf (stderr, "keyword = %.*s, index = %d\n",
+                     temp->first()->_allchars_length, temp->first()->_allchars, temp->first()->_final_index);
+          if (temp->first()->_duplicate_link)
+            {
+              /* Start a duplicate entry.  */
+              dup_ptr->hash_value = hash_value;
+              dup_ptr->index = temp->first()->_final_index;
+              dup_ptr->count = 1;
+
+              for (KeywordExt *ptr = temp->first()->_duplicate_link; ptr; ptr = ptr->_duplicate_link)
+                {
+                  dup_ptr->count++;
+                  if (option[DEBUG])
+                    fprintf (stderr,
+                             "static linked keyword = %.*s, index = %d\n",
+                             ptr->_allchars_length, ptr->_allchars, ptr->_final_index);
+                }
+              assert (dup_ptr->count >= 2);
+              dup_ptr++;
+            }
+        }
+
+      while (dup_ptr > duplicates)
+        {
+          dup_ptr--;
+
+          if (option[DEBUG])
+            fprintf (stderr,
+                     "dup_ptr[%d]: hash_value = %d, index = %d, count = %d\n",
+                     dup_ptr - duplicates,
+                     dup_ptr->hash_value, dup_ptr->index, dup_ptr->count);
+
+          int i;
+          /* Start searching for available space towards the right part
+             of the lookup array.  */
+          for (i = dup_ptr->hash_value; i < lookup_array_size-1; i++)
+            if (lookup_array[i] == DEFAULT_VALUE
+                && lookup_array[i + 1] == DEFAULT_VALUE)
+              goto found_i;
+          /* If we didn't find it to the right look to the left instead...  */
+          for (i = dup_ptr->hash_value-1; i >= 0; i--)
+            if (lookup_array[i] == DEFAULT_VALUE
+                && lookup_array[i + 1] == DEFAULT_VALUE)
+              goto found_i;
+          /* Append to the end of lookup_array.  */
+          i = lookup_array_size;
+          lookup_array_size += 2;
+        found_i:
+          /* Put in an indirection from dup_ptr->_hash_value to i.
+             At i and i+1 store dup_ptr->_final_index and dup_ptr->count.  */
+          assert (lookup_array[dup_ptr->hash_value] == dup_ptr->index);
+          lookup_array[dup_ptr->hash_value] = - 1 - _total_keys - i;
+          lookup_array[i] = - _total_keys + dup_ptr->index;
+          lookup_array[i + 1] = - dup_ptr->count;
+          /* All these three values are <= -2, distinct from DEFAULT_VALUE.  */
+        }
+
+      /* The values of the lookup array are now known.  */
+
+      int min = INT_MAX;
+      int max = INT_MIN;
+      lookup_ptr = lookup_array + lookup_array_size;
+      while (lookup_ptr > lookup_array)
+        {
+          int val = *--lookup_ptr;
+          if (min > val)
+            min = val;
+          if (max < val)
+            max = val;
+        }
+
+      const char *indent = option[GLOBAL] ? "" : "  ";
+      printf ("%sstatic %s%s lookup[] =\n"
+              "%s  {",
+              indent, const_readonly_array, smallest_integral_type (min, max),
+              indent);
+
+      int field_width;
+      /* Calculate maximum number of digits required for MIN..MAX.  */
+      {
+        field_width = 2;
+        for (int trunc = max; (trunc /= 10) > 0;)
+          field_width++;
+      }
+      if (min < 0)
+        {
+          int neg_field_width = 2;
+          for (int trunc = -min; (trunc /= 10) > 0;)
+            neg_field_width++;
+          neg_field_width++; /* account for the minus sign */
+          if (field_width < neg_field_width)
+            field_width = neg_field_width;
+        }
+
+      const int columns = 42 / field_width;
+      int column;
+
+      column = 0;
+      for (int i = 0; i < lookup_array_size; i++)
+        {
+          if (i > 0)
+            printf (",");
+          if ((column++ % columns) == 0)
+            printf("\n%s   ", indent);
+          printf ("%*d", field_width, lookup_array[i]);
+        }
+      printf ("\n%s  };\n\n", indent);
+
+      delete[] duplicates;
+      delete[] lookup_array;
+    }
+}
+
+/* ------------------------------------------------------------------------- */
+
+/* Generate all pools needed for the lookup function.  */
+
+void
+Output::output_lookup_pools () const
+{
+  if (option[SWITCH])
+    {
+      if (option[TYPE] || (option[DUP] && _total_duplicates > 0))
+        output_string_pool ();
+    }
+  else
+    {
+      output_string_pool ();
+    }
+}
+
+/* Generate all the tables needed for the lookup function.  */
+
+void
+Output::output_lookup_tables () const
+{
+  if (option[SWITCH])
+    {
+      /* Use the switch in place of lookup table.  */
+      if (option[LENTABLE] && (option[DUP] && _total_duplicates > 0))
+        output_keylength_table ();
+      if (option[TYPE] || (option[DUP] && _total_duplicates > 0))
+        output_keyword_table ();
+    }
+  else
+    {
+      /* Use the lookup table, in place of switch.  */
+      if (option[LENTABLE])
+        output_keylength_table ();
+      output_keyword_table ();
+      output_lookup_array ();
+    }
+}
+
+/* ------------------------------------------------------------------------- */
+
+/* Output a single switch case (including duplicates).  Advance list.  */
+
+static KeywordExt_List *
+output_switch_case (KeywordExt_List *list, int indent, int *jumps_away)
+{
+  if (option[DEBUG])
+    printf ("%*s/* hash value = %4d, keyword = \"%.*s\" */\n",
+            indent, "", list->first()->_hash_value, list->first()->_allchars_length, list->first()->_allchars);
+
+  if (option[DUP] && list->first()->_duplicate_link)
+    {
+      if (option[LENTABLE])
+        printf ("%*slengthptr = &%s[%d];\n",
+                indent, "", option.get_lengthtable_name (), list->first()->_final_index);
+      printf ("%*swordptr = &%s[%d];\n",
+              indent, "", option.get_wordlist_name (), list->first()->_final_index);
+
+      int count = 0;
+      for (KeywordExt *links = list->first(); links; links = links->_duplicate_link)
+        count++;
+
+      printf ("%*swordendptr = wordptr + %d;\n"
+              "%*sgoto multicompare;\n",
+              indent, "", count,
+              indent, "");
+      *jumps_away = 1;
+    }
+  else
+    {
+      if (option[LENTABLE])
+        {
+          printf ("%*sif (len == %d)\n"
+                  "%*s  {\n",
+                  indent, "", list->first()->_allchars_length,
+                  indent, "");
+          indent += 4;
+        }
+      printf ("%*sresword = ",
+              indent, "");
+      if (option[TYPE])
+        printf ("&%s[%d]", option.get_wordlist_name (), list->first()->_final_index);
+      else
+        output_string (list->first()->_allchars, list->first()->_allchars_length);
+      printf (";\n");
+      printf ("%*sgoto compare;\n",
+              indent, "");
+      if (option[LENTABLE])
+        {
+          indent -= 4;
+          printf ("%*s  }\n",
+                  indent, "");
+        }
+      else
+        *jumps_away = 1;
+    }
+
+  return list->rest();
+}
+
+/* Output a total of size cases, grouped into num_switches switch statements,
+   where 0 < num_switches <= size.  */
+
+static void
+output_switches (KeywordExt_List *list, int num_switches, int size, int min_hash_value, int max_hash_value, int indent)
+{
+  if (option[DEBUG])
+    printf ("%*s/* know %d <= key <= %d, contains %d cases */\n",
+            indent, "", min_hash_value, max_hash_value, size);
+
+  if (num_switches > 1)
+    {
+      int part1 = num_switches / 2;
+      int part2 = num_switches - part1;
+      int size1 = static_cast<int>(static_cast<double>(size) / static_cast<double>(num_switches) * static_cast<double>(part1) + 0.5);
+      int size2 = size - size1;
+
+      KeywordExt_List *temp = list;
+      for (int count = size1; count > 0; count--)
+        temp = temp->rest();
+
+      printf ("%*sif (key < %d)\n"
+              "%*s  {\n",
+              indent, "", temp->first()->_hash_value,
+              indent, "");
+
+      output_switches (list, part1, size1, min_hash_value, temp->first()->_hash_value-1, indent+4);
+
+      printf ("%*s  }\n"
+              "%*selse\n"
+              "%*s  {\n",
+              indent, "", indent, "", indent, "");
+
+      output_switches (temp, part2, size2, temp->first()->_hash_value, max_hash_value, indent+4);
+
+      printf ("%*s  }\n",
+              indent, "");
+    }
+  else
+    {
+      /* Output a single switch.  */
+      int lowest_case_value = list->first()->_hash_value;
+      if (size == 1)
+        {
+          int jumps_away = 0;
+          assert (min_hash_value <= lowest_case_value);
+          assert (lowest_case_value <= max_hash_value);
+          if (min_hash_value == max_hash_value)
+            output_switch_case (list, indent, &jumps_away);
+          else
+            {
+              printf ("%*sif (key == %d)\n"
+                      "%*s  {\n",
+                      indent, "", lowest_case_value,
+                      indent, "");
+              output_switch_case (list, indent+4, &jumps_away);
+              printf ("%*s  }\n",
+                      indent, "");
+            }
+        }
+      else
+        {
+          if (lowest_case_value == 0)
+            printf ("%*sswitch (key)\n", indent, "");
+          else
+            printf ("%*sswitch (key - %d)\n", indent, "", lowest_case_value);
+          printf ("%*s  {\n",
+                  indent, "");
+          for (; size > 0; size--)
+            {
+              int jumps_away = 0;
+              printf ("%*s    case %d:\n",
+                      indent, "", list->first()->_hash_value - lowest_case_value);
+              list = output_switch_case (list, indent+6, &jumps_away);
+              if (!jumps_away)
+                printf ("%*s      break;\n",
+                        indent, "");
+            }
+          printf ("%*s  }\n",
+                  indent, "");
+        }
+    }
+}
+
+/* Generates C code to perform the keyword lookup.  */
+
+void
+Output::output_lookup_function_body (const Output_Compare& comparison) const
+{
+  printf ("  if (len <= MAX_WORD_LENGTH && len >= MIN_WORD_LENGTH)\n"
+          "    {\n"
+          "      register int key = %s (str, len);\n\n",
+          option.get_hash_name ());
+
+  if (option[SWITCH])
+    {
+      int switch_size = num_hash_values ();
+      int num_switches = option.get_total_switches ();
+      if (num_switches > switch_size)
+        num_switches = switch_size;
+
+      printf ("      if (key <= MAX_HASH_VALUE && key >= MIN_HASH_VALUE)\n"
+              "        {\n");
+      if (option[DUP] && _total_duplicates > 0)
+        {
+          if (option[LENTABLE])
+            printf ("          register %s%s *lengthptr;\n",
+                    const_always, smallest_integral_type (_max_key_len));
+          printf ("          register ");
+          output_const_type (const_readonly_array, _wordlist_eltype);
+          printf ("*wordptr;\n");
+          printf ("          register ");
+          output_const_type (const_readonly_array, _wordlist_eltype);
+          printf ("*wordendptr;\n");
+        }
+      if (option[TYPE])
+        {
+          printf ("          register ");
+          output_const_type (const_readonly_array, _struct_tag);
+          printf ("*resword;\n\n");
+        }
+      else
+        printf ("          register %sresword;\n\n",
+                _struct_tag);
+
+      output_switches (_head, num_switches, switch_size, _min_hash_value, _max_hash_value, 10);
+
+      printf ("          return 0;\n");
+      if (option[DUP] && _total_duplicates > 0)
+        {
+          int indent = 8;
+          printf ("%*smulticompare:\n"
+                  "%*s  while (wordptr < wordendptr)\n"
+                  "%*s    {\n",
+                  indent, "", indent, "", indent, "");
+          if (option[LENTABLE])
+            {
+              printf ("%*s      if (len == *lengthptr)\n"
+                      "%*s        {\n",
+                      indent, "", indent, "");
+              indent += 4;
+            }
+          printf ("%*s      register %schar *s = ",
+                  indent, "", const_always);
+          if (option[TYPE])
+            printf ("wordptr->%s", option.get_slot_name ());
+          else
+            printf ("*wordptr");
+          if (option[SHAREDLIB])
+            printf (" + %s",
+                    option.get_stringpool_name ());
+          printf (";\n\n"
+                  "%*s      if (",
+                  indent, "");
+          comparison.output_comparison (Output_Expr1 ("str"), Output_Expr1 ("s"));
+          printf (")\n"
+                  "%*s        return %s;\n",
+                  indent, "",
+                  option[TYPE] ? "wordptr" : "s");
+          if (option[LENTABLE])
+            {
+              indent -= 4;
+              printf ("%*s        }\n",
+                      indent, "");
+            }
+          if (option[LENTABLE])
+            printf ("%*s      lengthptr++;\n",
+                    indent, "");
+          printf ("%*s      wordptr++;\n"
+                  "%*s    }\n"
+                  "%*s  return 0;\n",
+                  indent, "", indent, "", indent, "");
+        }
+      printf ("        compare:\n");
+      if (option[TYPE])
+        {
+          printf ("          {\n"
+                  "            register %schar *s = resword->%s",
+                  const_always, option.get_slot_name ());
+          if (option[SHAREDLIB])
+            printf (" + %s",
+                    option.get_stringpool_name ());
+          printf (";\n\n"
+                  "            if (");
+          comparison.output_comparison (Output_Expr1 ("str"), Output_Expr1 ("s"));
+          printf (")\n"
+                  "              return resword;\n"
+                  "          }\n");
+        }
+      else
+        {
+          printf ("          if (");
+          comparison.output_comparison (Output_Expr1 ("str"), Output_Expr1 ("resword"));
+          printf (")\n"
+                  "            return resword;\n");
+        }
+      printf ("        }\n");
+    }
+  else
+    {
+      printf ("      if (key <= MAX_HASH_VALUE && key >= 0)\n");
+
+      if (option[DUP])
+        {
+          int indent = 8;
+          printf ("%*s{\n"
+                  "%*s  register int index = lookup[key];\n\n"
+                  "%*s  if (index >= 0)\n",
+                  indent, "", indent, "", indent, "");
+          if (option[LENTABLE])
+            {
+              printf ("%*s    {\n"
+                      "%*s      if (len == %s[index])\n",
+                      indent, "", indent, "", option.get_lengthtable_name ());
+              indent += 4;
+            }
+          printf ("%*s    {\n"
+                  "%*s      register %schar *s = %s[index]",
+                  indent, "",
+                  indent, "", const_always, option.get_wordlist_name ());
+          if (option[TYPE])
+            printf (".%s", option.get_slot_name ());
+          if (option[SHAREDLIB])
+            printf (" + %s",
+                    option.get_stringpool_name ());
+          printf (";\n\n"
+                  "%*s      if (",
+                  indent, "");
+          comparison.output_comparison (Output_Expr1 ("str"), Output_Expr1 ("s"));
+          printf (")\n"
+                  "%*s        return ",
+                  indent, "");
+          if (option[TYPE])
+            printf ("&%s[index]", option.get_wordlist_name ());
+          else
+            printf ("s");
+          printf (";\n"
+                  "%*s    }\n",
+                  indent, "");
+          if (option[LENTABLE])
+            {
+              indent -= 4;
+              printf ("%*s    }\n", indent, "");
+            }
+          if (_total_duplicates > 0)
+            {
+              printf ("%*s  else if (index < -TOTAL_KEYWORDS)\n"
+                      "%*s    {\n"
+                      "%*s      register int offset = - 1 - TOTAL_KEYWORDS - index;\n",
+                      indent, "", indent, "", indent, "");
+              if (option[LENTABLE])
+                printf ("%*s      register %s%s *lengthptr = &%s[TOTAL_KEYWORDS + lookup[offset]];\n",
+                        indent, "", const_always, smallest_integral_type (_max_key_len),
+                        option.get_lengthtable_name ());
+              printf ("%*s      register ",
+                      indent, "");
+              output_const_type (const_readonly_array, _wordlist_eltype);
+              printf ("*wordptr = &%s[TOTAL_KEYWORDS + lookup[offset]];\n",
+                      option.get_wordlist_name ());
+              printf ("%*s      register ",
+                      indent, "");
+              output_const_type (const_readonly_array, _wordlist_eltype);
+              printf ("*wordendptr = wordptr + -lookup[offset + 1];\n\n");
+              printf ("%*s      while (wordptr < wordendptr)\n"
+                      "%*s        {\n",
+                      indent, "", indent, "");
+              if (option[LENTABLE])
+                {
+                  printf ("%*s          if (len == *lengthptr)\n"
+                          "%*s            {\n",
+                          indent, "", indent, "");
+                  indent += 4;
+                }
+              printf ("%*s          register %schar *s = ",
+                      indent, "", const_always);
+              if (option[TYPE])
+                printf ("wordptr->%s", option.get_slot_name ());
+              else
+                printf ("*wordptr");
+              if (option[SHAREDLIB])
+                printf (" + %s",
+                        option.get_stringpool_name ());
+              printf (";\n\n"
+                      "%*s          if (",
+                      indent, "");
+              comparison.output_comparison (Output_Expr1 ("str"), Output_Expr1 ("s"));
+              printf (")\n"
+                      "%*s            return %s;\n",
+                      indent, "",
+                      option[TYPE] ? "wordptr" : "s");
+              if (option[LENTABLE])
+                {
+                  indent -= 4;
+                  printf ("%*s            }\n",
+                          indent, "");
+                }
+              if (option[LENTABLE])
+                printf ("%*s          lengthptr++;\n",
+                        indent, "");
+              printf ("%*s          wordptr++;\n"
+                      "%*s        }\n"
+                      "%*s    }\n",
+                      indent, "", indent, "", indent, "");
+            }
+          printf ("%*s}\n",
+                  indent, "");
+        }
+      else
+        {
+          int indent = 8;
+          if (option[LENTABLE])
+            {
+              printf ("%*sif (len == %s[key])\n",
+                      indent, "", option.get_lengthtable_name ());
+              indent += 2;
+            }
+
+          if (option[SHAREDLIB])
+            {
+              if (!option[LENTABLE])
+                {
+                  printf ("%*s{\n"
+                          "%*s  register int o = %s[key]",
+                          indent, "",
+                          indent, "", option.get_wordlist_name ());
+                  if (option[TYPE])
+                    printf (".%s", option.get_slot_name ());
+                  printf (";\n"
+                          "%*s  if (o >= 0)\n"
+                          "%*s    {\n",
+                          indent, "",
+                          indent, "");
+                  indent += 4;
+                  printf ("%*s  register %schar *s = o",
+                          indent, "", const_always);
+                }
+              else
+                {
+                  /* No need for the (o >= 0) test, because the
+                     (len == lengthtable[key]) test already guarantees that
+                     key points to nonempty table entry.  */
+                  printf ("%*s{\n"
+                          "%*s  register %schar *s = %s[key]",
+                          indent, "",
+                          indent, "", const_always,
+                          option.get_wordlist_name ());
+                  if (option[TYPE])
+                    printf (".%s", option.get_slot_name ());
+                }
+              printf (" + %s",
+                      option.get_stringpool_name ());
+            }
+          else
+            {
+              printf ("%*s{\n"
+                      "%*s  register %schar *s = %s[key]",
+                      indent, "",
+                      indent, "", const_always, option.get_wordlist_name ());
+              if (option[TYPE])
+                printf (".%s", option.get_slot_name ());
+            }
+
+          printf (";\n\n"
+                  "%*s  if (",
+                  indent, "");
+          if (!option[SHAREDLIB] && option[NULLSTRINGS])
+            printf ("s && ");
+          comparison.output_comparison (Output_Expr1 ("str"), Output_Expr1 ("s"));
+          printf (")\n"
+                  "%*s    return ",
+                  indent, "");
+          if (option[TYPE])
+            printf ("&%s[key]", option.get_wordlist_name ());
+          else
+            printf ("s");
+          printf (";\n");
+          if (option[SHAREDLIB] && !option[LENTABLE])
+            {
+              indent -= 4;
+              printf ("%*s    }\n",
+                      indent, "");
+            }
+          printf ("%*s}\n",
+                  indent, "");
+        }
+    }
+  printf ("    }\n"
+          "  return 0;\n");
+}
+
+/* Generates C code for the lookup function.  */
+
+void
+Output::output_lookup_function () const
+{
+  /* Output the function's head.  */
+  if (option[KRC] | option[C] | option[ANSIC])
+    /* GCC 4.3 and above with -std=c99 or -std=gnu99 implements ISO C99
+       inline semantics, unless -fgnu89-inline is used.  It defines a macro
+       __GNUC_STDC_INLINE__ to indicate this situation.  */
+    printf ("#ifdef __GNUC__\n"
+            "__inline\n"
+            "#ifdef __GNUC_STDC_INLINE__\n"
+            "__attribute__ ((__gnu_inline__))\n"
+            "#endif\n"
+            "#endif\n");
+
+  printf ("%s%s\n",
+          const_for_struct, _return_type);
+  if (option[CPLUSPLUS])
+    printf ("%s::", option.get_class_name ());
+  printf ("%s ", option.get_function_name ());
+  printf (option[KRC] ?
+                 "(str, len)\n"
+            "     register char *str;\n"
+            "     register unsigned int len;\n" :
+          option[C] ?
+                 "(str, len)\n"
+            "     register const char *str;\n"
+            "     register unsigned int len;\n" :
+          option[ANSIC] | option[CPLUSPLUS] ?
+                 "(register const char *str, register unsigned int len)\n" :
+          "");
+
+  /* Output the function's body.  */
+  printf ("{\n");
+
+  if (option[ENUM] && !option[GLOBAL])
+    {
+      Output_Enum style ("  ");
+      output_constants (style);
+    }
+
+  if (option[SHAREDLIB] && !(option[GLOBAL] || option[TYPE]))
+    output_lookup_pools ();
+  if (!option[GLOBAL])
+    output_lookup_tables ();
+
+  if (option[LENTABLE])
+    output_lookup_function_body (Output_Compare_Memcmp ());
+  else
+    {
+      if (option[COMP])
+        output_lookup_function_body (Output_Compare_Strncmp ());
+      else
+        output_lookup_function_body (Output_Compare_Strcmp ());
+    }
+
+  printf ("}\n");
+}
+
+/* ------------------------------------------------------------------------- */
+
+/* Generates the hash function and the key word recognizer function
+   based upon the user's Options.  */
+
+void
+Output::output ()
+{
+  compute_min_max ();
+
+  if (option[C] | option[ANSIC] | option[CPLUSPLUS])
+    {
+      const_always = "const ";
+      const_readonly_array = (option[CONST] ? "const " : "");
+      const_for_struct = ((option[CONST] && option[TYPE]) ? "const " : "");
+    }
+  else
+    {
+      const_always = "";
+      const_readonly_array = "";
+      const_for_struct = "";
+    }
+
+  if (!option[TYPE])
+    {
+      _return_type = (const_always[0] ? "const char *" : "char *");
+      _struct_tag = (const_always[0] ? "const char *" : "char *");
+    }
+
+  _wordlist_eltype = (option[SHAREDLIB] && !option[TYPE] ? "int" : _struct_tag);
+
+  printf ("/* ");
+  if (option[KRC])
+    printf ("KR-C");
+  else if (option[C])
+    printf ("C");
+  else if (option[ANSIC])
+    printf ("ANSI-C");
+  else if (option[CPLUSPLUS])
+    printf ("C++");
+  printf (" code produced by gperf version %s */\n", version_string);
+  option.print_options ();
+  printf ("\n");
+  if (!option[POSITIONS])
+    {
+      printf ("/* Computed positions: -k'");
+      _key_positions.print();
+      printf ("' */\n");
+    }
+  printf ("\n");
+
+  if (_charset_dependent
+      && (_key_positions.get_size() > 0 || option[UPPERLOWER]))
+    {
+      /* The generated tables assume that the execution character set is
+         based on ISO-646, not EBCDIC.  */
+      printf ("#if !((' ' == 32) && ('!' == 33) && ('\"' == 34) && ('#' == 35) \\\n"
+              "      && ('%%' == 37) && ('&' == 38) && ('\\'' == 39) && ('(' == 40) \\\n"
+              "      && (')' == 41) && ('*' == 42) && ('+' == 43) && (',' == 44) \\\n"
+              "      && ('-' == 45) && ('.' == 46) && ('/' == 47) && ('0' == 48) \\\n"
+              "      && ('1' == 49) && ('2' == 50) && ('3' == 51) && ('4' == 52) \\\n"
+              "      && ('5' == 53) && ('6' == 54) && ('7' == 55) && ('8' == 56) \\\n"
+              "      && ('9' == 57) && (':' == 58) && (';' == 59) && ('<' == 60) \\\n"
+              "      && ('=' == 61) && ('>' == 62) && ('?' == 63) && ('A' == 65) \\\n"
+              "      && ('B' == 66) && ('C' == 67) && ('D' == 68) && ('E' == 69) \\\n"
+              "      && ('F' == 70) && ('G' == 71) && ('H' == 72) && ('I' == 73) \\\n"
+              "      && ('J' == 74) && ('K' == 75) && ('L' == 76) && ('M' == 77) \\\n"
+              "      && ('N' == 78) && ('O' == 79) && ('P' == 80) && ('Q' == 81) \\\n"
+              "      && ('R' == 82) && ('S' == 83) && ('T' == 84) && ('U' == 85) \\\n"
+              "      && ('V' == 86) && ('W' == 87) && ('X' == 88) && ('Y' == 89) \\\n"
+              "      && ('Z' == 90) && ('[' == 91) && ('\\\\' == 92) && (']' == 93) \\\n"
+              "      && ('^' == 94) && ('_' == 95) && ('a' == 97) && ('b' == 98) \\\n"
+              "      && ('c' == 99) && ('d' == 100) && ('e' == 101) && ('f' == 102) \\\n"
+              "      && ('g' == 103) && ('h' == 104) && ('i' == 105) && ('j' == 106) \\\n"
+              "      && ('k' == 107) && ('l' == 108) && ('m' == 109) && ('n' == 110) \\\n"
+              "      && ('o' == 111) && ('p' == 112) && ('q' == 113) && ('r' == 114) \\\n"
+              "      && ('s' == 115) && ('t' == 116) && ('u' == 117) && ('v' == 118) \\\n"
+              "      && ('w' == 119) && ('x' == 120) && ('y' == 121) && ('z' == 122) \\\n"
+              "      && ('{' == 123) && ('|' == 124) && ('}' == 125) && ('~' == 126))\n"
+              "/* The character set is not based on ISO-646.  */\n");
+      printf ("%s \"gperf generated tables don't work with this execution character set. Please report a bug to <bug-gnu-gperf at gnu.org>.\"\n", option[KRC] || option[C] ? "error" : "#error");
+      printf ("#endif\n\n");
+    }
+
+  if (_verbatim_declarations < _verbatim_declarations_end)
+    {
+      output_line_directive (_verbatim_declarations_lineno);
+      fwrite (_verbatim_declarations, 1,
+              _verbatim_declarations_end - _verbatim_declarations, stdout);
+    }
+
+  if (option[TYPE] && !option[NOTYPE]) /* Output type declaration now, reference it later on.... */
+    {
+      output_line_directive (_struct_decl_lineno);
+      printf ("%s\n", _struct_decl);
+    }
+
+  if (option[INCLUDE])
+    printf ("#include <string.h>\n"); /* Declare strlen(), strcmp(), strncmp(). */
+
+  if (!option[ENUM])
+    {
+      Output_Defines style;
+      output_constants (style);
+    }
+  else if (option[GLOBAL])
+    {
+      Output_Enum style ("");
+      output_constants (style);
+    }
+
+  printf ("/* maximum key range = %d, duplicates = %d */\n\n",
+          _max_hash_value - _min_hash_value + 1, _total_duplicates);
+
+  if (option[UPPERLOWER])
+    {
+      #if USE_DOWNCASE_TABLE
+      output_upperlower_table ();
+      #endif
+
+      if (option[LENTABLE])
+        output_upperlower_memcmp ();
+      else
+        {
+          if (option[COMP])
+            output_upperlower_strncmp ();
+          else
+            output_upperlower_strcmp ();
+        }
+    }
+
+  if (option[CPLUSPLUS])
+    printf ("class %s\n"
+            "{\n"
+            "private:\n"
+            "  static inline unsigned int %s (const char *str, unsigned int len);\n"
+            "public:\n"
+            "  static %s%s%s (const char *str, unsigned int len);\n"
+            "};\n"
+            "\n",
+            option.get_class_name (), option.get_hash_name (),
+            const_for_struct, _return_type, option.get_function_name ());
+
+  output_hash_function ();
+
+  if (option[SHAREDLIB] && (option[GLOBAL] || option[TYPE]))
+    output_lookup_pools ();
+  if (option[GLOBAL])
+    output_lookup_tables ();
+
+  output_lookup_function ();
+
+  if (_verbatim_code < _verbatim_code_end)
+    {
+      output_line_directive (_verbatim_code_lineno);
+      fwrite (_verbatim_code, 1, _verbatim_code_end - _verbatim_code, stdout);
+    }
+
+  fflush (stdout);
+}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/src/output.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/contrib/gperf/src/output.h	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,154 @@
+/* This may look like C code, but it is really -*- C++ -*- */
+
+/* Output routines.
+
+   Copyright (C) 1989-1998, 2000, 2002-2003 Free Software Foundation, Inc.
+   Written by Douglas C. Schmidt <schmidt at ics.uci.edu>
+   and Bruno Haible <bruno at clisp.org>.
+
+   This file is part of GNU GPERF.
+
+   GNU GPERF 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 GPERF 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; see the file COPYING.
+   If not, write to the Free Software Foundation, Inc.,
+   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
+
+#ifndef output_h
+#define output_h 1
+
+#include "keyword-list.h"
+#include "positions.h"
+
+/* OSF/1 cxx needs these forward declarations. */
+struct Output_Constants;
+struct Output_Compare;
+
+class Output
+{
+public:
+  /* Constructor.  */
+                        Output (KeywordExt_List *head,
+                                const char *struct_decl,
+                                unsigned int struct_decl_lineno,
+                                const char *return_type,
+                                const char *struct_tag,
+                                const char *verbatim_declarations,
+                                const char *verbatim_declarations_end,
+                                unsigned int verbatim_declarations_lineno,
+                                const char *verbatim_code,
+                                const char *verbatim_code_end,
+                                unsigned int verbatim_code_lineno,
+                                bool charset_dependent,
+                                int total_keys,
+                                int max_key_len, int min_key_len,
+                                const Positions& positions,
+                                const unsigned int *alpha_inc,
+                                int total_duplicates,
+                                unsigned int alpha_size,
+                                const int *asso_values);
+
+  /* Generates the hash function and the key word recognizer function.  */
+  void                  output ();
+
+private:
+
+  /* Computes the minimum and maximum hash values, and stores them
+     in _min_hash_value and _max_hash_value.  */
+  void                  compute_min_max ();
+
+  /* Returns the number of different hash values.  */
+  int                   num_hash_values () const;
+
+  /* Outputs the maximum and minimum hash values etc.  */
+  void                  output_constants (struct Output_Constants&) const;
+
+  /* Generates a C expression for an asso_values[] reference.  */
+  void                  output_asso_values_ref (int pos) const;
+
+  /* Generates C code for the hash function that returns the
+     proper encoding for each keyword.  */
+  void                  output_hash_function () const;
+
+  /* Prints out a table of keyword lengths, for use with the
+     comparison code in generated function 'in_word_set'.  */
+  void                  output_keylength_table () const;
+
+  /* Prints out the string pool, containing the strings of the keyword table.
+   */
+  void                  output_string_pool () const;
+
+  /* Prints out the array containing the keywords for the hash function.  */
+  void                  output_keyword_table () const;
+
+  /* Generates the large, sparse table that maps hash values into
+     the smaller, contiguous range of the keyword table.  */
+  void                  output_lookup_array () const;
+
+  /* Generate all pools needed for the lookup function.  */
+  void                  output_lookup_pools () const;
+
+  /* Generate all the tables needed for the lookup function.  */
+  void                  output_lookup_tables () const;
+
+  /* Generates C code to perform the keyword lookup.  */
+  void                  output_lookup_function_body (const struct Output_Compare&) const;
+
+  /* Generates C code for the lookup function.  */
+  void                  output_lookup_function () const;
+
+  /* Linked list of keywords.  */
+  KeywordExt_List *     _head;
+
+  /* Declaration of struct type for a keyword and its attributes.  */
+  const char * const    _struct_decl;
+  unsigned int const    _struct_decl_lineno;
+  /* Pointer to return type for lookup function. */
+  const char *          _return_type;
+  /* Shorthand for user-defined struct tag type. */
+  const char *          _struct_tag;
+  /* Element type of keyword array.  */
+  const char *          _wordlist_eltype;
+  /* The C code from the declarations section.  */
+  const char * const    _verbatim_declarations;
+  const char * const    _verbatim_declarations_end;
+  unsigned int const    _verbatim_declarations_lineno;
+  /* The C code from the end of the file.  */
+  const char * const    _verbatim_code;
+  const char * const    _verbatim_code_end;
+  unsigned int const    _verbatim_code_lineno;
+  /* Whether the keyword chars would have different values in a different
+     character set.  */
+  bool                  _charset_dependent;
+  /* Total number of keys, counting duplicates. */
+  int const             _total_keys;
+  /* Maximum length of the longest keyword. */
+  int const             _max_key_len;
+  /* Minimum length of the shortest keyword. */
+  int const             _min_key_len;
+  /* Key positions.  */
+  Positions const       _key_positions;
+  /* Adjustments to add to bytes add specific key positions.  */
+  const unsigned int * const _alpha_inc;
+  /* Total number of duplicate hash values. */
+  int const             _total_duplicates;
+  /* Minimum hash value for all keywords. */
+  int                   _min_hash_value;
+  /* Maximum hash value for all keywords. */
+  int                   _max_hash_value;
+  /* Size of alphabet. */
+  unsigned int const    _alpha_size;
+  /* Value associated with each character. */
+  const int * const     _asso_values;
+};
+
+#endif
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/src/positions.cc
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/contrib/gperf/src/positions.cc	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,177 @@
+/* A set of byte positions.
+   Copyright (C) 1989-1998, 2000, 2002 Free Software Foundation, Inc.
+   Written by Douglas C. Schmidt <schmidt at ics.uci.edu>
+   and Bruno Haible <bruno at clisp.org>.
+
+   This file is part of GNU GPERF.
+
+   GNU GPERF 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 GPERF 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; see the file COPYING.
+   If not, write to the Free Software Foundation, Inc.,
+   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
+
+/* Specification. */
+#include "positions.h"
+
+#include <stdio.h>
+#include <stdlib.h> /* declares exit() */
+#include <string.h>
+
+/* ---------------------------- Class Positions ---------------------------- */
+
+/* Set operations.  Assumes the array is in reverse order.  */
+
+bool
+Positions::contains (int pos) const
+{
+  unsigned int count = _size;
+  const int *p = _positions + _size - 1;
+
+  for (; count > 0; p--, count--)
+    {
+      if (*p == pos)
+        return true;
+      if (*p > pos)
+        break;
+    }
+  return false;
+}
+
+void
+Positions::add (int pos)
+{
+  set_useall (false);
+
+  unsigned int count = _size;
+
+  if (count == MAX_SIZE)
+    {
+      fprintf (stderr, "Positions::add internal error: overflow\n");
+      exit (1);
+    }
+
+  int *p = _positions + _size - 1;
+
+  for (; count > 0; p--, count--)
+    {
+      if (*p == pos)
+        {
+          fprintf (stderr, "Positions::add internal error: duplicate\n");
+          exit (1);
+        }
+      if (*p > pos)
+        break;
+      p[1] = p[0];
+    }
+  p[1] = pos;
+  _size++;
+}
+
+void
+Positions::remove (int pos)
+{
+  set_useall (false);
+
+  unsigned int count = _size;
+  if (count > 0)
+    {
+      int *p = _positions + _size - 1;
+
+      if (*p == pos)
+        {
+          _size--;
+          return;
+        }
+      if (*p < pos)
+        {
+          int prev = *p;
+
+          for (;;)
+            {
+              p--;
+              count--;
+              if (count == 0)
+                break;
+              if (*p == pos)
+                {
+                  *p = prev;
+                  _size--;
+                  return;
+                }
+              if (*p > pos)
+                break;
+              int curr = *p;
+              *p = prev;
+              prev = curr;
+            }
+        }
+    }
+  fprintf (stderr, "Positions::remove internal error: not found\n");
+  exit (1);
+}
+
+/* Output in external syntax.  */
+void
+Positions::print () const
+{
+  if (_useall)
+    printf ("*");
+  else
+    {
+      bool first = true;
+      bool seen_LASTCHAR = false;
+      unsigned int count = _size;
+      const int *p = _positions + _size - 1;
+
+      for (; count > 0; p--)
+        {
+          count--;
+          if (*p == LASTCHAR)
+            seen_LASTCHAR = true;
+          else
+            {
+              if (!first)
+                printf (",");
+              printf ("%d", *p + 1);
+              if (count > 0 && p[-1] == *p + 1)
+                {
+                  printf ("-");
+                  do
+                    {
+                      p--;
+                      count--;
+                    }
+                  while (count > 0 && p[-1] == *p + 1);
+                  printf ("%d", *p + 1);
+                }
+              first = false;
+            }
+        }
+      if (seen_LASTCHAR)
+        {
+          if (!first)
+            printf (",");
+          printf ("$");
+        }
+    }
+}
+
+/* ------------------------------------------------------------------------- */
+
+#ifndef __OPTIMIZE__
+
+#define INLINE /* not inline */
+#include "positions.icc"
+#undef INLINE
+
+#endif /* not defined __OPTIMIZE__ */
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/src/positions.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/contrib/gperf/src/positions.h	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,175 @@
+/* This may look like C code, but it is really -*- C++ -*- */
+
+/* A set of byte positions.
+
+   Copyright (C) 1989-1998, 2000, 2002, 2005 Free Software Foundation, Inc.
+   Written by Douglas C. Schmidt <schmidt at ics.uci.edu>
+   and Bruno Haible <bruno at clisp.org>.
+
+   This file is part of GNU GPERF.
+
+   GNU GPERF 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 GPERF 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; see the file COPYING.
+   If not, write to the Free Software Foundation, Inc.,
+   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
+
+#ifndef positions_h
+#define positions_h 1
+
+/* Classes defined below.  */
+class PositionIterator;
+class PositionReverseIterator;
+
+/* This class denotes a set of byte positions, used to access a keyword.  */
+
+class Positions
+{
+  friend class PositionIterator;
+  friend class PositionReverseIterator;
+public:
+  /* Denotes the last char of a keyword, depending on the keyword's length.  */
+  enum {                LASTCHAR = -1 };
+
+  /* Maximum key position specifiable by the user, 1-based.
+     Note that MAX_KEY_POS-1 must fit into the element type of _positions[],
+     below.  */
+  enum {                MAX_KEY_POS = 255 };
+
+  /* Maximum possible size.  Since duplicates are eliminated and the possible
+     0-based positions are -1 .. MAX_KEY_POS-1, this is:  */
+  enum {                MAX_SIZE = MAX_KEY_POS + 1 };
+
+  /* Constructors.  */
+                        Positions ();
+                        Positions (int pos1);
+                        Positions (int pos1, int pos2);
+
+  /* Copy constructor.  */
+                        Positions (const Positions& src);
+
+  /* Assignment operator.  */
+  Positions&            operator= (const Positions& src);
+
+  /* Accessors.  */
+  bool                  is_useall () const;
+  int                   operator[] (unsigned int index) const;
+  unsigned int          get_size () const;
+
+  /* Write access.  */
+  void                  set_useall (bool useall);
+  int *                 pointer ();
+  void                  set_size (unsigned int size);
+
+  /* Sorts the array in reverse order.
+     Returns true if there are no duplicates, false otherwise.  */
+  bool                  sort ();
+
+  /* Creates an iterator, returning the positions in descending order.  */
+  PositionIterator      iterator () const;
+  /* Creates an iterator, returning the positions in descending order,
+     that apply to strings of length <= maxlen.  */
+  PositionIterator      iterator (int maxlen) const;
+  /* Creates an iterator, returning the positions in ascending order.  */
+  PositionReverseIterator reviterator () const;
+  /* Creates an iterator, returning the positions in ascending order,
+     that apply to strings of length <= maxlen.  */
+  PositionReverseIterator reviterator (int maxlen) const;
+
+  /* Set operations.  Assumes the array is in reverse order.  */
+  bool                  contains (int pos) const;
+  void                  add (int pos);
+  void                  remove (int pos);
+
+  /* Output in external syntax.  */
+  void                  print () const;
+
+private:
+  /* The special case denoted by '*'.  */
+  bool                  _useall;
+  /* Number of positions.  */
+  unsigned int          _size;
+  /* Array of positions.  0 for the first char, 1 for the second char etc.,
+     LASTCHAR for the last char.  */
+  int                   _positions[MAX_SIZE];
+};
+
+/* This class denotes an iterator through a set of byte positions.  */
+
+class PositionIterator
+{
+  friend class Positions;
+public:
+  /* Copy constructor.  */
+                        PositionIterator (const PositionIterator& src);
+
+  /* End of iteration marker.  */
+  enum {                EOS = -2 };
+
+  /* Retrieves the next position, or EOS past the end.  */
+  int                   next ();
+
+  /* Returns the number of remaining positions, i.e. how often next() will
+     return a value != EOS.  */
+  unsigned int          remaining () const;
+
+private:
+  /* Initializes an iterator through POSITIONS.  */
+                        PositionIterator (Positions const& positions);
+  /* Initializes an iterator through POSITIONS, ignoring positions >= maxlen.  */
+                        PositionIterator (Positions const& positions, int maxlen);
+
+  const Positions&      _set;
+  unsigned int          _index;
+};
+
+/* This class denotes an iterator in reverse direction through a set of
+   byte positions.  */
+
+class PositionReverseIterator
+{
+  friend class Positions;
+public:
+  /* Copy constructor.  */
+                        PositionReverseIterator (const PositionReverseIterator& src);
+
+  /* End of iteration marker.  */
+  enum {                EOS = -2 };
+
+  /* Retrieves the next position, or EOS past the end.  */
+  int                   next ();
+
+  /* Returns the number of remaining positions, i.e. how often next() will
+     return a value != EOS.  */
+  unsigned int          remaining () const;
+
+private:
+  /* Initializes an iterator through POSITIONS.  */
+                        PositionReverseIterator (Positions const& positions);
+  /* Initializes an iterator through POSITIONS, ignoring positions >= maxlen.  */
+                        PositionReverseIterator (Positions const& positions, int maxlen);
+
+  const Positions&      _set;
+  unsigned int          _index;
+  unsigned int          _minindex;
+};
+
+#ifdef __OPTIMIZE__
+
+#include <string.h>
+#define INLINE inline
+#include "positions.icc"
+#undef INLINE
+
+#endif
+
+#endif
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/src/positions.icc
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/contrib/gperf/src/positions.icc	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,285 @@
+/* Inline Functions for positions.{h,cc}.
+
+   Copyright (C) 1989-1998, 2000, 2002 Free Software Foundation, Inc.
+   Written by Douglas C. Schmidt <schmidt at ics.uci.edu>
+   and Bruno Haible <bruno at clisp.org>.
+
+   This file is part of GNU GPERF.
+
+   GNU GPERF 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 GPERF 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; see the file COPYING.
+   If not, write to the Free Software Foundation, Inc.,
+   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
+
+// This needs:
+//#include <string.h>
+
+/* ---------------------------- Class Positions ---------------------------- */
+
+/* Constructors.  */
+
+INLINE
+Positions::Positions ()
+  : _useall (false),
+    _size (0)
+{
+}
+
+INLINE
+Positions::Positions (int pos1)
+  : _useall (false),
+    _size (1)
+{
+  _positions[0] = pos1;
+}
+
+INLINE
+Positions::Positions (int pos1, int pos2)
+  : _useall (false),
+    _size (2)
+{
+  _positions[0] = pos1;
+  _positions[1] = pos2;
+}
+
+/* Copy constructor.  */
+
+INLINE
+Positions::Positions (const Positions& src)
+  : _useall (src._useall),
+    _size (src._size)
+{
+  memcpy (_positions, src._positions, _size * sizeof (_positions[0]));
+}
+
+/* Assignment operator.  */
+
+INLINE Positions&
+Positions::operator= (const Positions& src)
+{
+  _useall = src._useall;
+  _size = src._size;
+  memcpy (_positions, src._positions, _size * sizeof (_positions[0]));
+  return *this;
+}
+
+/* Accessors.  */
+
+INLINE bool
+Positions::is_useall () const
+{
+  return _useall;
+}
+
+INLINE int
+Positions::operator[] (unsigned int index) const
+{
+  return _positions[index];
+}
+
+INLINE unsigned int
+Positions::get_size () const
+{
+  return _size;
+}
+
+/* Write access.  */
+
+INLINE void
+Positions::set_useall (bool useall)
+{
+  _useall = useall;
+  if (useall)
+    {
+      /* The positions are 0, 1, ..., MAX_KEY_POS-1, in descending order.  */
+      _size = MAX_KEY_POS;
+      int *ptr = _positions;
+      for (int i = MAX_KEY_POS - 1; i >= 0; i--)
+        *ptr++ = i;
+    }
+}
+
+INLINE int *
+Positions::pointer ()
+{
+  return _positions;
+}
+
+INLINE void
+Positions::set_size (unsigned int size)
+{
+  _size = size;
+}
+
+/* Sorts the array in reverse order.
+   Returns true if there are no duplicates, false otherwise.  */
+INLINE bool
+Positions::sort ()
+{
+  if (_useall)
+    return true;
+
+  /* Bubble sort.  */
+  bool duplicate_free = true;
+  int *base = _positions;
+  unsigned int len = _size;
+
+  for (unsigned int i = 1; i < len; i++)
+    {
+      unsigned int j;
+      int tmp;
+
+      for (j = i, tmp = base[j]; j > 0 && tmp >= base[j - 1]; j--)
+        if ((base[j] = base[j - 1]) == tmp) /* oh no, a duplicate!!! */
+          duplicate_free = false;
+
+      base[j] = tmp;
+    }
+
+  return duplicate_free;
+}
+
+/* Creates an iterator, returning the positions in descending order.  */
+INLINE PositionIterator
+Positions::iterator () const
+{
+  return PositionIterator (*this);
+}
+
+/* Creates an iterator, returning the positions in descending order,
+   that apply to strings of length <= maxlen.  */
+INLINE PositionIterator
+Positions::iterator (int maxlen) const
+{
+  return PositionIterator (*this, maxlen);
+}
+
+/* Creates an iterator, returning the positions in ascending order.  */
+INLINE PositionReverseIterator
+Positions::reviterator () const
+{
+  return PositionReverseIterator (*this);
+}
+
+/* Creates an iterator, returning the positions in ascending order,
+   that apply to strings of length <= maxlen.  */
+INLINE PositionReverseIterator
+Positions::reviterator (int maxlen) const
+{
+  return PositionReverseIterator (*this, maxlen);
+}
+
+/* ------------------------- Class PositionIterator ------------------------ */
+
+/* Initializes an iterator through POSITIONS.  */
+INLINE
+PositionIterator::PositionIterator (Positions const& positions)
+  : _set (positions),
+    _index (0)
+{
+}
+
+/* Initializes an iterator through POSITIONS, ignoring positions >= maxlen.  */
+INLINE
+PositionIterator::PositionIterator (Positions const& positions, int maxlen)
+  : _set (positions)
+{
+  if (positions._useall)
+    _index = (maxlen <= Positions::MAX_KEY_POS ? Positions::MAX_KEY_POS - maxlen : 0);
+  else
+    {
+      unsigned int index;
+      for (index = 0;
+           index < positions._size && positions._positions[index] >= maxlen;
+           index++)
+        ;
+      _index = index;
+    }
+}
+
+/* Retrieves the next position, or EOS past the end.  */
+INLINE int
+PositionIterator::next ()
+{
+  return (_index < _set._size ? _set._positions[_index++] : EOS);
+}
+
+/* Returns the number of remaining positions, i.e. how often next() will
+   return a value != EOS.  */
+INLINE unsigned int
+PositionIterator::remaining () const
+{
+  return _set._size - _index;
+}
+
+/* Copy constructor.  */
+INLINE
+PositionIterator::PositionIterator (const PositionIterator& src)
+  : _set (src._set),
+    _index (src._index)
+{
+}
+
+/* --------------------- Class PositionReverseIterator --------------------- */
+
+/* Initializes an iterator through POSITIONS.  */
+INLINE
+PositionReverseIterator::PositionReverseIterator (Positions const& positions)
+  : _set (positions),
+    _index (_set._size),
+    _minindex (0)
+{
+}
+
+/* Initializes an iterator through POSITIONS, ignoring positions >= maxlen.  */
+INLINE
+PositionReverseIterator::PositionReverseIterator (Positions const& positions, int maxlen)
+  : _set (positions),
+    _index (_set._size)
+{
+  if (positions._useall)
+    _minindex = (maxlen <= Positions::MAX_KEY_POS ? Positions::MAX_KEY_POS - maxlen : 0);
+  else
+    {
+      unsigned int index;
+      for (index = 0;
+           index < positions._size && positions._positions[index] >= maxlen;
+           index++)
+        ;
+      _minindex = index;
+    }
+}
+
+/* Retrieves the next position, or EOS past the end.  */
+INLINE int
+PositionReverseIterator::next ()
+{
+  return (_index > _minindex ? _set._positions[--_index] : EOS);
+}
+
+/* Returns the number of remaining positions, i.e. how often next() will
+   return a value != EOS.  */
+INLINE unsigned int
+PositionReverseIterator::remaining () const
+{
+  return _index - _minindex;
+}
+
+/* Copy constructor.  */
+INLINE
+PositionReverseIterator::PositionReverseIterator (const PositionReverseIterator& src)
+  : _set (src._set),
+    _index (src._index),
+    _minindex (src._minindex)
+{
+}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/src/read-line.cc
--- a/head/contrib/gperf/src/read-line.cc	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,97 +0,0 @@
-/* Correctly reads an arbitrarily size string.
-
-   Copyright (C) 1989-1998 Free Software Foundation, Inc.
-   written by Douglas C. Schmidt (schmidt at ics.uci.edu)
-
-This file is part of GNU GPERF.
-
-GNU GPERF 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 1, or (at your option)
-any later version.
-
-GNU GPERF 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 GPERF; see the file COPYING.  If not, write to the Free
-Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111, USA.  */
-
-#include "read-line.h"
-
-#include <stdlib.h>
-#include <string.h> /* declares memcpy() */
-#include "options.h"
-#include "trace.h"
-
-/* Recursively fills up the buffer. */
-
-#define CHUNK_SIZE 4096
-
-/* CHUNKS is the number of chunks (each of size CHUNK_SIZE) which have
-   already been read and which are temporarily stored on the stack.
-   This function reads the remainder of the line, allocates a buffer
-   for the entire line, fills the part beyond &buffer[chunks*CHUNK_SIZE],
-   and returns &buffer[chunks*CHUNK_SIZE].  */
-
-char *
-Read_Line::readln_aux (int chunks)
-{
-  T (Trace t ("Read_Line::readln_aux");)
-#if LARGE_STACK
-  char buf[CHUNK_SIZE];
-#else
-  // Note: we don't use new, because that invokes a custom operator new.
-  char *buf = (char*)malloc(CHUNK_SIZE);
-  if (buf == NULL)
-    abort ();
-#endif
-  char *bufptr = buf;
-  char *ptr;
-  int c;
-
-  while (c = getc (fp), c != EOF && c != '\n') /* fill the current buffer */
-    {
-      *bufptr++ = c;
-      if (bufptr - buf == CHUNK_SIZE)
-        {
-          if ((ptr = readln_aux (chunks + 1)) != NULL)
-
-            /* prepend remainder to ptr buffer */
-            {
-              ptr -= CHUNK_SIZE;
-              memcpy (ptr, buf, CHUNK_SIZE);
-            }
-
-          goto done;
-        }
-    }
-  if (c == EOF && bufptr == buf && chunks == 0)
-    ptr = NULL;
-  else
-    {
-      size_t s1 = chunks * CHUNK_SIZE;
-      size_t s2 = bufptr - buf;
-
-      ptr = new char[s1+s2+1];
-      ptr += s1;
-      ptr[s2] = '\0';
-      memcpy (ptr, buf, s2);
-    }
- done:
-#if !LARGE_STACK
-  free (buf);
-#endif
-
-  return ptr;
-}
-
-#ifndef __OPTIMIZE__
-
-#define INLINE /* not inline */
-#include "read-line.icc"
-#undef INLINE
-
-#endif /* not defined __OPTIMIZE__ */
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/src/read-line.h
--- a/head/contrib/gperf/src/read-line.h	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,53 +0,0 @@
-/* This may look like C code, but it is really -*- C++ -*- */
-
-/* Reads arbitrarily long string from input file, returning it as a
-   dynamically allocated buffer.
-
-   Copyright (C) 1989-1998 Free Software Foundation, Inc.
-   written by Douglas C. Schmidt (schmidt at ics.uci.edu)
-
-This file is part of GNU GPERF.
-
-GNU GPERF 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 1, or (at your option)
-any later version.
-
-GNU GPERF 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 GPERF; see the file COPYING.  If not, write to the Free
-Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111, USA.  */
-
-/* Returns a pointer to an arbitrary length string.  Returns NULL on error or EOF
-   The storage for the string is dynamically allocated by new. */
-
-#ifndef read_line_h
-#define read_line_h 1
-
-#include <stdio.h>
-
-class Read_Line
-{
-private:
-  char *readln_aux (int chunks);
-  FILE *fp;                       /* FILE pointer to the input stream. */
-
-public:
-        Read_Line (FILE *stream = stdin) : fp (stream) {}
-  char *get_line (void);
-};
-
-#ifdef __OPTIMIZE__
-
-#include "trace.h"
-#define INLINE inline
-#include "read-line.icc"
-#undef INLINE
-
-#endif
-
-#endif
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/src/read-line.icc
--- a/head/contrib/gperf/src/read-line.icc	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,47 +0,0 @@
-/* Inline Functions for read-line.{h,cc}.
-
-   Copyright (C) 1989-1998 Free Software Foundation, Inc.
-   written by Douglas C. Schmidt (schmidt at ics.uci.edu)
-
-This file is part of GNU GPERF.
-
-GNU GPERF 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 1, or (at your option)
-any later version.
-
-GNU GPERF 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 GPERF; see the file COPYING.  If not, write to the Free
-Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111, USA.  */
-
-// This needs:
-//#include <stdio.h>
-//#include "trace.h"
-
-/* Returns the ``next'' line, ignoring comments beginning with '#'. */
-INLINE char *
-Read_Line::get_line (void)
-{
-  T (Trace t ("Read_Line::get_line");)
-  int c;
-
-  while ((c = getc (fp)) == '#')
-    {
-      while (c = getc (fp), c != EOF && c != '\n')
-        ;
-
-      if (c == EOF)
-        return (char *)0;
-    }
-
-  if (c == EOF)
-    return (char *)0;
-
-  ungetc (c, stdin);
-  return readln_aux (0);
-}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/src/search.cc
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/contrib/gperf/src/search.cc	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,1684 @@
+/* Search algorithm.
+   Copyright (C) 1989-1998, 2000, 2002 Free Software Foundation, Inc.
+   Written by Douglas C. Schmidt <schmidt at ics.uci.edu>
+   and Bruno Haible <bruno at clisp.org>.
+
+   This file is part of GNU GPERF.
+
+   GNU GPERF 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 GPERF 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; see the file COPYING.
+   If not, write to the Free Software Foundation, Inc.,
+   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
+
+/* Specification. */
+#include "search.h"
+
+#include <stdio.h>
+#include <stdlib.h> /* declares exit(), rand(), srand() */
+#include <string.h> /* declares memset(), memcmp() */
+#include <time.h> /* declares time() */
+#include <math.h> /* declares exp() */
+#include <limits.h> /* defines INT_MIN, INT_MAX, UINT_MAX */
+#include "options.h"
+#include "hash-table.h"
+#include "config.h"
+
+/* ============================== Portability ============================== */
+
+/* Assume ISO C++ 'for' scoping rule.  */
+#define for if (0) ; else for
+
+/* Dynamically allocated array with dynamic extent:
+
+   Example:
+       DYNAMIC_ARRAY (my_array, int, n);
+       ...
+       FREE_DYNAMIC_ARRAY (my_array);
+
+   Attention: depending on your implementation my_array is either the array
+   itself or a pointer to the array! Always use my_array only as expression!
+ */
+#if HAVE_DYNAMIC_ARRAY
+  #define DYNAMIC_ARRAY(var,eltype,size) eltype var[size]
+  #define FREE_DYNAMIC_ARRAY(var)
+#else
+  #define DYNAMIC_ARRAY(var,eltype,size) eltype *var = new eltype[size]
+  #define FREE_DYNAMIC_ARRAY(var) delete[] var
+#endif
+
+/* ================================ Theory ================================= */
+
+/* The general form of the hash function is
+
+      hash (keyword) = sum (asso_values[keyword[i] + alpha_inc[i]] : i in Pos)
+                       + len (keyword)
+
+   where Pos is a set of byte positions,
+   each alpha_inc[i] is a nonnegative integer,
+   each asso_values[c] is a nonnegative integer,
+   len (keyword) is the keyword's length if !option[NOLENGTH], or 0 otherwise.
+
+   Theorem 1: If all keywords are different, there is a set Pos such that
+   all tuples (keyword[i] : i in Pos) are different.
+
+   Theorem 2: If all tuples (keyword[i] : i in Pos) are different, there
+   are nonnegative integers alpha_inc[i] such that all multisets
+   {keyword[i] + alpha_inc[i] : i in Pos} are different.
+
+   Define selchars[keyword] := {keyword[i] + alpha_inc[i] : i in Pos}.
+
+   Theorem 3: If all multisets selchars[keyword] are different, there are
+   nonnegative integers asso_values[c] such that all hash values
+   sum (asso_values[c] : c in selchars[keyword]) are different.
+
+   Based on these three facts, we find the hash function in three steps:
+
+   Step 1 (Finding good byte positions):
+   Find a set Pos, as small as possible, such that all tuples
+   (keyword[i] : i in Pos) are different.
+
+   Step 2 (Finding good alpha increments):
+   Find nonnegative integers alpha_inc[i], as many of them as possible being
+   zero, and the others being as small as possible, such that all multisets
+   {keyword[i] + alpha_inc[i] : i in Pos} are different.
+
+   Step 3 (Finding good asso_values):
+   Find asso_values[c] such that all hash (keyword) are different.
+
+   In other words, each step finds a projection that is injective on the
+   given finite set:
+     proj1 : String --> Map (Pos --> N)
+     proj2 : Map (Pos --> N) --> Map (Pos --> N) / S(Pos)
+     proj3 : Map (Pos --> N) / S(Pos) --> N
+   where
+     N denotes the set of nonnegative integers,
+     Map (A --> B) := Hom_Set (A, B) is the set of maps from A to B, and
+     S(Pos) is the symmetric group over Pos.
+
+   This was the theory for option[NOLENGTH]; if !option[NOLENGTH], slight
+   modifications apply:
+     proj1 : String --> Map (Pos --> N) x N
+     proj2 : Map (Pos --> N) x N --> Map (Pos --> N) / S(Pos) x N
+     proj3 : Map (Pos --> N) / S(Pos) x N --> N
+
+   For a case-insensitive hash function, the general form is
+
+      hash (keyword) =
+        sum (asso_values[alpha_unify[keyword[i] + alpha_inc[i]]] : i in Pos)
+        + len (keyword)
+
+   where alpha_unify[c] is chosen so that an upper/lower case change in
+   keyword[i] doesn't change  alpha_unify[keyword[i] + alpha_inc[i]].
+ */
+
+/* ==================== Initialization and Preparation ===================== */
+
+Search::Search (KeywordExt_List *list)
+  : _head (list)
+{
+}
+
+void
+Search::prepare ()
+{
+  /* Compute the total number of keywords.  */
+  _total_keys = 0;
+  for (KeywordExt_List *temp = _head; temp; temp = temp->rest())
+    _total_keys++;
+
+  /* Compute the minimum and maximum keyword length.  */
+  _max_key_len = INT_MIN;
+  _min_key_len = INT_MAX;
+  for (KeywordExt_List *temp = _head; temp; temp = temp->rest())
+    {
+      KeywordExt *keyword = temp->first();
+
+      if (_max_key_len < keyword->_allchars_length)
+        _max_key_len = keyword->_allchars_length;
+      if (_min_key_len > keyword->_allchars_length)
+        _min_key_len = keyword->_allchars_length;
+    }
+
+  /* Exit program if an empty string is used as keyword, since the comparison
+     expressions don't work correctly for looking up an empty string.  */
+  if (_min_key_len == 0)
+    {
+      fprintf (stderr, "Empty input keyword is not allowed.\n"
+               "To recognize an empty input keyword, your code should check for\n"
+               "len == 0 before calling the gperf generated lookup function.\n");
+      exit (1);
+    }
+
+  /* Exit program if the characters in the keywords are not in the required
+     range.  */
+  if (option[SEVENBIT])
+    for (KeywordExt_List *temp = _head; temp; temp = temp->rest())
+      {
+        KeywordExt *keyword = temp->first();
+
+        const char *k = keyword->_allchars;
+        for (int i = keyword->_allchars_length; i > 0; k++, i--)
+          if (!(static_cast<unsigned char>(*k) < 128))
+            {
+              fprintf (stderr, "Option --seven-bit has been specified,\n"
+                       "but keyword \"%.*s\" contains non-ASCII characters.\n"
+                       "Try removing option --seven-bit.\n",
+                       keyword->_allchars_length, keyword->_allchars);
+              exit (1);
+            }
+      }
+}
+
+/* ====================== Finding good byte positions ====================== */
+
+/* Computes the upper bound on the indices passed to asso_values[],
+   assuming no alpha_increments.  */
+unsigned int
+Search::compute_alpha_size () const
+{
+  return (option[SEVENBIT] ? 128 : 256);
+}
+
+/* Computes the unification rules between different asso_values[c],
+   assuming no alpha_increments.  */
+unsigned int *
+Search::compute_alpha_unify () const
+{
+  if (option[UPPERLOWER])
+    {
+      /* Uppercase to lowercase mapping.  */
+      unsigned int alpha_size = compute_alpha_size();
+      unsigned int *alpha_unify = new unsigned int[alpha_size];
+      for (unsigned int c = 0; c < alpha_size; c++)
+        alpha_unify[c] = c;
+      for (unsigned int c = 'A'; c <= 'Z'; c++)
+        alpha_unify[c] = c + ('a'-'A');
+      return alpha_unify;
+    }
+  else
+    /* Identity mapping.  */
+    return NULL;
+}
+
+/* Initializes each keyword's _selchars array.  */
+void
+Search::init_selchars_tuple (const Positions& positions, const unsigned int *alpha_unify) const
+{
+  for (KeywordExt_List *temp = _head; temp; temp = temp->rest())
+    temp->first()->init_selchars_tuple(positions, alpha_unify);
+}
+
+/* Deletes each keyword's _selchars array.  */
+void
+Search::delete_selchars () const
+{
+  for (KeywordExt_List *temp = _head; temp; temp = temp->rest())
+    temp->first()->delete_selchars();
+}
+
+/* Count the duplicate keywords that occur with a given set of positions.
+   In other words, it returns the difference
+     # K - # proj1 (K)
+   where K is the multiset of given keywords.  */
+unsigned int
+Search::count_duplicates_tuple (const Positions& positions, const unsigned int *alpha_unify) const
+{
+  /* Run through the keyword list and count the duplicates incrementally.
+     The result does not depend on the order of the keyword list, thanks to
+     the formula above.  */
+  init_selchars_tuple (positions, alpha_unify);
+
+  unsigned int count = 0;
+  {
+    Hash_Table representatives (_total_keys, option[NOLENGTH]);
+    for (KeywordExt_List *temp = _head; temp; temp = temp->rest())
+      {
+        KeywordExt *keyword = temp->first();
+        if (representatives.insert (keyword))
+          count++;
+      }
+  }
+
+  delete_selchars ();
+
+  return count;
+}
+
+/* Find good key positions.  */
+
+void
+Search::find_positions ()
+{
+  /* If the user gave the key positions, we use them.  */
+  if (option[POSITIONS])
+    {
+      _key_positions = option.get_key_positions();
+      return;
+    }
+
+  /* Compute preliminary alpha_unify table.  */
+  unsigned int *alpha_unify = compute_alpha_unify ();
+
+  /* 1. Find positions that must occur in order to distinguish duplicates.  */
+  Positions mandatory;
+
+  if (!option[DUP])
+    {
+      for (KeywordExt_List *l1 = _head; l1 && l1->rest(); l1 = l1->rest())
+        {
+          KeywordExt *keyword1 = l1->first();
+          for (KeywordExt_List *l2 = l1->rest(); l2; l2 = l2->rest())
+            {
+              KeywordExt *keyword2 = l2->first();
+
+              /* If keyword1 and keyword2 have the same length and differ
+                 in just one position, and it is not the last character,
+                 this position is mandatory.  */
+              if (keyword1->_allchars_length == keyword2->_allchars_length)
+                {
+                  int n = keyword1->_allchars_length;
+                  int i;
+                  for (i = 0; i < n - 1; i++)
+                    {
+                      unsigned char c1 = keyword1->_allchars[i];
+                      unsigned char c2 = keyword2->_allchars[i];
+                      if (option[UPPERLOWER])
+                        {
+                          if (c1 >= 'A' && c1 <= 'Z')
+                            c1 += 'a' - 'A';
+                          if (c2 >= 'A' && c2 <= 'Z')
+                            c2 += 'a' - 'A';
+                        }
+                      if (c1 != c2)
+                        break;
+                    }
+                  if (i < n - 1)
+                    {
+                      int j;
+                      for (j = i + 1; j < n; j++)
+                        {
+                          unsigned char c1 = keyword1->_allchars[j];
+                          unsigned char c2 = keyword2->_allchars[j];
+                          if (option[UPPERLOWER])
+                            {
+                              if (c1 >= 'A' && c1 <= 'Z')
+                                c1 += 'a' - 'A';
+                              if (c2 >= 'A' && c2 <= 'Z')
+                                c2 += 'a' - 'A';
+                            }
+                          if (c1 != c2)
+                            break;
+                        }
+                      if (j >= n)
+                        {
+                          /* Position i is mandatory.  */
+                          if (!mandatory.contains (i))
+                            mandatory.add (i);
+                        }
+                    }
+                }
+            }
+        }
+    }
+
+  /* 2. Add positions, as long as this decreases the duplicates count.  */
+  int imax = (_max_key_len - 1 < Positions::MAX_KEY_POS - 1
+              ? _max_key_len - 1 : Positions::MAX_KEY_POS - 1);
+  Positions current = mandatory;
+  unsigned int current_duplicates_count =
+    count_duplicates_tuple (current, alpha_unify);
+  for (;;)
+    {
+      Positions best;
+      unsigned int best_duplicates_count = UINT_MAX;
+
+      for (int i = imax; i >= -1; i--)
+        if (!current.contains (i))
+          {
+            Positions tryal = current;
+            tryal.add (i);
+            unsigned int try_duplicates_count =
+              count_duplicates_tuple (tryal, alpha_unify);
+
+            /* We prefer 'try' to 'best' if it produces less duplicates,
+               or if it produces the same number of duplicates but with
+               a more efficient hash function.  */
+            if (try_duplicates_count < best_duplicates_count
+                || (try_duplicates_count == best_duplicates_count && i >= 0))
+              {
+                best = tryal;
+                best_duplicates_count = try_duplicates_count;
+              }
+          }
+
+      /* Stop adding positions when it gives no improvement.  */
+      if (best_duplicates_count >= current_duplicates_count)
+        break;
+
+      current = best;
+      current_duplicates_count = best_duplicates_count;
+    }
+
+  /* 3. Remove positions, as long as this doesn't increase the duplicates
+     count.  */
+  for (;;)
+    {
+      Positions best;
+      unsigned int best_duplicates_count = UINT_MAX;
+
+      for (int i = imax; i >= -1; i--)
+        if (current.contains (i) && !mandatory.contains (i))
+          {
+            Positions tryal = current;
+            tryal.remove (i);
+            unsigned int try_duplicates_count =
+              count_duplicates_tuple (tryal, alpha_unify);
+
+            /* We prefer 'try' to 'best' if it produces less duplicates,
+               or if it produces the same number of duplicates but with
+               a more efficient hash function.  */
+            if (try_duplicates_count < best_duplicates_count
+                || (try_duplicates_count == best_duplicates_count && i == -1))
+              {
+                best = tryal;
+                best_duplicates_count = try_duplicates_count;
+              }
+          }
+
+      /* Stop removing positions when it gives no improvement.  */
+      if (best_duplicates_count > current_duplicates_count)
+        break;
+
+      current = best;
+      current_duplicates_count = best_duplicates_count;
+    }
+
+  /* 4. Replace two positions by one, as long as this doesn't increase the
+     duplicates count.  */
+  for (;;)
+    {
+      Positions best;
+      unsigned int best_duplicates_count = UINT_MAX;
+
+      for (int i1 = imax; i1 >= -1; i1--)
+        if (current.contains (i1) && !mandatory.contains (i1))
+          for (int i2 = imax; i2 >= -1; i2--)
+            if (current.contains (i2) && !mandatory.contains (i2) && i2 != i1)
+              for (int i3 = imax; i3 >= 0; i3--)
+                if (!current.contains (i3))
+                  {
+                    Positions tryal = current;
+                    tryal.remove (i1);
+                    tryal.remove (i2);
+                    tryal.add (i3);
+                    unsigned int try_duplicates_count =
+                      count_duplicates_tuple (tryal, alpha_unify);
+
+                    /* We prefer 'try' to 'best' if it produces less duplicates,
+                       or if it produces the same number of duplicates but with
+                       a more efficient hash function.  */
+                    if (try_duplicates_count < best_duplicates_count
+                        || (try_duplicates_count == best_duplicates_count
+                            && (i1 == -1 || i2 == -1 || i3 >= 0)))
+                      {
+                        best = tryal;
+                        best_duplicates_count = try_duplicates_count;
+                      }
+                  }
+
+      /* Stop removing positions when it gives no improvement.  */
+      if (best_duplicates_count > current_duplicates_count)
+        break;
+
+      current = best;
+      current_duplicates_count = best_duplicates_count;
+    }
+
+  /* That's it.  Hope it's good enough.  */
+  _key_positions = current;
+
+  if (option[DEBUG])
+    {
+      /* Print the result.  */
+      fprintf (stderr, "\nComputed positions: ");
+      PositionReverseIterator iter = _key_positions.reviterator();
+      bool seen_lastchar = false;
+      bool first = true;
+      for (int i; (i = iter.next ()) != PositionReverseIterator::EOS; )
+        {
+          if (!first)
+            fprintf (stderr, ", ");
+          if (i == Positions::LASTCHAR)
+            seen_lastchar = true;
+          else
+            {
+              fprintf (stderr, "%d", i + 1);
+              first = false;
+            }
+        }
+      if (seen_lastchar)
+        {
+          if (!first)
+            fprintf (stderr, ", ");
+          fprintf (stderr, "$");
+        }
+      fprintf (stderr, "\n");
+    }
+
+  /* Free preliminary alpha_unify table.  */
+  delete[] alpha_unify;
+}
+
+/* Count the duplicate keywords that occur with the found set of positions.
+   In other words, it returns the difference
+     # K - # proj1 (K)
+   where K is the multiset of given keywords.  */
+unsigned int
+Search::count_duplicates_tuple () const
+{
+  unsigned int *alpha_unify = compute_alpha_unify ();
+  unsigned int count = count_duplicates_tuple (_key_positions, alpha_unify);
+  delete[] alpha_unify;
+  return count;
+}
+
+/* ===================== Finding good alpha increments ===================== */
+
+/* Computes the upper bound on the indices passed to asso_values[].  */
+unsigned int
+Search::compute_alpha_size (const unsigned int *alpha_inc) const
+{
+  unsigned int max_alpha_inc = 0;
+  for (int i = 0; i < _max_key_len; i++)
+    if (max_alpha_inc < alpha_inc[i])
+      max_alpha_inc = alpha_inc[i];
+  return (option[SEVENBIT] ? 128 : 256) + max_alpha_inc;
+}
+
+/* Computes the unification rules between different asso_values[c].  */
+unsigned int *
+Search::compute_alpha_unify (const Positions& positions, const unsigned int *alpha_inc) const
+{
+  if (option[UPPERLOWER])
+    {
+      /* Without alpha increments, we would simply unify
+           'A' -> 'a', ..., 'Z' -> 'z'.
+         But when a keyword contains at position i a character c,
+         we have the constraint
+            asso_values[tolower(c) + alpha_inc[i]] ==
+            asso_values[toupper(c) + alpha_inc[i]].
+         This introduces a unification
+           toupper(c) + alpha_inc[i] -> tolower(c) + alpha_inc[i].
+         Note that this unification can extend outside the range of
+         ASCII letters!  But still every unified character pair is at
+         a distance of 'a'-'A' = 32, or (after chained unification)
+         at a multiple of 32.  So in the end the alpha_unify vector has
+         the form    c -> c + 32 * f(c)   where f(c) is a nonnegative
+         integer.  */
+      unsigned int alpha_size = compute_alpha_size (alpha_inc);
+
+      unsigned int *alpha_unify = new unsigned int[alpha_size];
+      for (unsigned int c = 0; c < alpha_size; c++)
+        alpha_unify[c] = c;
+
+      for (KeywordExt_List *temp = _head; temp; temp = temp->rest())
+        {
+          KeywordExt *keyword = temp->first();
+
+          /* Iterate through the selected character positions.  */
+          PositionIterator iter = positions.iterator(keyword->_allchars_length);
+
+          for (int i; (i = iter.next ()) != PositionIterator::EOS; )
+            {
+              unsigned int c;
+              if (i == Positions::LASTCHAR)
+                c = static_cast<unsigned char>(keyword->_allchars[keyword->_allchars_length - 1]);
+              else if (i < keyword->_allchars_length)
+                c = static_cast<unsigned char>(keyword->_allchars[i]);
+              else
+                abort ();
+              if (c >= 'A' && c <= 'Z')
+                c += 'a' - 'A';
+              if (c >= 'a' && c <= 'z')
+                {
+                  if (i != Positions::LASTCHAR)
+                    c += alpha_inc[i];
+                  /* Unify c with c - ('a'-'A').  */
+                  unsigned int d = alpha_unify[c];
+                  unsigned int b = c - ('a'-'A');
+                  for (int a = b; a >= 0 && alpha_unify[a] == b; a -= ('a'-'A'))
+                    alpha_unify[a] = d;
+                }
+            }
+        }
+      return alpha_unify;
+    }
+  else
+    /* Identity mapping.  */
+    return NULL;
+}
+
+/* Initializes each keyword's _selchars array.  */
+void
+Search::init_selchars_multiset (const Positions& positions, const unsigned int *alpha_unify, const unsigned int *alpha_inc) const
+{
+  for (KeywordExt_List *temp = _head; temp; temp = temp->rest())
+    temp->first()->init_selchars_multiset(positions, alpha_unify, alpha_inc);
+}
+
+/* Count the duplicate keywords that occur with the given set of positions
+   and a given alpha_inc[] array.
+   In other words, it returns the difference
+     # K - # proj2 (proj1 (K))
+   where K is the multiset of given keywords.  */
+unsigned int
+Search::count_duplicates_multiset (const unsigned int *alpha_inc) const
+{
+  /* Run through the keyword list and count the duplicates incrementally.
+     The result does not depend on the order of the keyword list, thanks to
+     the formula above.  */
+  unsigned int *alpha_unify = compute_alpha_unify (_key_positions, alpha_inc);
+  init_selchars_multiset (_key_positions, alpha_unify, alpha_inc);
+
+  unsigned int count = 0;
+  {
+    Hash_Table representatives (_total_keys, option[NOLENGTH]);
+    for (KeywordExt_List *temp = _head; temp; temp = temp->rest())
+      {
+        KeywordExt *keyword = temp->first();
+        if (representatives.insert (keyword))
+          count++;
+      }
+  }
+
+  delete_selchars ();
+  delete[] alpha_unify;
+
+  return count;
+}
+
+/* Find good _alpha_inc[].  */
+
+void
+Search::find_alpha_inc ()
+{
+  /* The goal is to choose _alpha_inc[] such that it doesn't introduce
+     artificial duplicates.
+     In other words, the goal is  # proj2 (proj1 (K)) = # proj1 (K).  */
+  unsigned int duplicates_goal = count_duplicates_tuple ();
+
+  /* Start with zero increments.  This is sufficient in most cases.  */
+  unsigned int *current = new unsigned int [_max_key_len];
+  for (int i = 0; i < _max_key_len; i++)
+    current[i] = 0;
+  unsigned int current_duplicates_count = count_duplicates_multiset (current);
+
+  if (current_duplicates_count > duplicates_goal)
+    {
+      /* Look which _alpha_inc[i] we are free to increment.  */
+      unsigned int nindices;
+      {
+        nindices = 0;
+        PositionIterator iter = _key_positions.iterator(_max_key_len);
+        for (;;)
+          {
+            int key_pos = iter.next ();
+            if (key_pos == PositionIterator::EOS)
+              break;
+            if (key_pos != Positions::LASTCHAR)
+              nindices++;
+          }
+      }
+
+      DYNAMIC_ARRAY (indices, unsigned int, nindices);
+      {
+        unsigned int j = 0;
+        PositionIterator iter = _key_positions.iterator(_max_key_len);
+        for (;;)
+          {
+            int key_pos = iter.next ();
+            if (key_pos == PositionIterator::EOS)
+              break;
+            if (key_pos != Positions::LASTCHAR)
+              indices[j++] = key_pos;
+          }
+        if (!(j == nindices))
+          abort ();
+      }
+
+      /* Perform several rounds of searching for a good alpha increment.
+         Each round reduces the number of artificial collisions by adding
+         an increment in a single key position.  */
+      DYNAMIC_ARRAY (best, unsigned int, _max_key_len);
+      DYNAMIC_ARRAY (tryal, unsigned int, _max_key_len);
+      do
+        {
+          /* An increment of 1 is not always enough.  Try higher increments
+             also.  */
+          for (unsigned int inc = 1; ; inc++)
+            {
+              unsigned int best_duplicates_count = UINT_MAX;
+
+              for (unsigned int j = 0; j < nindices; j++)
+                {
+                  memcpy (tryal, current, _max_key_len * sizeof (unsigned int));
+                  tryal[indices[j]] += inc;
+                  unsigned int try_duplicates_count =
+                    count_duplicates_multiset (tryal);
+
+                  /* We prefer 'try' to 'best' if it produces less
+                     duplicates.  */
+                  if (try_duplicates_count < best_duplicates_count)
+                    {
+                      memcpy (best, tryal, _max_key_len * sizeof (unsigned int));
+                      best_duplicates_count = try_duplicates_count;
+                    }
+                }
+
+              /* Stop this round when we got an improvement.  */
+              if (best_duplicates_count < current_duplicates_count)
+                {
+                  memcpy (current, best, _max_key_len * sizeof (unsigned int));
+                  current_duplicates_count = best_duplicates_count;
+                  break;
+                }
+            }
+        }
+      while (current_duplicates_count > duplicates_goal);
+      FREE_DYNAMIC_ARRAY (tryal);
+      FREE_DYNAMIC_ARRAY (best);
+
+      if (option[DEBUG])
+        {
+          /* Print the result.  */
+          fprintf (stderr, "\nComputed alpha increments: ");
+          bool first = true;
+          for (unsigned int j = nindices; j-- > 0; )
+            if (current[indices[j]] != 0)
+              {
+                if (!first)
+                  fprintf (stderr, ", ");
+                fprintf (stderr, "%u:+%u",
+                         indices[j] + 1, current[indices[j]]);
+                first = false;
+              }
+          fprintf (stderr, "\n");
+        }
+      FREE_DYNAMIC_ARRAY (indices);
+    }
+
+  _alpha_inc = current;
+  _alpha_size = compute_alpha_size (_alpha_inc);
+  _alpha_unify = compute_alpha_unify (_key_positions, _alpha_inc);
+}
+
+/* ======================= Finding good asso_values ======================== */
+
+/* Initializes the asso_values[] related parameters.  */
+
+void
+Search::prepare_asso_values ()
+{
+  KeywordExt_List *temp;
+
+  /* Initialize each keyword's _selchars array.  */
+  init_selchars_multiset(_key_positions, _alpha_unify, _alpha_inc);
+
+  /* Compute the maximum _selchars_length over all keywords.  */
+  _max_selchars_length = _key_positions.iterator(_max_key_len).remaining();
+
+  /* Check for duplicates, i.e. keywords with the same _selchars array
+     (and - if !option[NOLENGTH] - also the same length).
+     We deal with these by building an equivalence class, so that only
+     1 keyword is representative of the entire collection.  Only this
+     representative remains in the keyword list; the others are accessible
+     through the _duplicate_link chain, starting at the representative.
+     This *greatly* simplifies processing during later stages of the program.
+     Set _total_duplicates and _list_len = _total_keys - _total_duplicates.  */
+  {
+    _list_len = _total_keys;
+    _total_duplicates = 0;
+    /* Make hash table for efficiency.  */
+    Hash_Table representatives (_list_len, option[NOLENGTH]);
+
+    KeywordExt_List *prev = NULL; /* list node before temp */
+    for (temp = _head; temp; )
+      {
+        KeywordExt *keyword = temp->first();
+        KeywordExt *other_keyword = representatives.insert (keyword);
+        KeywordExt_List *garbage = NULL;
+
+        if (other_keyword)
+          {
+            _total_duplicates++;
+            _list_len--;
+            /* Remove keyword from the main list.  */
+            prev->rest() = temp->rest();
+            garbage = temp;
+            /* And insert it on other_keyword's duplicate list.  */
+            keyword->_duplicate_link = other_keyword->_duplicate_link;
+            other_keyword->_duplicate_link = keyword;
+
+            /* Complain if user hasn't enabled the duplicate option. */
+            if (!option[DUP] || option[DEBUG])
+              {
+                fprintf (stderr, "Key link: \"%.*s\" = \"%.*s\", with key set \"",
+                         keyword->_allchars_length, keyword->_allchars,
+                         other_keyword->_allchars_length, other_keyword->_allchars);
+                for (int j = 0; j < keyword->_selchars_length; j++)
+                  putc (keyword->_selchars[j], stderr);
+                fprintf (stderr, "\".\n");
+              }
+          }
+        else
+          {
+            keyword->_duplicate_link = NULL;
+            prev = temp;
+          }
+        temp = temp->rest();
+        if (garbage)
+          delete garbage;
+      }
+    if (option[DEBUG])
+      representatives.dump();
+  }
+
+  /* Exit program if duplicates exists and option[DUP] not set, since we
+     don't want to continue in this case.  (We don't want to turn on
+     option[DUP] implicitly, because the generated code is usually much
+     slower.  */
+  if (_total_duplicates)
+    {
+      if (option[DUP])
+        fprintf (stderr, "%d input keys have identical hash values, examine output carefully...\n",
+                         _total_duplicates);
+      else
+        {
+          fprintf (stderr, "%d input keys have identical hash values,\n",
+                           _total_duplicates);
+          if (option[POSITIONS])
+            fprintf (stderr, "try different key positions or use option -D.\n");
+          else
+            fprintf (stderr, "use option -D.\n");
+          exit (1);
+        }
+    }
+
+  /* Compute the occurrences of each character in the alphabet.  */
+  _occurrences = new int[_alpha_size];
+  memset (_occurrences, 0, _alpha_size * sizeof (_occurrences[0]));
+  for (temp = _head; temp; temp = temp->rest())
+    {
+      KeywordExt *keyword = temp->first();
+      const unsigned int *ptr = keyword->_selchars;
+      for (int count = keyword->_selchars_length; count > 0; ptr++, count--)
+        _occurrences[*ptr]++;
+    }
+
+  /* Memory allocation.  */
+  _asso_values = new int[_alpha_size];
+
+  int non_linked_length = _list_len;
+  unsigned int asso_value_max;
+
+  asso_value_max =
+    static_cast<unsigned int>(non_linked_length * option.get_size_multiple());
+  /* Round up to the next power of two.  This makes it easy to ensure
+     an _asso_value[c] is >= 0 and < asso_value_max.  Also, the jump value
+     being odd, it guarantees that Search::try_asso_value() will iterate
+     through different values for _asso_value[c].  */
+  if (asso_value_max == 0)
+    asso_value_max = 1;
+  asso_value_max |= asso_value_max >> 1;
+  asso_value_max |= asso_value_max >> 2;
+  asso_value_max |= asso_value_max >> 4;
+  asso_value_max |= asso_value_max >> 8;
+  asso_value_max |= asso_value_max >> 16;
+  asso_value_max++;
+  _asso_value_max = asso_value_max;
+
+  /* Given the bound for _asso_values[c], we have a bound for the possible
+     hash values, as computed in compute_hash().  */
+  _max_hash_value = (option[NOLENGTH] ? 0 : _max_key_len)
+                    + (_asso_value_max - 1) * _max_selchars_length;
+  /* Allocate a sparse bit vector for detection of collisions of hash
+     values.  */
+  _collision_detector = new Bool_Array (_max_hash_value + 1);
+
+  if (option[DEBUG])
+    {
+      fprintf (stderr, "total non-linked keys = %d\nmaximum associated value is %d"
+               "\nmaximum size of generated hash table is %d\n",
+               non_linked_length, asso_value_max, _max_hash_value);
+
+      int field_width;
+
+      field_width = 0;
+      {
+        for (KeywordExt_List *temp = _head; temp; temp = temp->rest())
+          {
+            KeywordExt *keyword = temp->first();
+            if (field_width < keyword->_selchars_length)
+              field_width = keyword->_selchars_length;
+          }
+      }
+
+      fprintf (stderr, "\ndumping the keyword list without duplicates\n");
+      fprintf (stderr, "keyword #, %*s, keyword\n", field_width, "keysig");
+      int i = 0;
+      for (KeywordExt_List *temp = _head; temp; temp = temp->rest())
+        {
+          KeywordExt *keyword = temp->first();
+          fprintf (stderr, "%9d, ", ++i);
+          if (field_width > keyword->_selchars_length)
+            fprintf (stderr, "%*s", field_width - keyword->_selchars_length, "");
+          for (int j = 0; j < keyword->_selchars_length; j++)
+            putc (keyword->_selchars[j], stderr);
+          fprintf (stderr, ", %.*s\n",
+                   keyword->_allchars_length, keyword->_allchars);
+        }
+      fprintf (stderr, "\nend of keyword list\n\n");
+    }
+
+  if (option[RANDOM] || option.get_jump () == 0)
+    /* We will use rand(), so initialize the random number generator.  */
+    srand (static_cast<long>(time (0)));
+
+  _initial_asso_value = (option[RANDOM] ? -1 : option.get_initial_asso_value ());
+  _jump = option.get_jump ();
+}
+
+/* Finds some _asso_values[] that fit.  */
+
+/* The idea is to choose the _asso_values[] one by one, in a way that
+   a choice that has been made never needs to be undone later.  This
+   means that we split the work into several steps.  Each step chooses
+   one or more _asso_values[c].  The result of choosing one or more
+   _asso_values[c] is that the partitioning of the keyword set gets
+   broader.
+   Look at this partitioning:  After every step, the _asso_values[] of a
+   certain set C of characters are undetermined.  (At the beginning, C
+   is the set of characters c with _occurrences[c] > 0.  At the end, C
+   is empty.)  To each keyword K, we associate the multiset of _selchars
+   for which the _asso_values[] are undetermined:
+                    K  -->  K->_selchars intersect C.
+   Consider two keywords equivalent if their value under this mapping is
+   the same.  This introduces an equivalence relation on the set of
+   keywords.  The equivalence classes partition the keyword set.  (At the
+   beginning, the partition is the finest possible: each K is an equivalence
+   class by itself, because all K have a different _selchars.  At the end,
+   all K have been merged into a single equivalence class.)
+   The partition before a step is always a refinement of the partition
+   after the step.
+   We choose the steps in such a way that the partition really becomes
+   broader at each step.  (A step that only chooses an _asso_values[c]
+   without changing the partition is better merged with the previous step,
+   to avoid useless backtracking.)  */
+
+struct EquivalenceClass
+{
+  /* The keywords in this equivalence class.  */
+  KeywordExt_List *     _keywords;
+  KeywordExt_List *     _keywords_last;
+  /* The number of keywords in this equivalence class.  */
+  unsigned int          _cardinality;
+  /* The undetermined selected characters for the keywords in this
+     equivalence class, as a canonically reordered multiset.  */
+  unsigned int *        _undetermined_chars;
+  unsigned int          _undetermined_chars_length;
+
+  EquivalenceClass *    _next;
+};
+
+struct Step
+{
+  /* The characters whose values are being determined in this step.  */
+  unsigned int          _changing_count;
+  unsigned int *        _changing;
+  /* Exclusive upper bound for the _asso_values[c] of this step.
+     A power of 2.  */
+  unsigned int          _asso_value_max;
+  /* The characters whose values will be determined after this step.  */
+  bool *                _undetermined;
+  /* The keyword set partition after this step.  */
+  EquivalenceClass *    _partition;
+  /* The expected number of iterations in this step.  */
+  double                _expected_lower;
+  double                _expected_upper;
+
+  Step *                _next;
+};
+
+static inline bool
+equals (const unsigned int *ptr1, const unsigned int *ptr2, unsigned int len)
+{
+  while (len > 0)
+    {
+      if (*ptr1 != *ptr2)
+        return false;
+      ptr1++;
+      ptr2++;
+      len--;
+    }
+  return true;
+}
+
+EquivalenceClass *
+Search::compute_partition (bool *undetermined) const
+{
+  EquivalenceClass *partition = NULL;
+  EquivalenceClass *partition_last = NULL;
+  for (KeywordExt_List *temp = _head; temp; temp = temp->rest())
+    {
+      KeywordExt *keyword = temp->first();
+
+      /* Compute the undetermined characters for this keyword.  */
+      unsigned int *undetermined_chars =
+        new unsigned int[keyword->_selchars_length];
+      unsigned int undetermined_chars_length = 0;
+
+      for (int i = 0; i < keyword->_selchars_length; i++)
+        if (undetermined[keyword->_selchars[i]])
+          undetermined_chars[undetermined_chars_length++] = keyword->_selchars[i];
+
+      /* Look up the equivalence class to which this keyword belongs.  */
+      EquivalenceClass *equclass;
+      for (equclass = partition; equclass; equclass = equclass->_next)
+        if (equclass->_undetermined_chars_length == undetermined_chars_length
+            && equals (equclass->_undetermined_chars, undetermined_chars,
+                       undetermined_chars_length))
+          break;
+      if (equclass == NULL)
+        {
+          equclass = new EquivalenceClass();
+          equclass->_keywords = NULL;
+          equclass->_keywords_last = NULL;
+          equclass->_cardinality = 0;
+          equclass->_undetermined_chars = undetermined_chars;
+          equclass->_undetermined_chars_length = undetermined_chars_length;
+          equclass->_next = NULL;
+          if (partition)
+            partition_last->_next = equclass;
+          else
+            partition = equclass;
+          partition_last = equclass;
+        }
+      else
+        delete[] undetermined_chars;
+
+      /* Add the keyword to the equivalence class.  */
+      KeywordExt_List *cons = new KeywordExt_List(keyword);
+      if (equclass->_keywords)
+        equclass->_keywords_last->rest() = cons;
+      else
+        equclass->_keywords = cons;
+      equclass->_keywords_last = cons;
+      equclass->_cardinality++;
+    }
+
+  /* Free some of the allocated memory.  The caller doesn't need it.  */
+  for (EquivalenceClass *cls = partition; cls; cls = cls->_next)
+    delete[] cls->_undetermined_chars;
+
+  return partition;
+}
+
+static void
+delete_partition (EquivalenceClass *partition)
+{
+  while (partition != NULL)
+    {
+      EquivalenceClass *equclass = partition;
+      partition = equclass->_next;
+      delete_list (equclass->_keywords);
+      //delete[] equclass->_undetermined_chars; // already freed above
+      delete equclass;
+    }
+}
+
+/* Compute the possible number of collisions when _asso_values[c] is
+   chosen, leading to the given partition.  */
+unsigned int
+Search::count_possible_collisions (EquivalenceClass *partition, unsigned int c) const
+{
+  /* Every equivalence class p is split according to the frequency of
+     occurrence of c, leading to equivalence classes p1, p2, ...
+     This leads to   (|p|^2 - |p1|^2 - |p2|^2 - ...)/2  possible collisions.
+     Return the sum of this expression over all equivalence classes.  */
+  unsigned int sum = 0;
+  unsigned int m = _max_selchars_length;
+  DYNAMIC_ARRAY (split_cardinalities, unsigned int, m + 1);
+  for (EquivalenceClass *cls = partition; cls; cls = cls->_next)
+    {
+      for (unsigned int i = 0; i <= m; i++)
+        split_cardinalities[i] = 0;
+
+      for (KeywordExt_List *temp = cls->_keywords; temp; temp = temp->rest())
+        {
+          KeywordExt *keyword = temp->first();
+
+          unsigned int count = 0;
+          for (int i = 0; i < keyword->_selchars_length; i++)
+            if (keyword->_selchars[i] == c)
+              count++;
+
+          split_cardinalities[count]++;
+        }
+
+      sum += cls->_cardinality * cls->_cardinality;
+      for (unsigned int i = 0; i <= m; i++)
+        sum -= split_cardinalities[i] * split_cardinalities[i];
+    }
+  FREE_DYNAMIC_ARRAY (split_cardinalities);
+  return sum;
+}
+
+/* Test whether adding c to the undetermined characters changes the given
+   partition.  */
+bool
+Search::unchanged_partition (EquivalenceClass *partition, unsigned int c) const
+{
+  for (EquivalenceClass *cls = partition; cls; cls = cls->_next)
+    {
+      unsigned int first_count = UINT_MAX;
+
+      for (KeywordExt_List *temp = cls->_keywords; temp; temp = temp->rest())
+        {
+          KeywordExt *keyword = temp->first();
+
+          unsigned int count = 0;
+          for (int i = 0; i < keyword->_selchars_length; i++)
+            if (keyword->_selchars[i] == c)
+              count++;
+
+          if (temp == cls->_keywords)
+            first_count = count;
+          else if (count != first_count)
+            /* c would split this equivalence class.  */
+            return false;
+        }
+    }
+  return true;
+}
+
+void
+Search::find_asso_values ()
+{
+  Step *steps;
+
+  /* Determine the steps, starting with the last one.  */
+  {
+    bool *undetermined;
+    bool *determined;
+
+    steps = NULL;
+
+    undetermined = new bool[_alpha_size];
+    for (unsigned int c = 0; c < _alpha_size; c++)
+      undetermined[c] = false;
+
+    determined = new bool[_alpha_size];
+    for (unsigned int c = 0; c < _alpha_size; c++)
+      determined[c] = true;
+
+    for (;;)
+      {
+        /* Compute the partition that needs to be refined.  */
+        EquivalenceClass *partition = compute_partition (undetermined);
+
+        /* Determine the main character to be chosen in this step.
+           Choosing such a character c has the effect of splitting every
+           equivalence class (according the the frequency of occurrence of c).
+           We choose the c with the minimum number of possible collisions,
+           so that characters which lead to a large number of collisions get
+           handled early during the search.  */
+        unsigned int chosen_c;
+        unsigned int chosen_possible_collisions;
+        {
+          unsigned int best_c = 0;
+          unsigned int best_possible_collisions = UINT_MAX;
+          for (unsigned int c = 0; c < _alpha_size; c++)
+            if (_occurrences[c] > 0 && determined[c])
+              {
+                unsigned int possible_collisions =
+                  count_possible_collisions (partition, c);
+                if (possible_collisions < best_possible_collisions)
+                  {
+                    best_c = c;
+                    best_possible_collisions = possible_collisions;
+                  }
+              }
+          if (best_possible_collisions == UINT_MAX)
+            {
+              /* All c with _occurrences[c] > 0 are undetermined.  We are
+                 are the starting situation and don't need any more step.  */
+              delete_partition (partition);
+              break;
+            }
+          chosen_c = best_c;
+          chosen_possible_collisions = best_possible_collisions;
+        }
+
+        /* We need one more step.  */
+        Step *step = new Step();
+
+        step->_undetermined = new bool[_alpha_size];
+        memcpy (step->_undetermined, undetermined, _alpha_size*sizeof(bool));
+
+        step->_partition = partition;
+
+        /* Now determine how the equivalence classes will be before this
+           step.  */
+        undetermined[chosen_c] = true;
+        partition = compute_partition (undetermined);
+
+        /* Now determine which other characters should be determined in this
+           step, because they will not change the equivalence classes at
+           this point.  It is the set of all c which, for all equivalence
+           classes, have the same frequency of occurrence in every keyword
+           of the equivalence class.  */
+        for (unsigned int c = 0; c < _alpha_size; c++)
+          if (_occurrences[c] > 0 && determined[c]
+              && unchanged_partition (partition, c))
+            {
+              undetermined[c] = true;
+              determined[c] = false;
+            }
+
+        /* main_c must be one of these.  */
+        if (determined[chosen_c])
+          abort ();
+
+        /* Now the set of changing characters of this step.  */
+        unsigned int changing_count;
+
+        changing_count = 0;
+        for (unsigned int c = 0; c < _alpha_size; c++)
+          if (undetermined[c] && !step->_undetermined[c])
+            changing_count++;
+
+        unsigned int *changing = new unsigned int[changing_count];
+        changing_count = 0;
+        for (unsigned int c = 0; c < _alpha_size; c++)
+          if (undetermined[c] && !step->_undetermined[c])
+            changing[changing_count++] = c;
+
+        step->_changing = changing;
+        step->_changing_count = changing_count;
+
+        step->_asso_value_max = _asso_value_max;
+
+        step->_expected_lower =
+          exp (static_cast<double>(chosen_possible_collisions)
+               / static_cast<double>(_max_hash_value));
+        step->_expected_upper =
+          exp (static_cast<double>(chosen_possible_collisions)
+               / static_cast<double>(_asso_value_max));
+
+        delete_partition (partition);
+
+        step->_next = steps;
+        steps = step;
+      }
+
+    delete[] determined;
+    delete[] undetermined;
+  }
+
+  if (option[DEBUG])
+    {
+      unsigned int stepno = 0;
+      for (Step *step = steps; step; step = step->_next)
+        {
+          stepno++;
+          fprintf (stderr, "Step %u chooses _asso_values[", stepno);
+          for (unsigned int i = 0; i < step->_changing_count; i++)
+            {
+              if (i > 0)
+                fprintf (stderr, ",");
+              fprintf (stderr, "'%c'", step->_changing[i]);
+            }
+          fprintf (stderr, "], expected number of iterations between %g and %g.\n",
+                   step->_expected_lower, step->_expected_upper);
+          fprintf (stderr, "Keyword equivalence classes:\n");
+          for (EquivalenceClass *cls = step->_partition; cls; cls = cls->_next)
+            {
+              fprintf (stderr, "\n");
+              for (KeywordExt_List *temp = cls->_keywords; temp; temp = temp->rest())
+                {
+                  KeywordExt *keyword = temp->first();
+                  fprintf (stderr, "  %.*s\n",
+                           keyword->_allchars_length, keyword->_allchars);
+                }
+            }
+          fprintf (stderr, "\n");
+        }
+    }
+
+  /* Initialize _asso_values[].  (The value given here matters only
+     for those c which occur in all keywords with equal multiplicity.)  */
+  for (unsigned int c = 0; c < _alpha_size; c++)
+    _asso_values[c] = 0;
+
+  unsigned int stepno = 0;
+  for (Step *step = steps; step; step = step->_next)
+    {
+      stepno++;
+
+      /* Initialize the asso_values[].  */
+      unsigned int k = step->_changing_count;
+      for (unsigned int i = 0; i < k; i++)
+        {
+          unsigned int c = step->_changing[i];
+          _asso_values[c] =
+            (_initial_asso_value < 0 ? rand () : _initial_asso_value)
+            & (step->_asso_value_max - 1);
+        }
+
+      unsigned int iterations = 0;
+      DYNAMIC_ARRAY (iter, unsigned int, k);
+      for (unsigned int i = 0; i < k; i++)
+        iter[i] = 0;
+      unsigned int ii = (_jump != 0 ? k - 1 : 0);
+
+      for (;;)
+        {
+          /* Test whether these asso_values[] lead to collisions among
+             the equivalence classes that should be collision-free.  */
+          bool has_collision = false;
+          for (EquivalenceClass *cls = step->_partition; cls; cls = cls->_next)
+            {
+              /* Iteration Number array is a win, O(1) initialization time!  */
+              _collision_detector->clear ();
+
+              for (KeywordExt_List *ptr = cls->_keywords; ptr; ptr = ptr->rest())
+                {
+                  KeywordExt *keyword = ptr->first();
+
+                  /* Compute the new hash code for the keyword, leaving apart
+                     the yet undetermined asso_values[].  */
+                  int hashcode;
+                  {
+                    int sum = option[NOLENGTH] ? 0 : keyword->_allchars_length;
+                    const unsigned int *p = keyword->_selchars;
+                    int i = keyword->_selchars_length;
+                    for (; i > 0; p++, i--)
+                      if (!step->_undetermined[*p])
+                        sum += _asso_values[*p];
+                    hashcode = sum;
+                  }
+
+                  /* See whether it collides with another keyword's hash code,
+                     from the same equivalence class.  */
+                  if (_collision_detector->set_bit (hashcode))
+                    {
+                      has_collision = true;
+                      break;
+                    }
+                }
+
+              /* Don't need to continue looking at the other equivalence
+                 classes if we already have found a collision.  */
+              if (has_collision)
+                break;
+            }
+
+          iterations++;
+          if (!has_collision)
+            break;
+
+          /* Try other asso_values[].  */
+          if (_jump != 0)
+            {
+              /* The way we try various values for
+                   asso_values[step->_changing[0],...step->_changing[k-1]]
+                 is like this:
+                 for (bound = 0,1,...)
+                   for (ii = 0,...,k-1)
+                     iter[ii] := bound
+                     iter[0..ii-1] := values <= bound
+                     iter[ii+1..k-1] := values < bound
+                 and
+                   asso_values[step->_changing[i]] =
+                     _initial_asso_value + iter[i] * _jump.
+                 This makes it more likely to find small asso_values[].
+               */
+              unsigned int bound = iter[ii];
+              unsigned int i = 0;
+              while (i < ii)
+                {
+                  unsigned int c = step->_changing[i];
+                  iter[i]++;
+                  _asso_values[c] =
+                    (_asso_values[c] + _jump) & (step->_asso_value_max - 1);
+                  if (iter[i] <= bound)
+                    goto found_next;
+                  _asso_values[c] =
+                    (_asso_values[c] - iter[i] * _jump)
+                    & (step->_asso_value_max - 1);
+                  iter[i] = 0;
+                  i++;
+                }
+              i = ii + 1;
+              while (i < k)
+                {
+                  unsigned int c = step->_changing[i];
+                  iter[i]++;
+                  _asso_values[c] =
+                    (_asso_values[c] + _jump) & (step->_asso_value_max - 1);
+                  if (iter[i] < bound)
+                    goto found_next;
+                  _asso_values[c] =
+                    (_asso_values[c] - iter[i] * _jump)
+                    & (step->_asso_value_max - 1);
+                  iter[i] = 0;
+                  i++;
+                }
+              /* Switch from one ii to the next.  */
+              {
+                unsigned int c = step->_changing[ii];
+                _asso_values[c] =
+                  (_asso_values[c] - bound * _jump)
+                  & (step->_asso_value_max - 1);
+                iter[ii] = 0;
+              }
+              /* Here all iter[i] == 0.  */
+              ii++;
+              if (ii == k)
+                {
+                  ii = 0;
+                  bound++;
+                  if (bound == step->_asso_value_max)
+                    {
+                      /* Out of search space!  We can either backtrack, or
+                         increase the available search space of this step.
+                         It seems simpler to choose the latter solution.  */
+                      step->_asso_value_max = 2 * step->_asso_value_max;
+                      if (step->_asso_value_max > _asso_value_max)
+                        {
+                          _asso_value_max = step->_asso_value_max;
+                          /* Reinitialize _max_hash_value.  */
+                          _max_hash_value =
+                            (option[NOLENGTH] ? 0 : _max_key_len)
+                            + (_asso_value_max - 1) * _max_selchars_length;
+                          /* Reinitialize _collision_detector.  */
+                          delete _collision_detector;
+                          _collision_detector =
+                            new Bool_Array (_max_hash_value + 1);
+                        }
+                    }
+                }
+              {
+                unsigned int c = step->_changing[ii];
+                iter[ii] = bound;
+                _asso_values[c] =
+                  (_asso_values[c] + bound * _jump)
+                  & (step->_asso_value_max - 1);
+              }
+             found_next: ;
+            }
+          else
+            {
+              /* Random.  */
+              unsigned int c = step->_changing[ii];
+              _asso_values[c] =
+                (_asso_values[c] + rand ()) & (step->_asso_value_max - 1);
+              /* Next time, change the next c.  */
+              ii++;
+              if (ii == k)
+                ii = 0;
+            }
+        }
+      FREE_DYNAMIC_ARRAY (iter);
+
+      if (option[DEBUG])
+        {
+          fprintf (stderr, "Step %u chose _asso_values[", stepno);
+          for (unsigned int i = 0; i < step->_changing_count; i++)
+            {
+              if (i > 0)
+                fprintf (stderr, ",");
+              fprintf (stderr, "'%c'", step->_changing[i]);
+            }
+          fprintf (stderr, "] in %u iterations.\n", iterations);
+        }
+    }
+
+  /* Free allocated memory.  */
+  while (steps != NULL)
+    {
+      Step *step = steps;
+      steps = step->_next;
+      delete[] step->_changing;
+      delete[] step->_undetermined;
+      delete_partition (step->_partition);
+      delete step;
+    }
+}
+
+/* Computes a keyword's hash value, relative to the current _asso_values[],
+   and stores it in keyword->_hash_value.  */
+
+inline int
+Search::compute_hash (KeywordExt *keyword) const
+{
+  int sum = option[NOLENGTH] ? 0 : keyword->_allchars_length;
+
+  const unsigned int *p = keyword->_selchars;
+  int i = keyword->_selchars_length;
+  for (; i > 0; p++, i--)
+    sum += _asso_values[*p];
+
+  return keyword->_hash_value = sum;
+}
+
+/* Finds good _asso_values[].  */
+
+void
+Search::find_good_asso_values ()
+{
+  prepare_asso_values ();
+
+  /* Search for good _asso_values[].  */
+  int asso_iteration;
+  if ((asso_iteration = option.get_asso_iterations ()) == 0)
+    /* Try only the given _initial_asso_value and _jump.  */
+    find_asso_values ();
+  else
+    {
+      /* Try different pairs of _initial_asso_value and _jump, in the
+         following order:
+           (0, 1)
+           (1, 1)
+           (2, 1) (0, 3)
+           (3, 1) (1, 3)
+           (4, 1) (2, 3) (0, 5)
+           (5, 1) (3, 3) (1, 5)
+           ..... */
+      KeywordExt_List *saved_head = _head;
+      int best_initial_asso_value = 0;
+      int best_jump = 1;
+      int *best_asso_values = new int[_alpha_size];
+      int best_collisions = INT_MAX;
+      int best_max_hash_value = INT_MAX;
+
+      _initial_asso_value = 0; _jump = 1;
+      for (;;)
+        {
+          /* Restore the keyword list in its original order.  */
+          _head = copy_list (saved_head);
+          /* Find good _asso_values[].  */
+          find_asso_values ();
+          /* Test whether it is the best solution so far.  */
+          int collisions = 0;
+          int max_hash_value = INT_MIN;
+          _collision_detector->clear ();
+          for (KeywordExt_List *ptr = _head; ptr; ptr = ptr->rest())
+            {
+              KeywordExt *keyword = ptr->first();
+              int hashcode = compute_hash (keyword);
+              if (max_hash_value < hashcode)
+                max_hash_value = hashcode;
+              if (_collision_detector->set_bit (hashcode))
+                collisions++;
+            }
+          if (collisions < best_collisions
+              || (collisions == best_collisions
+                  && max_hash_value < best_max_hash_value))
+            {
+              memcpy (best_asso_values, _asso_values,
+                      _alpha_size * sizeof (_asso_values[0]));
+              best_collisions = collisions;
+              best_max_hash_value = max_hash_value;
+            }
+          /* Delete the copied keyword list.  */
+          delete_list (_head);
+
+          if (--asso_iteration == 0)
+            break;
+          /* Prepare for next iteration.  */
+          if (_initial_asso_value >= 2)
+            _initial_asso_value -= 2, _jump += 2;
+          else
+            _initial_asso_value += _jump, _jump = 1;
+        }
+      _head = saved_head;
+      /* Install the best found asso_values.  */
+      _initial_asso_value = best_initial_asso_value;
+      _jump = best_jump;
+      memcpy (_asso_values, best_asso_values,
+              _alpha_size * sizeof (_asso_values[0]));
+      delete[] best_asso_values;
+      /* The keywords' _hash_value fields are recomputed below.  */
+    }
+}
+
+/* ========================================================================= */
+
+/* Comparison function for sorting by increasing _hash_value.  */
+static bool
+less_by_hash_value (KeywordExt *keyword1, KeywordExt *keyword2)
+{
+  return keyword1->_hash_value < keyword2->_hash_value;
+}
+
+/* Sorts the keyword list by hash value.  */
+
+void
+Search::sort ()
+{
+  _head = mergesort_list (_head, less_by_hash_value);
+}
+
+void
+Search::optimize ()
+{
+  /* Preparations.  */
+  prepare ();
+
+  /* Step 1: Finding good byte positions.  */
+  find_positions ();
+
+  /* Step 2: Finding good alpha increments.  */
+  find_alpha_inc ();
+
+  /* Step 3: Finding good asso_values.  */
+  find_good_asso_values ();
+
+  /* Make one final check, just to make sure nothing weird happened.... */
+  _collision_detector->clear ();
+  for (KeywordExt_List *curr_ptr = _head; curr_ptr; curr_ptr = curr_ptr->rest())
+    {
+      KeywordExt *curr = curr_ptr->first();
+      unsigned int hashcode = compute_hash (curr);
+      if (_collision_detector->set_bit (hashcode))
+        {
+          /* This shouldn't happen.  proj1, proj2, proj3 must have been
+             computed to be injective on the given keyword set.  */
+          fprintf (stderr,
+                   "\nInternal error, unexpected duplicate hash code\n");
+          if (option[POSITIONS])
+            fprintf (stderr, "try options -m or -r, or use new key positions.\n\n");
+          else
+            fprintf (stderr, "try options -m or -r.\n\n");
+          exit (1);
+        }
+    }
+
+  /* Sorts the keyword list by hash value.  */
+  sort ();
+
+  /* Set unused asso_values[c] to max_hash_value + 1.  This is not absolutely
+     necessary, but speeds up the lookup function in many cases of lookup
+     failure: no string comparison is needed once the hash value of a string
+     is larger than the hash value of any keyword.  */
+  int max_hash_value;
+  {
+    KeywordExt_List *temp;
+    for (temp = _head; temp->rest(); temp = temp->rest())
+      ;
+    max_hash_value = temp->first()->_hash_value;
+  }
+  for (unsigned int c = 0; c < _alpha_size; c++)
+    if (_occurrences[c] == 0)
+      _asso_values[c] = max_hash_value + 1;
+
+  /* Propagate unified asso_values.  */
+  if (_alpha_unify)
+    for (unsigned int c = 0; c < _alpha_size; c++)
+      if (_alpha_unify[c] != c)
+        _asso_values[c] = _asso_values[_alpha_unify[c]];
+}
+
+/* Prints out some diagnostics upon completion.  */
+
+Search::~Search ()
+{
+  delete _collision_detector;
+  if (option[DEBUG])
+    {
+      fprintf (stderr, "\ndumping occurrence and associated values tables\n");
+
+      for (unsigned int i = 0; i < _alpha_size; i++)
+        if (_occurrences[i])
+          fprintf (stderr, "asso_values[%c] = %6d, occurrences[%c] = %6d\n",
+                   i, _asso_values[i], i, _occurrences[i]);
+
+      fprintf (stderr, "end table dumping\n");
+
+      fprintf (stderr, "\nDumping key list information:\ntotal non-static linked keywords = %d"
+               "\ntotal keywords = %d\ntotal duplicates = %d\nmaximum key length = %d\n",
+               _list_len, _total_keys, _total_duplicates, _max_key_len);
+
+      int field_width = _max_selchars_length;
+      fprintf (stderr, "\nList contents are:\n(hash value, key length, index, %*s, keyword):\n",
+               field_width, "selchars");
+      for (KeywordExt_List *ptr = _head; ptr; ptr = ptr->rest())
+        {
+          fprintf (stderr, "%11d,%11d,%6d, ",
+                   ptr->first()->_hash_value, ptr->first()->_allchars_length, ptr->first()->_final_index);
+          if (field_width > ptr->first()->_selchars_length)
+            fprintf (stderr, "%*s", field_width - ptr->first()->_selchars_length, "");
+          for (int j = 0; j < ptr->first()->_selchars_length; j++)
+            putc (ptr->first()->_selchars[j], stderr);
+          fprintf (stderr, ", %.*s\n",
+                   ptr->first()->_allchars_length, ptr->first()->_allchars);
+        }
+
+      fprintf (stderr, "End dumping list.\n\n");
+    }
+  delete[] _asso_values;
+  delete[] _occurrences;
+  delete[] _alpha_unify;
+  delete[] _alpha_inc;
+}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/src/search.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/contrib/gperf/src/search.h	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,165 @@
+/* This may look like C code, but it is really -*- C++ -*- */
+
+/* Search algorithm.
+
+   Copyright (C) 1989-1998, 2000, 2002 Free Software Foundation, Inc.
+   Written by Douglas C. Schmidt <schmidt at ics.uci.edu>
+   and Bruno Haible <bruno at clisp.org>.
+
+   This file is part of GNU GPERF.
+
+   GNU GPERF 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 GPERF 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; see the file COPYING.
+   If not, write to the Free Software Foundation, Inc.,
+   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
+
+#ifndef search_h
+#define search_h 1
+
+#include "keyword-list.h"
+#include "positions.h"
+#include "bool-array.h"
+
+struct EquivalenceClass;
+
+class Search
+{
+public:
+                        Search (KeywordExt_List *list);
+                        ~Search ();
+  void                  optimize ();
+private:
+  void                  prepare ();
+
+  /* Computes the upper bound on the indices passed to asso_values[],
+     assuming no alpha_increments.  */
+  unsigned int          compute_alpha_size () const;
+
+  /* Computes the unification rules between different asso_values[c],
+     assuming no alpha_increments.  */
+  unsigned int *        compute_alpha_unify () const;
+
+  /* Initializes each keyword's _selchars array.  */
+  void                  init_selchars_tuple (const Positions& positions, const unsigned int *alpha_unify) const;
+  /* Deletes each keyword's _selchars array.  */
+  void                  delete_selchars () const;
+
+  /* Count the duplicate keywords that occur with a given set of positions.  */
+  unsigned int          count_duplicates_tuple (const Positions& positions, const unsigned int *alpha_unify) const;
+
+  /* Find good key positions.  */
+  void                  find_positions ();
+
+  /* Count the duplicate keywords that occur with the found set of positions.  */
+  unsigned int          count_duplicates_tuple () const;
+
+  /* Computes the upper bound on the indices passed to asso_values[].  */
+  unsigned int          compute_alpha_size (const unsigned int *alpha_inc) const;
+
+  /* Computes the unification rules between different asso_values[c].  */
+  unsigned int *        compute_alpha_unify (const Positions& positions, const unsigned int *alpha_inc) const;
+
+  /* Initializes each keyword's _selchars array.  */
+  void                  init_selchars_multiset (const Positions& positions, const unsigned int *alpha_unify, const unsigned int *alpha_inc) const;
+
+  /* Count the duplicate keywords that occur with the given set of positions
+     and a given alpha_inc[] array.  */
+  unsigned int          count_duplicates_multiset (const unsigned int *alpha_inc) const;
+
+  /* Find good _alpha_inc[].  */
+  void                  find_alpha_inc ();
+
+  /* Initializes the asso_values[] related parameters.  */
+  void                  prepare_asso_values ();
+
+  EquivalenceClass *    compute_partition (bool *undetermined) const;
+
+  unsigned int          count_possible_collisions (EquivalenceClass *partition, unsigned int c) const;
+
+  bool                  unchanged_partition (EquivalenceClass *partition, unsigned int c) const;
+
+  /* Finds some _asso_values[] that fit.  */
+  void                  find_asso_values ();
+
+  /* Computes a keyword's hash value, relative to the current _asso_values[],
+     and stores it in keyword->_hash_value.  */
+  int                   compute_hash (KeywordExt *keyword) const;
+
+  /* Finds good _asso_values[].  */
+  void                  find_good_asso_values ();
+
+  /* Sorts the keyword list by hash value.  */
+  void                  sort ();
+
+public:
+
+  /* Linked list of keywords.  */
+  KeywordExt_List *     _head;
+
+  /* Total number of keywords, counting duplicates.  */
+  int                   _total_keys;
+
+  /* Maximum length of the longest keyword.  */
+  int                   _max_key_len;
+
+  /* Minimum length of the shortest keyword.  */
+  int                   _min_key_len;
+
+  /* User-specified or computed key positions.  */
+  Positions             _key_positions;
+
+  /* Adjustments to add to bytes add specific key positions.  */
+  unsigned int *        _alpha_inc;
+
+  /* Size of alphabet.  */
+  unsigned int          _alpha_size;
+
+  /* Alphabet character unification, either the identity or a mapping from
+     upper case characters to lower case characters (and maybe more).  */
+  unsigned int *        _alpha_unify;
+
+  /* Maximum _selchars_length over all keywords.  */
+  unsigned int          _max_selchars_length;
+
+  /* Total number of duplicates that have been moved to _duplicate_link lists
+     (not counting their representatives which stay on the main list).  */
+  int                   _total_duplicates;
+
+  /* Counts occurrences of each key set character.
+     _occurrences[c] is the number of times that c occurs among the _selchars
+     of a keyword.  */
+  int *                 _occurrences;
+  /* Value associated with each character. */
+  int *                 _asso_values;
+
+private:
+
+  /* Length of _head list.  Number of keywords, not counting duplicates.  */
+  int                   _list_len;
+
+  /* Exclusive upper bound for every _asso_values[c].  A power of 2.  */
+  unsigned int          _asso_value_max;
+
+  /* Initial value for asso_values table.  -1 means random.  */
+  int                   _initial_asso_value;
+  /* Jump length when trying alternative values.  0 means random.  */
+  int                   _jump;
+
+  /* Maximal possible hash value.  */
+  int                   _max_hash_value;
+
+  /* Sparse bit vector for collision detection.  */
+  Bool_Array *          _collision_detector;
+};
+
+#endif
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/src/trace.cc
--- a/head/contrib/gperf/src/trace.cc	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,35 +0,0 @@
-/* Tracing function calls.
-   Copyright (C) 1989-1998 Free Software Foundation, Inc.
-   written by Douglas C. Schmidt (schmidt at ics.uci.edu)
-
-This file is part of GNU GPERF.
-
-GNU GPERF 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 1, or (at your option)
-any later version.
-
-GNU GPERF 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 GPERF; see the file COPYING.  If not, write to the Free
-Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111, USA.  */
-
-#include "trace.h"
-
-#include <stdio.h>
-
-int Trace::nesting = 0;
-
-Trace::Trace (const char *n)
-{
-  fprintf (stderr, "%*scalling %s\n", 3 * nesting++, "", name = n);
-}
-
-Trace::~Trace (void)
-{
-  fprintf (stderr, "%*sleaving %s\n", 3 * --nesting, "", name);
-}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/src/trace.h
--- a/head/contrib/gperf/src/trace.h	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,40 +0,0 @@
-/* Tracing function calls.
-   Copyright (C) 1989-1998 Free Software Foundation, Inc.
-   written by Douglas C. Schmidt (schmidt at ics.uci.edu)
-
-This file is part of GNU GPERF.
-
-GNU GPERF 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 1, or (at your option)
-any later version.
-
-GNU GPERF 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 GPERF; see the file COPYING.  If not, write to the Free
-Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111, USA.  */
-
-#ifndef trace_h
-#define trace_h 1
-
-#ifdef TRACE
-#define T(X) X
-#else
-#define T(X)
-#endif
-
-class Trace
-{
-private:
-  static int nesting;
-  const char *name;
-public:
-  Trace (const char *n);
- ~Trace (void);
-};
-
-#endif
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/src/vectors.cc
--- a/head/contrib/gperf/src/vectors.cc	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,25 +0,0 @@
-/* Static class data members that are shared between several classes.
-   Copyright (C) 1989-1998 Free Software Foundation, Inc.
-   written by Douglas C. Schmidt (schmidt at ics.uci.edu)
-
-This file is part of GNU GPERF.
-
-GNU GPERF 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 1, or (at your option)
-any later version.
-
-GNU GPERF 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 GPERF; see the file COPYING.  If not, write to the Free
-Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111, USA.  */
-
-#include "vectors.h"
-
-int Vectors::ALPHA_SIZE = MAX_ALPHA_SIZE;
-int Vectors::occurrences[MAX_ALPHA_SIZE];
-int Vectors::asso_values[MAX_ALPHA_SIZE];
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/src/vectors.h
--- a/head/contrib/gperf/src/vectors.h	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,37 +0,0 @@
-/* This may look like C code, but it is really -*- C++ -*- */
-
-/* Static class data members that are shared between several classes via
-   inheritance.
-
-   Copyright (C) 1989-1998 Free Software Foundation, Inc.
-   written by Douglas C. Schmidt (schmidt at ics.uci.edu)
-
-This file is part of GNU GPERF.
-
-GNU GPERF 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 1, or (at your option)
-any later version.
-
-GNU GPERF 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 GPERF; see the file COPYING.  If not, write to the Free
-Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111, USA.  */
-
-#ifndef vectors_h
-#define vectors_h 1
-
-static const int MAX_ALPHA_SIZE = 256;
-
-struct Vectors
-{
-  static int   ALPHA_SIZE;                  /* Size of alphabet. */
-  static int   occurrences[MAX_ALPHA_SIZE]; /* Counts occurrences of each key set character. */
-  static int   asso_values[MAX_ALPHA_SIZE]; /* Value associated with each character. */
-};
-
-#endif
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/src/version.cc
--- a/head/contrib/gperf/src/version.cc	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/contrib/gperf/src/version.cc	Tue Dec 06 20:26:16 2011 +0200
@@ -1,22 +1,28 @@
 /* Current program version number.
 
-   Copyright (C) 1989-1998, 2000 Free Software Foundation, Inc.
-   written by Douglas C. Schmidt (schmidt at ics.uci.edu)
+   Copyright (C) 1989-1998, 2000, 2002-2003, 2005, 2007 Free Software Foundation, Inc.
+   Written by Douglas C. Schmidt <schmidt at ics.uci.edu>
+   and Bruno Haible <bruno at clisp.org>.
 
-This file is part of GNU GPERF.
+   This file is part of GNU GPERF.
 
-GNU GPERF 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 1, or (at your option)
-any later version.
+   GNU GPERF 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 GPERF 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.
+   GNU GPERF 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 GPERF; see the file COPYING.  If not, write to the Free
-Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111, USA.  */
+   You should have received a copy of the GNU General Public License
+   along with this program; see the file COPYING.
+   If not, write to the Free Software Foundation, Inc.,
+   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
 
-const char *version_string = "2.7.2";
+/* Specification. */
+#include "version.h"
+
+/* Current release version. */
+const char *version_string = "3.0.3";
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/src/version.h
--- a/head/contrib/gperf/src/version.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/contrib/gperf/src/version.h	Tue Dec 06 20:26:16 2011 +0200
@@ -1,23 +1,25 @@
 /* Current program version number.
 
-   Copyright (C) 1989-1998 Free Software Foundation, Inc.
-   written by Douglas C. Schmidt (schmidt at ics.uci.edu)
+   Copyright (C) 1989-1998, 2002 Free Software Foundation, Inc.
+   Written by Douglas C. Schmidt <schmidt at ics.uci.edu>
+   and Bruno Haible <bruno at clisp.org>.
 
-This file is part of GNU GPERF.
+   This file is part of GNU GPERF.
 
-GNU GPERF 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 1, or (at your option)
-any later version.
+   GNU GPERF 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 GPERF 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.
+   GNU GPERF 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 GPERF; see the file COPYING.  If not, write to the Free
-Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111, USA.  */
+   You should have received a copy of the GNU General Public License
+   along with this program; see the file COPYING.
+   If not, write to the Free Software Foundation, Inc.,
+   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
 
 /* Current release version. */
 extern const char *version_string;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/tests/Makefile.in
--- a/head/contrib/gperf/tests/Makefile.in	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,232 +0,0 @@
-# Makefile for gperf/tests
-
-# Copyright (C) 1989, 1992, 1993, 1995, 1998 Free Software Foundation, Inc.
-# written by Douglas C. Schmidt (schmidt at ics.uci.edu)
-#
-# This file is part of GNU GPERF.
-#
-# GNU GPERF 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 1, or (at your option)
-# any later version.
-#
-# GNU GPERF 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 GPERF; see the file COPYING.  If not, write to the Free
-# Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111, USA.
-
-#### Start of system configuration section. ####
-
-# Directories used by "make":
-srcdir = @srcdir@
-
-# Programs used by "make":
-# C compiler
-CC = @CC@
-CFLAGS = @CFLAGS@
-CPP = @CPP@
-# C++ compiler
-CXX = @CXX@
-CXXFLAGS = @CXXFLAGS@
-CXXCPP = @CXXCPP@
-# Other
-MV = mv
-LN = ln
-RM = rm -f
- at SET_MAKE@
-
-#### End of system configuration section. ####
-
-SHELL = /bin/sh
-
-VPATH = $(srcdir)
-
-GPERF = ../src/gperf
-
-all :
-
-install : all
-
-installdirs :
-
-uninstall :
-
-check : check-link-c check-link-c++ check-c check-ada check-modula3 check-pascal check-test
-	@true
-
-extracheck : @CHECK_LANG_SYNTAX@
-	@true
-
-check-link-c: force
-	@echo "performing some tests of the perfect hash generator"
-	$(CC) -c $(CFLAGS) $(srcdir)/test.c
-	$(GPERF) -p -c -l -S1 -o $(srcdir)/c.gperf > cinset.c
-	$(CC) $(CFLAGS) -o cout cinset.c test.o
-
-check-link-c++: force
-
-check-c:
-	@echo "testing ANSI C reserved words, all items should be found in the set"
-	./cout -v < $(srcdir)/c.gperf > c.out
-	diff $(srcdir)/c.exp c.out
-
-check-ada:
-	$(GPERF) -k1,4,'$$' $(srcdir)/ada.gperf > adainset.c
-# double '$$' is only there since make gets confused; program wants only 1 '$'
-	$(CC) $(CFLAGS) -o aout adainset.c test.o
-	@echo "testing Ada reserved words, all items should be found in the set"
-	./aout -v < $(srcdir)/ada.gperf > ada-res.out
-	diff $(srcdir)/ada-res.exp ada-res.out
-	$(GPERF) -p -D -k1,'$$' -s 2 -o $(srcdir)/adadefs.gperf > preinset.c
-	$(CC) $(CFLAGS) -o preout preinset.c test.o
-	@echo "testing Ada predefined words, all items should be found in the set"
-	./preout -v < $(srcdir)/adadefs.gperf > ada-pred.out
-	diff $(srcdir)/ada-pred.exp ada-pred.out
-
-check-modula3:
-	$(GPERF) -k1,2,'$$' -o $(srcdir)/modula3.gperf > m3inset.c
-	$(CC) $(CFLAGS) -o m3out m3inset.c test.o
-	@echo "testing Modula3 reserved words, all items should be found in the set"
-	./m3out -v < $(srcdir)/modula3.gperf > modula.out
-	diff $(srcdir)/modula.exp modula.out
-
-check-pascal:
-	$(GPERF) -o -S2 -p < $(srcdir)/pascal.gperf > pinset.c
-	$(CC) $(CFLAGS) -o pout pinset.c test.o
-	@echo "testing Pascal reserved words, all items should be found in the set"
-	./pout -v < $(srcdir)/pascal.gperf > pascal.out
-	diff $(srcdir)/pascal.exp pascal.out
-
-# these next 5 are demos that show off the generated code
-check-test:
-	$(GPERF) -p -j1 -g -o -t -N is_reserved_word -k1,3,'$$' < $(srcdir)/c-parse.gperf > test-1.out
-	diff $(srcdir)/test-1.exp test-1.out
-	$(GPERF) -n -k1-8 -l < $(srcdir)/modula2.gperf > test-2.out
-	diff $(srcdir)/test-2.exp test-2.out
-	$(GPERF) -p -j 1 -o -a -C -g -t -k1,4,$$ < $(srcdir)/gplus.gperf > test-3.out
-	diff $(srcdir)/test-3.exp test-3.out
-	$(GPERF) -D -p -t < $(srcdir)/c-parse.gperf > test-4.out
-	diff $(srcdir)/test-4.exp test-4.out
-	$(GPERF) -g -o -j1 -t -p -N is_reserved_word < $(srcdir)/gpc.gperf > test-5.out
-	diff $(srcdir)/test-5.exp test-5.out
-# prints out the help message
-	-$(GPERF) -h > test-6.out 2>&1
-	diff $(srcdir)/test-6.exp test-6.out
-	@echo "only if, do, for, case, goto, else, while, and return should be found "
-	./aout -v < $(srcdir)/c.gperf > test-7.out
-	diff $(srcdir)/test-7.exp test-7.out
-
-# The following validates valid language syntax with different parameters.
-# Works only with gcc and g++, and only on platforms where "gcc -ansi" is
-# usable. (There are still platforms where gcc-2.8.0's fixincludes does not
-# work well enough.)
-
-VALIDATE = CC='$(CC)' CFLAGS='$(CFLAGS)' CXX='$(CXX)' CXXFLAGS='$(CXXFLAGS)' GPERF='$(GPERF)' ./validate
-
-check-lang-syntax : force
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest1.gperf
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest1.gperf -c
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest1.gperf -C
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest1.gperf -E
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest1.gperf -G
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest1.gperf -G -C
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest1.gperf -G -E
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest1.gperf -l
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest1.gperf -D
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest1.gperf -D -l
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest1.gperf -S 10
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest1.gperf -S 10 -c
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest1.gperf -S 10 -C
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest1.gperf -S 10 -E
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest1.gperf -S 10 -G
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest1.gperf -S 10 -l
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest1.gperf -S 10 -D
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest1.gperf -S 10 -D -l
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest1.gperf -S 1000
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest1.gperf -p
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest1.gperf -p -C
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest1.gperf -p -l
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest1.gperf -p -D
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest1.gperf -p -D -l
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest1.gperf -p -S 10
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest1.gperf -p -S 10 -C
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest1.gperf -p -S 10 -l
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest1.gperf -p -S 10 -D
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest1.gperf -p -S 10 -D -l
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest1.gperf -p -S 1000
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest1.gperf -K key_name
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest1.gperf -H hash_function_name
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest1.gperf -W word_list_name
-	sed -e 's,in_word_set,lookup_function_name,g' < jstest1.gperf > tmp-jstest1.gperf && \
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 tmp-jstest1.gperf -N lookup_function_name
-	sed -e 's,Perfect_Hash,class_name,g' < jstest1.gperf > tmp-jstest1.gperf && \
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 tmp-jstest1.gperf -Z class_name
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest2.gperf -t -p
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest2.gperf -t -p -c
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest2.gperf -t -p -C
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest2.gperf -t -p -E
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest2.gperf -t -p -G
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest2.gperf -t -p -G -C
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest2.gperf -t -p -G -E
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest2.gperf -t -p -l
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest2.gperf -t -p -D
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest2.gperf -t -p -D -l
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest2.gperf -t -p -S 10
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest2.gperf -t -p -S 10 -c
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest2.gperf -t -p -S 10 -C
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest2.gperf -t -p -S 10 -E
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest2.gperf -t -p -S 10 -G
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest2.gperf -t -p -S 10 -l
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest2.gperf -t -p -S 10 -D
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest2.gperf -t -p -S 10 -D -l
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest2.gperf -t -p -S 1000
-	sed -e 's,name,key_name,g' < jstest2.gperf > tmp-jstest2.gperf && \
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 tmp-jstest2.gperf -t -p -K key_name
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 jstest2.gperf -t -p -H hash_function_name
-	sed -e 's,in_word_set,lookup_function_name,g' < jstest2.gperf > tmp-jstest2.gperf && \
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 tmp-jstest2.gperf -t -p -N lookup_function_name
-	sed -e 's,Perfect_Hash,class_name,g' < jstest2.gperf > tmp-jstest2.gperf && \
-	$(VALIDATE) KR-C,C,ANSI-C,C++ -k1,2 tmp-jstest2.gperf -t -p -Z class_name
-	$(VALIDATE) C,ANSI-C,C++ -k1,2 jstest3.gperf -t -p
-	$(VALIDATE) C,ANSI-C,C++ -k1,2 jstest3.gperf -t -p -c
-	$(VALIDATE) C,ANSI-C,C++ -k1,2 jstest3.gperf -t -p -C
-	$(VALIDATE) C,ANSI-C,C++ -k1,2 jstest3.gperf -t -p -E
-	$(VALIDATE) C,ANSI-C,C++ -k1,2 jstest3.gperf -t -p -G
-	$(VALIDATE) C,ANSI-C,C++ -k1,2 jstest3.gperf -t -p -G -C
-	$(VALIDATE) C,ANSI-C,C++ -k1,2 jstest3.gperf -t -p -G -E
-	$(VALIDATE) C,ANSI-C,C++ -k1,2 jstest3.gperf -t -p -l
-	$(VALIDATE) C,ANSI-C,C++ -k1,2 jstest3.gperf -t -p -D
-	$(VALIDATE) C,ANSI-C,C++ -k1,2 jstest3.gperf -t -p -D -l
-	$(VALIDATE) C,ANSI-C,C++ -k1,2 jstest3.gperf -t -p -S 10
-	$(VALIDATE) C,ANSI-C,C++ -k1,2 jstest3.gperf -t -p -S 10 -c
-	$(VALIDATE) C,ANSI-C,C++ -k1,2 jstest3.gperf -t -p -S 10 -C
-	$(VALIDATE) C,ANSI-C,C++ -k1,2 jstest3.gperf -t -p -S 10 -E
-	$(VALIDATE) C,ANSI-C,C++ -k1,2 jstest3.gperf -t -p -S 10 -G
-	$(VALIDATE) C,ANSI-C,C++ -k1,2 jstest3.gperf -t -p -S 10 -l
-	$(VALIDATE) C,ANSI-C,C++ -k1,2 jstest3.gperf -t -p -S 10 -D
-	$(VALIDATE) C,ANSI-C,C++ -k1,2 jstest3.gperf -t -p -S 10 -D -l
-	$(VALIDATE) C,ANSI-C,C++ -k1,2 jstest3.gperf -t -p -S 1000
-	sed -e 's,name,key_name,g' < jstest3.gperf > tmp-jstest3.gperf && \
-	$(VALIDATE) C,ANSI-C,C++ -k1,2 tmp-jstest3.gperf -t -p -K key_name
-	$(VALIDATE) C,ANSI-C,C++ -k1,2 jstest3.gperf -t -p -H hash_function_name
-	sed -e 's,in_word_set,lookup_function_name,g' < jstest3.gperf > tmp-jstest3.gperf && \
-	$(VALIDATE) C,ANSI-C,C++ -k1,2 tmp-jstest3.gperf -t -p -N lookup_function_name
-	sed -e 's,Perfect_Hash,class_name,g' < jstest3.gperf > tmp-jstest3.gperf && \
-	$(VALIDATE) C,ANSI-C,C++ -k1,2 tmp-jstest3.gperf -t -p -Z class_name
-
-mostlyclean : clean
-
-clean : force
-	$(RM) *.o core *inset.c output.* *.out aout cout m3out pout preout tmp-* valitest*
-
-distclean : clean
-	$(RM) config.status config.log config.cache Makefile
-
-maintainer-clean : distclean
-
-force :
-
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/tests/ada-pred.exp
--- a/head/contrib/gperf/tests/ada-pred.exp	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,54 +0,0 @@
-in word set boolean
-in word set character
-in word set constraint_error
-in word set false
-in word set float
-in word set integer
-in word set natural
-in word set numeric_error
-in word set positive
-in word set program_error
-in word set storage_error
-in word set string
-in word set tasking_error
-in word set true
-in word set address
-in word set aft
-in word set base
-in word set callable
-in word set constrained
-in word set count
-in word set delta
-in word set digits
-in word set emax
-in word set epsilon
-in word set first
-in word set firstbit
-in word set fore
-in word set image
-in word set large
-in word set last
-in word set lastbit
-in word set length
-in word set machine_emax
-in word set machine_emin
-in word set machine_mantissa
-in word set machine_overflows
-in word set machine_radix
-in word set machine_rounds
-in word set mantissa
-in word set pos
-in word set position
-in word set pred
-in word set range
-in word set safe_emax
-in word set safe_large
-in word set safe_small
-in word set size
-in word set small
-in word set storage_size
-in word set succ
-in word set terminated
-in word set val
-in word set value
-in word set width
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/tests/ada-res.exp
--- a/head/contrib/gperf/tests/ada-res.exp	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,63 +0,0 @@
-in word set else
-in word set exit
-in word set terminate
-in word set type
-in word set raise
-in word set range
-in word set reverse
-in word set declare
-in word set end
-in word set record
-in word set exception
-in word set not
-in word set then
-in word set return
-in word set separate
-in word set select
-in word set digits
-in word set renames
-in word set subtype
-in word set elsif
-in word set function
-in word set for
-in word set package
-in word set procedure
-in word set private
-in word set while
-in word set when
-in word set new
-in word set entry
-in word set delay
-in word set case
-in word set constant
-in word set at
-in word set abort
-in word set accept
-in word set and
-in word set delta
-in word set access
-in word set abs
-in word set pragma
-in word set array
-in word set use
-in word set out
-in word set do
-in word set others
-in word set of
-in word set or
-in word set all
-in word set limited
-in word set loop
-in word set null
-in word set task
-in word set in
-in word set is
-in word set if
-in word set rem
-in word set mod
-in word set begin
-in word set body
-in word set xor
-in word set goto
-in word set generic
-in word set with
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/tests/ada.gperf
--- a/head/contrib/gperf/tests/ada.gperf	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,63 +0,0 @@
-else
-exit
-terminate
-type
-raise
-range
-reverse
-declare
-end
-record
-exception
-not
-then
-return
-separate
-select
-digits
-renames
-subtype
-elsif
-function
-for
-package
-procedure
-private
-while
-when
-new
-entry
-delay
-case
-constant
-at
-abort
-accept
-and
-delta
-access
-abs
-pragma
-array
-use
-out
-do
-others
-of
-or
-all
-limited
-loop
-null
-task
-in
-is
-if
-rem
-mod
-begin
-body
-xor
-goto
-generic
-with
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/tests/adadefs.gperf
--- a/head/contrib/gperf/tests/adadefs.gperf	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,54 +0,0 @@
-boolean
-character
-constraint_error
-false
-float
-integer
-natural
-numeric_error
-positive
-program_error
-storage_error
-string
-tasking_error
-true
-address
-aft
-base
-callable
-constrained
-count
-delta
-digits
-emax
-epsilon
-first
-firstbit
-fore
-image
-large
-last
-lastbit
-length
-machine_emax
-machine_emin
-machine_mantissa
-machine_overflows
-machine_radix
-machine_rounds
-mantissa
-pos
-position
-pred
-range
-safe_emax
-safe_large
-safe_small
-size
-small
-storage_size
-succ
-terminated
-val
-value
-width
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/tests/c++.gperf
--- a/head/contrib/gperf/tests/c++.gperf	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,47 +0,0 @@
-asm
-auto
-break
-case
-catch
-char
-class
-const
-continue
-default
-delete
-do
-double
-else
-enum
-extern
-float
-for
-friend
-goto
-if
-inline
-int
-long
-new
-operator
-overload
-private
-protected
-public
-register
-return
-short
-signed
-sizeof
-static
-struct
-switch
-template
-this
-typedef
-union
-unsigned
-virtual
-void
-volatile
-while
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/tests/c-parse.gperf
--- a/head/contrib/gperf/tests/c-parse.gperf	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,56 +0,0 @@
-%{
-/* Command-line: gperf -p -j1 -i 1 -g -o -t -N is_reserved_word -k1,3,$ c-parse.gperf  */
-%}
-struct resword { char *name; short token; enum rid rid; };
-%%
-__alignof, ALIGNOF, NORID
-__alignof__, ALIGNOF, NORID
-__asm, ASM, NORID
-__asm__, ASM, NORID
-__attribute, ATTRIBUTE, NORID
-__attribute__, ATTRIBUTE, NORID
-__const, TYPE_QUAL, RID_CONST
-__const__, TYPE_QUAL, RID_CONST
-__inline, SCSPEC, RID_INLINE
-__inline__, SCSPEC, RID_INLINE
-__signed, TYPESPEC, RID_SIGNED
-__signed__, TYPESPEC, RID_SIGNED
-__typeof, TYPEOF, NORID
-__typeof__, TYPEOF, NORID
-__volatile, TYPE_QUAL, RID_VOLATILE
-__volatile__, TYPE_QUAL, RID_VOLATILE
-asm, ASM, NORID
-auto, SCSPEC, RID_AUTO
-break, BREAK, NORID
-case, CASE, NORID
-char, TYPESPEC, RID_CHAR
-const, TYPE_QUAL, RID_CONST
-continue, CONTINUE, NORID
-default, DEFAULT, NORID
-do, DO, NORID
-double, TYPESPEC, RID_DOUBLE
-else, ELSE, NORID
-enum, ENUM, NORID
-extern, SCSPEC, RID_EXTERN
-float, TYPESPEC, RID_FLOAT
-for, FOR, NORID
-goto, GOTO, NORID
-if, IF, NORID
-inline, SCSPEC, RID_INLINE
-int, TYPESPEC, RID_INT
-long, TYPESPEC, RID_LONG
-register, SCSPEC, RID_REGISTER
-return, RETURN, NORID
-short, TYPESPEC, RID_SHORT
-signed, TYPESPEC, RID_SIGNED
-sizeof, SIZEOF, NORID
-static, SCSPEC, RID_STATIC
-struct, STRUCT, NORID
-switch, SWITCH, NORID
-typedef, SCSPEC, RID_TYPEDEF
-typeof, TYPEOF, NORID
-union, UNION, NORID
-unsigned, TYPESPEC, RID_UNSIGNED
-void, TYPESPEC, RID_VOID
-volatile, TYPE_QUAL, RID_VOLATILE
-while, WHILE, NORID
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/tests/c.exp
--- a/head/contrib/gperf/tests/c.exp	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,32 +0,0 @@
-in word set if
-in word set do
-in word set int
-in word set for
-in word set case
-in word set char
-in word set auto
-in word set goto
-in word set else
-in word set long
-in word set void
-in word set enum
-in word set float
-in word set short
-in word set union
-in word set break
-in word set while
-in word set const
-in word set double
-in word set static
-in word set extern
-in word set struct
-in word set return
-in word set sizeof
-in word set switch
-in word set signed
-in word set typedef
-in word set default
-in word set unsigned
-in word set continue
-in word set register
-in word set volatile
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/tests/c.gperf
--- a/head/contrib/gperf/tests/c.gperf	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,32 +0,0 @@
-if
-do
-int
-for
-case
-char
-auto
-goto
-else
-long
-void
-enum
-float
-short
-union
-break
-while
-const
-double
-static
-extern
-struct
-return
-sizeof
-switch
-signed
-typedef
-default
-unsigned
-continue
-register
-volatile
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/tests/configure
--- a/head/contrib/gperf/tests/configure	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,1214 +0,0 @@
-#! /bin/sh
-
-# Guess values for system-dependent variables and create Makefiles.
-# Generated automatically using autoconf version 2.12 
-# 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=
-# 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.12"
-    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=c-parse.gperf
-
-# 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 $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS 1>&5'
-cross_compiling=$ac_cv_prog_cc_cross
-
-if (echo "testing\c"; echo 1,2,3) | grep c >/dev/null; then
-  # Stardent Vistra SVR4 grep lacks -e, says ghazi at 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
-
-
-echo $ac_n "checking whether ${MAKE-make} sets \${MAKE}""... $ac_c" 1>&6
-echo "configure:523: 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 "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:552: 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="${IFS}:"
-  for ac_dir in $PATH; 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:581: 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="${IFS}:"
-  ac_prog_rejected=no
-  for ac_dir in $PATH; 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 the C compiler ($CC $CFLAGS $LDFLAGS) works""... $ac_c" 1>&6
-echo "configure:629: checking whether the C compiler ($CC $CFLAGS $LDFLAGS) works" >&5
-
-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 $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS 1>&5'
-cross_compiling=$ac_cv_prog_cc_cross
-
-cat > conftest.$ac_ext <<EOF
-#line 639 "configure"
-#include "confdefs.h"
-main(){return(0);}
-EOF
-if { (eval echo configure:643: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest; then
-  ac_cv_prog_cc_works=yes
-  # If we can't run a trivial program, we are probably using a cross compiler.
-  if (./conftest; exit) 2>/dev/null; then
-    ac_cv_prog_cc_cross=no
-  else
-    ac_cv_prog_cc_cross=yes
-  fi
-else
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  ac_cv_prog_cc_works=no
-fi
-rm -fr conftest*
-
-echo "$ac_t""$ac_cv_prog_cc_works" 1>&6
-if test $ac_cv_prog_cc_works = no; then
-  { echo "configure: error: installation or configuration problem: C compiler cannot create executables." 1>&2; exit 1; }
-fi
-echo $ac_n "checking whether the C compiler ($CC $CFLAGS $LDFLAGS) is a cross-compiler""... $ac_c" 1>&6
-echo "configure:663: checking whether the C compiler ($CC $CFLAGS $LDFLAGS) is a cross-compiler" >&5
-echo "$ac_t""$ac_cv_prog_cc_cross" 1>&6
-cross_compiling=$ac_cv_prog_cc_cross
-
-echo $ac_n "checking whether we are using GNU C""... $ac_c" 1>&6
-echo "configure:668: 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 <<EOF
-#ifdef __GNUC__
-  yes;
-#endif
-EOF
-if { ac_try='${CC-cc} -E conftest.c'; { (eval echo configure:677: \"$ac_try\") 1>&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:692: 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
-
-                      echo $ac_n "checking how to run the C preprocessor""... $ac_c" 1>&6
-echo "configure:720: 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 <<EOF
-#line 735 "configure"
-#include "confdefs.h"
-#include <assert.h>
-Syntax Error
-EOF
-ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
-{ (eval echo configure:741: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
-ac_err=`grep -v '^ *+' conftest.out`
-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 <<EOF
-#line 752 "configure"
-#include "confdefs.h"
-#include <assert.h>
-Syntax Error
-EOF
-ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
-{ (eval echo configure:758: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
-ac_err=`grep -v '^ *+' conftest.out`
-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*
-  ac_cv_prog_CPP="$CPP"
-fi
-  CPP="$ac_cv_prog_CPP"
-else
-  ac_cv_prog_CPP="$CPP"
-fi
-echo "$ac_t""$CPP" 1>&6
-
-                      for ac_prog in $CCC c++ g++ gcc CC cxx cc++
-do
-# Extract the first word of "$ac_prog", so it can be a program name with args.
-set dummy $ac_prog; ac_word=$2
-echo $ac_n "checking for $ac_word""... $ac_c" 1>&6
-echo "configure:785: checking for $ac_word" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_CXX'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  if test -n "$CXX"; then
-  ac_cv_prog_CXX="$CXX" # Let the user override the test.
-else
-  IFS="${IFS= 	}"; ac_save_ifs="$IFS"; IFS="${IFS}:"
-  for ac_dir in $PATH; do
-    test -z "$ac_dir" && ac_dir=.
-    if test -f $ac_dir/$ac_word; then
-      ac_cv_prog_CXX="$ac_prog"
-      break
-    fi
-  done
-  IFS="$ac_save_ifs"
-fi
-fi
-CXX="$ac_cv_prog_CXX"
-if test -n "$CXX"; then
-  echo "$ac_t""$CXX" 1>&6
-else
-  echo "$ac_t""no" 1>&6
-fi
-
-test -n "$CXX" && break
-done
-test -n "$CXX" || CXX="gcc"
-
-
-echo $ac_n "checking whether the C++ compiler ($CXX $CXXFLAGS $LDFLAGS) works""... $ac_c" 1>&6
-echo "configure:816: checking whether the C++ compiler ($CXX $CXXFLAGS $LDFLAGS) works" >&5
-
-ac_ext=C
-# CXXFLAGS is not in ac_cpp because -g, -O, etc. are not valid cpp options.
-ac_cpp='$CXXCPP $CPPFLAGS'
-ac_compile='${CXX-g++} -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext 1>&5'
-ac_link='${CXX-g++} -o conftest $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS 1>&5'
-cross_compiling=$ac_cv_prog_cxx_cross
-
-cat > conftest.$ac_ext <<EOF
-#line 826 "configure"
-#include "confdefs.h"
-main(){return(0);}
-EOF
-if { (eval echo configure:830: \"$ac_link\") 1>&5; (eval $ac_link) 2>&5; } && test -s conftest; then
-  ac_cv_prog_cxx_works=yes
-  # If we can't run a trivial program, we are probably using a cross compiler.
-  if (./conftest; exit) 2>/dev/null; then
-    ac_cv_prog_cxx_cross=no
-  else
-    ac_cv_prog_cxx_cross=yes
-  fi
-else
-  echo "configure: failed program was:" >&5
-  cat conftest.$ac_ext >&5
-  ac_cv_prog_cxx_works=no
-fi
-rm -fr 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 $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS 1>&5'
-cross_compiling=$ac_cv_prog_cc_cross
-
-echo "$ac_t""$ac_cv_prog_cxx_works" 1>&6
-if test $ac_cv_prog_cxx_works = no; then
-  { echo "configure: error: installation or configuration problem: C++ compiler cannot create executables." 1>&2; exit 1; }
-fi
-echo $ac_n "checking whether the C++ compiler ($CXX $CXXFLAGS $LDFLAGS) is a cross-compiler""... $ac_c" 1>&6
-echo "configure:856: checking whether the C++ compiler ($CXX $CXXFLAGS $LDFLAGS) is a cross-compiler" >&5
-echo "$ac_t""$ac_cv_prog_cxx_cross" 1>&6
-cross_compiling=$ac_cv_prog_cxx_cross
-
-echo $ac_n "checking whether we are using GNU C++""... $ac_c" 1>&6
-echo "configure:861: checking whether we are using GNU C++" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_gxx'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  cat > conftest.C <<EOF
-#ifdef __GNUC__
-  yes;
-#endif
-EOF
-if { ac_try='${CXX-g++} -E conftest.C'; { (eval echo configure:870: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }; } | egrep yes >/dev/null 2>&1; then
-  ac_cv_prog_gxx=yes
-else
-  ac_cv_prog_gxx=no
-fi
-fi
-
-echo "$ac_t""$ac_cv_prog_gxx" 1>&6
-
-if test $ac_cv_prog_gxx = yes; then
-  GXX=yes
-  ac_test_CXXFLAGS="${CXXFLAGS+set}"
-  ac_save_CXXFLAGS="$CXXFLAGS"
-  CXXFLAGS=
-  echo $ac_n "checking whether ${CXX-g++} accepts -g""... $ac_c" 1>&6
-echo "configure:885: checking whether ${CXX-g++} accepts -g" >&5
-if eval "test \"`echo '$''{'ac_cv_prog_cxx_g'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  echo 'void f(){}' > conftest.cc
-if test -z "`${CXX-g++} -g -c conftest.cc 2>&1`"; then
-  ac_cv_prog_cxx_g=yes
-else
-  ac_cv_prog_cxx_g=no
-fi
-rm -f conftest*
-
-fi
-
-echo "$ac_t""$ac_cv_prog_cxx_g" 1>&6
-  if test "$ac_test_CXXFLAGS" = set; then
-    CXXFLAGS="$ac_save_CXXFLAGS"
-  elif test $ac_cv_prog_cxx_g = yes; then
-    CXXFLAGS="-g -O2"
-  else
-    CXXFLAGS="-O2"
-  fi
-else
-  GXX=
-  test "${CXXFLAGS+set}" = set || CXXFLAGS="-g"
-fi
-
-                      echo $ac_n "checking how to run the C++ preprocessor""... $ac_c" 1>&6
-echo "configure:913: checking how to run the C++ preprocessor" >&5
-if test -z "$CXXCPP"; then
-if eval "test \"`echo '$''{'ac_cv_prog_CXXCPP'+set}'`\" = set"; then
-  echo $ac_n "(cached) $ac_c" 1>&6
-else
-  ac_ext=C
-# CXXFLAGS is not in ac_cpp because -g, -O, etc. are not valid cpp options.
-ac_cpp='$CXXCPP $CPPFLAGS'
-ac_compile='${CXX-g++} -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext 1>&5'
-ac_link='${CXX-g++} -o conftest $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS 1>&5'
-cross_compiling=$ac_cv_prog_cxx_cross
-  CXXCPP="${CXX-g++} -E"
-  cat > conftest.$ac_ext <<EOF
-#line 926 "configure"
-#include "confdefs.h"
-#include <stdlib.h>
-EOF
-ac_try="$ac_cpp conftest.$ac_ext >/dev/null 2>conftest.out"
-{ (eval echo configure:931: \"$ac_try\") 1>&5; (eval $ac_try) 2>&5; }
-ac_err=`grep -v '^ *+' conftest.out`
-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*
-  CXXCPP=/lib/cpp
-fi
-rm -f conftest*
-  ac_cv_prog_CXXCPP="$CXXCPP"
-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 $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS 1>&5'
-cross_compiling=$ac_cv_prog_cc_cross
-fi
-fi
-CXXCPP="$ac_cv_prog_CXXCPP"
-echo "$ac_t""$CXXCPP" 1>&6
-
-                      if test $ac_cv_prog_gcc = yes -a $ac_cv_prog_gxx = yes; then
-  CHECK_LANG_SYNTAX='check-lang-syntax'
-else
-  CHECK_LANG_SYNTAX=''
-fi
-
-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) 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 <<EOF
-#! /bin/sh
-# Generated automatically by configure.
-# Run this file to recreate the current configuration.
-# This directory was configured as follows,
-# on host `(hostname || uname -n) 2>/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.12"
-    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 <<EOF
-
-# Protect against being on the right side of a sed subst in config.status.
-sed 's/%@/@@/; s/@%/@@/; s/%g\$/@g/; /@g\$/s/[\\\\&%]/\\\\&/g;
- s/@@/%@/; s/@@/@%/; s/@g\$/%g/' > conftest.subs <<\\CEOF
-$ac_vpsub
-$extrasub
-s%@CFLAGS@%$CFLAGS%g
-s%@CPPFLAGS@%$CPPFLAGS%g
-s%@CXXFLAGS@%$CXXFLAGS%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%@SET_MAKE@%$SET_MAKE%g
-s%@CC@%$CC%g
-s%@CPP@%$CPP%g
-s%@CXX@%$CXX%g
-s%@CXXCPP@%$CXXCPP%g
-s%@CHECK_LANG_SYNTAX@%$CHECK_LANG_SYNTAX%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 <<EOF
-
-CONFIG_FILES=\${CONFIG_FILES-"Makefile"}
-EOF
-cat >> $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 <<EOF
-
-EOF
-cat >> $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 -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/tests/configure.in
--- a/head/contrib/gperf/tests/configure.in	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,45 +0,0 @@
-dnl autoconf configuration for gperf/tests
-
-dnl Copyright (C) 1998 Free Software Foundation, Inc.
-dnl written by Douglas C. Schmidt (schmidt at ics.uci.edu)
-dnl
-dnl This file is part of GNU GPERF.
-dnl
-dnl GNU GPERF is free software; you can redistribute it and/or modify
-dnl it under the terms of the GNU General Public License as published by
-dnl the Free Software Foundation; either version 1, or (at your option)
-dnl any later version.
-dnl
-dnl GNU GPERF is distributed in the hope that it will be useful,
-dnl but WITHOUT ANY WARRANTY; without even the implied warranty of
-dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-dnl GNU General Public License for more details.
-dnl
-dnl You should have received a copy of the GNU General Public License
-dnl along with GNU GPERF; see the file COPYING.  If not, write to the
-dnl Free Software Foundation, 59 Temple Place - Suite 330, Boston,
-dnl MA 02111-1307, USA.
-
-AC_INIT(c-parse.gperf)
-AC_PROG_MAKE_SET
-dnl
-dnl           checks for programs
-dnl
-AC_PROG_CC
-                      dnl sets variable CC
-AC_PROG_CPP
-                      dnl sets variable CPP
-AC_PROG_CXX
-                      dnl sets variable CXX
-AC_PROG_CXXCPP
-                      dnl sets variable CXXCPP
-if test $ac_cv_prog_gcc = yes -a $ac_cv_prog_gxx = yes; then
-  CHECK_LANG_SYNTAX='check-lang-syntax'
-else
-  CHECK_LANG_SYNTAX=''
-fi
-AC_SUBST(CHECK_LANG_SYNTAX)
-dnl
-dnl           That's it.
-dnl
-AC_OUTPUT(Makefile)
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/tests/gpc.gperf
--- a/head/contrib/gperf/tests/gpc.gperf	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,48 +0,0 @@
-%{
-/* ISO Pascal 7185 reserved words.
- *
- * For GNU Pascal compiler (GPC) by jtv at hut.fi
- *
- * run this through the Doug Schmidt's gperf program
- * with command
- * gperf  -g -o -j1 -t -p -N is_reserved_word
- *
- */
-%}
-struct resword { char *name; short token; short iclass;};
-%%
-And,  AND,  PASCAL_ISO
-Array,  ARRAY,  PASCAL_ISO
-Begin,  BEGIN_, PASCAL_ISO
-Case, CASE, PASCAL_ISO
-Const,  CONST,  PASCAL_ISO
-Div,  DIV,  PASCAL_ISO
-Do, DO, PASCAL_ISO
-Downto, DOWNTO, PASCAL_ISO
-Else, ELSE, PASCAL_ISO
-End,  END,  PASCAL_ISO
-File, FILE_,  PASCAL_ISO
-For,  FOR,  PASCAL_ISO
-Function, FUNCTION, PASCAL_ISO
-Goto, GOTO, PASCAL_ISO
-If, IF, PASCAL_ISO
-In, IN, PASCAL_ISO
-Label,  LABEL,  PASCAL_ISO
-Mod,  MOD,  PASCAL_ISO
-Nil,  NIL,  PASCAL_ISO
-Not,  NOT,  PASCAL_ISO
-Of, OF, PASCAL_ISO
-Or, OR, PASCAL_ISO
-Packed, PACKED, PASCAL_ISO
-Procedure, PROCEDURE, PASCAL_ISO
-Program,PROGRAM,PASCAL_ISO
-Record, RECORD, PASCAL_ISO
-Repeat, REPEAT, PASCAL_ISO
-Set,  SET,  PASCAL_ISO
-Then, THEN, PASCAL_ISO
-To, TO, PASCAL_ISO
-Type, TYPE, PASCAL_ISO
-Until,  UNTIL,  PASCAL_ISO
-Var,  VAR,  PASCAL_ISO
-While,  WHILE,  PASCAL_ISO
-With, WITH, PASCAL_ISO
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/tests/gplus.gperf
--- a/head/contrib/gperf/tests/gplus.gperf	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,76 +0,0 @@
-%{
-/* Command-line: gperf -p -j1 -g -o -t -N is_reserved_word -k1,4,$ gplus.gperf  */
-%}
-struct resword { char *name; short token; enum rid rid;};
-%%
-__alignof, ALIGNOF, NORID
-__alignof__, ALIGNOF, NORID
-__asm, ASM, NORID
-__asm__, ASM, NORID
-__attribute, ATTRIBUTE, NORID
-__attribute__, ATTRIBUTE, NORID
-__const, TYPE_QUAL, RID_CONST
-__const__, TYPE_QUAL, RID_CONST
-__inline, SCSPEC, RID_INLINE
-__inline__, SCSPEC, RID_INLINE
-__signed, TYPESPEC, RID_SIGNED
-__signed__, TYPESPEC, RID_SIGNED
-__typeof, TYPEOF, NORID
-__typeof__, TYPEOF, NORID
-__volatile, TYPE_QUAL, RID_VOLATILE
-__volatile__, TYPE_QUAL, RID_VOLATILE
-all, ALL, NORID			/* Extension */,
-except, EXCEPT, NORID		/* Extension */,
-exception, AGGR, RID_EXCEPTION	/* Extension */,
-raise, RAISE, NORID		/* Extension */,
-raises, RAISES, NORID		/* Extension */,
-reraise, RERAISE, NORID		/* Extension */,
-try, TRY, NORID			/* Extension */,
-asm, ASM, NORID,
-auto, SCSPEC, RID_AUTO,
-break, BREAK, NORID,
-case, CASE, NORID,
-catch, CATCH, NORID,
-char, TYPESPEC, RID_CHAR,
-class, AGGR, RID_CLASS,
-const, TYPE_QUAL, RID_CONST,
-continue, CONTINUE, NORID,
-default, DEFAULT, NORID,
-delete, DELETE, NORID,
-do, DO, NORID,
-double, TYPESPEC, RID_DOUBLE,
-dynamic, DYNAMIC, NORID,
-else, ELSE, NORID,
-enum, ENUM, NORID,
-extern, SCSPEC, RID_EXTERN,
-float, TYPESPEC, RID_FLOAT,
-for, FOR, NORID,
-friend, SCSPEC, RID_FRIEND,
-goto, GOTO, NORID,
-if, IF, NORID,
-inline, SCSPEC, RID_INLINE,
-int, TYPESPEC, RID_INT,
-long, TYPESPEC, RID_LONG,
-new, NEW, NORID,
-operator, OPERATOR, NORID,
-overload, OVERLOAD, NORID,
-private, PRIVATE, NORID,
-protected, PROTECTED, NORID,
-public, PUBLIC, NORID,
-register, SCSPEC, RID_REGISTER,
-return, RETURN, NORID,
-short, TYPESPEC, RID_SHORT,
-signed, TYPESPEC, RID_SIGNED,
-sizeof, SIZEOF, NORID,
-static, SCSPEC, RID_STATIC,
-struct, AGGR, RID_RECORD,
-switch, SWITCH, NORID,
-this, THIS, NORID,
-typedef, SCSPEC, RID_TYPEDEF,
-typeof, TYPEOF, NORID,
-union, AGGR, RID_UNION,
-unsigned, TYPESPEC, RID_UNSIGNED,
-virtual, SCSPEC, RID_VIRTUAL,
-void, TYPESPEC, RID_VOID,
-volatile, TYPE_QUAL, RID_VOLATILE,
-while, WHILE, NORID,
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/tests/irc.gperf
--- a/head/contrib/gperf/tests/irc.gperf	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,63 +0,0 @@
-%{
-extern int m_text(), m_private(), m_who(), m_whois(), m_user(), m_list();
-extern int m_topic(), m_invite(), m_channel(), m_version(), m_quit();
-extern int m_server(), m_kill(), m_info(), m_links(), m_summon(), m_stats();
-extern int m_users(), m_nick(), m_error(), m_help(), m_whoreply();
-extern int m_squit(), m_restart(), m_away(), m_die(), m_connect();
-extern int m_ping(), m_pong(), m_oper(), m_pass(), m_wall(), m_trace();
-extern int m_time(), m_rehash(), m_names(), m_namreply(), m_admin();
-extern int m_linreply(), m_notice(), m_lusers(), m_voice(), m_grph();
-extern int m_xtra(), m_motd();
-%}
-struct Message {
-  char *cmd;
-  int (* func)();
-  int count;
-  int parameters;
-};
-%%
-NICK,    m_nick,     0, 1
-MSG,     m_text,     0, 1
-PRIVMSG, m_private,  0, 2
-WHO,     m_who,      0, 1
-WHOIS,   m_whois,    0, 4
-USER,    m_user,     0, 4
-SERVER,  m_server,   0, 2
-LIST,    m_list,     0, 1
-TOPIC,   m_topic,    0, 1
-INVITE,  m_invite,   0, 2
-CHANNEL, m_channel,  0, 1
-VERSION, m_version,  0, 1
-QUIT,    m_quit,     0, 2
-SQUIT,   m_squit,    0, 2
-KILL,    m_kill,     0, 2
-INFO,    m_info,     0, 1
-LINKS,   m_links,    0, 1
-SUMMON,  m_summon,   0, 1
-STATS,   m_stats,    0, 1
-USERS,   m_users,    0, 1
-RESTART, m_restart,  0, 1
-WHOREPLY,m_whoreply, 0, 7
-HELP,    m_help,     0, 2
-ERROR,   m_error,    0, 1
-AWAY,    m_away,     0, 1
-DIE,     m_die,      0, 1
-CONNECT, m_connect,  0, 3
-PING,    m_ping,     0, 2
-PONG,    m_pong,     0, 3
-OPER,    m_oper,     0, 3
-PASS,    m_pass,     0, 2
-WALL,    m_wall,     0, 1
-TIME,    m_time,     0, 1
-REHASH,  m_rehash,   0, 1
-NAMES,   m_names,    0, 1
-NAMREPLY,m_namreply, 0, 3
-ADMIN,   m_admin,    0, 1
-TRACE,   m_trace,    0, 1
-LINREPLY,m_linreply, 0, 2
-NOTICE,  m_notice,   0, 2
-LUSERS,  m_lusers,   0, 1
-VOICE,   m_voice,    0, 2
-GRPH,    m_grph,     0, 2
-XTRA,    m_xtra,     0, 2
-MOTD,    m_motd,     0, 2
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/tests/jscript.gperf
--- a/head/contrib/gperf/tests/jscript.gperf	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,73 +0,0 @@
-%{
-/* Command-line: gperf -k'1,2,$' -t -p -K 'name' -H 'js_kw_hash' -N 'js_kw_lookup' -a -g jscript.gperf */
-%}
-struct js_keyword {
-  char * name;
-  int token;
-}
-
-%%
-# Javascript reserved words, see "keywords.html"
-abstract, TK_ABSTRACT
-boolean, TK_BOOLEAN
-break, TK_BREAK
-byte, TK_BYTE
-case, TK_CASE
-catch, TK_CATCH
-char, TK_CHAR
-class, TK_CLASS
-const, TK_CONST
-continue, TK_CONTINUE
-default, TK_DEFAULT
-do, TK_DO
-double, TK_DOUBLE
-else, TK_ELSE
-extends, TK_EXTENDS
-false, TK_FALSE
-final, TK_FINAL
-finally, TK_FINALLY
-float, TK_FLOAT
-for, TK_FOR
-function, TK_FUNCTION
-goto, TK_GOTO
-if, TK_IF
-implements, TK_IMPLEMENTS
-import, TK_IMPORT
-in, TK_IN
-instanceof, TK_INSTANCEOF
-int, TK_INT
-interface, TK_INTERFACE
-long, TK_LONG
-native, TK_NATIVE
-new, TK_NEW
-null, TK_NULL
-package, TK_PACKAGE
-private, TK_PRIVATE
-protected, TK_PROTECTED
-public, TK_PUBLIC
-return, TK_RETURN
-short, TK_SHORT
-static, TK_STATIC
-super, TK_SUPER
-switch, TK_SWITCH
-synchronized, TK_SYNCHRONIZED
-this, TK_THIS
-throw, TK_THROW
-throws, TK_THROWS
-transient, TK_TRANSIENT
-true, TK_TRUE
-try, TK_TRY
-var, TK_VAR
-void, TK_VOID
-while, TK_WHILE
-with, TK_WITH
-%%
-
-int js_keyword_lookup (register const char *str, register int len)
-{
-  struct js_keyword * keyword = js_kw_lookup(str,len);
-  if (keyword)
-    return keyword->token;
-  else
-    return TK_IDENT;
-}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/tests/jstest1.gperf
--- a/head/contrib/gperf/tests/jstest1.gperf	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,142 +0,0 @@
-abstract
-boolean
-break
-byte
-case
-catch
-char
-class
-const
-continue
-default
-do
-double
-else
-extends
-false
-final
-finally
-float
-for
-function
-goto
-if
-implements
-import
-in
-instanceof
-int
-interface
-long
-native
-new
-null
-package
-private
-protected
-public
-return
-short
-static
-super
-switch
-synchronized
-this
-throw
-throws
-transient
-true
-try
-var
-void
-while
-with
-%%
-#include <stdlib.h>
-#include <string.h>
-#if defined(__STDC__) || defined(__cplusplus)
-#define CONST const
-#else
-#define CONST
-#endif
-static CONST char* testdata[] = {
-  "bogus",
-  "abstract",
-  "boolean",
-  "break",
-  "byte",
-  "case",
-  "catch",
-  "char",
-  "class",
-  "const",
-  "continue",
-  "default",
-  "do",
-  "double",
-  "else",
-  "extends",
-  "false",
-  "final",
-  "finally",
-  "float",
-  "for",
-  "function",
-  "goto",
-  "if",
-  "implements",
-  "import",
-  "in",
-  "instanceof",
-  "int",
-  "interface",
-  "long",
-  "native",
-  "new",
-  "null",
-  "package",
-  "private",
-  "protected",
-  "public",
-  "return",
-  "short",
-  "static",
-  "super",
-  "switch",
-  "synchronized",
-  "this",
-  "throw",
-  "throws",
-  "transient",
-  "true",
-  "try",
-  "var",
-  "void",
-  "while",
-  "with"
-};
-int main ()
-{
-  int i;
-  for (i = 0; i < sizeof(testdata)/sizeof(testdata[0]); i++)
-    {
-#ifdef CPLUSPLUS_TEST
-      CONST char * resword = Perfect_Hash::in_word_set(testdata[i],strlen(testdata[i]));
-#else
-      CONST char * resword = in_word_set(testdata[i],strlen(testdata[i]));
-#endif
-      if (i > 0)
-        {
-          if (!resword)
-            exit (1);
-          if (strcmp(testdata[i],resword))
-            exit (1);
-        }
-      else
-        {
-          if (resword)
-            exit (1);
-        }
-    }
-  return 0;
-}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/tests/jstest2.gperf
--- a/head/contrib/gperf/tests/jstest2.gperf	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,147 +0,0 @@
-struct js_keyword {
-  char * name;
-  int token;
-}
-%%
-abstract, 1
-boolean, 2
-break, 3
-byte, 4
-case, 5
-catch, 6
-char, 7
-class, 8
-const, 9
-continue, 10
-default, 11
-do, 12
-double, 13
-else, 14
-extends, 15
-false, 16
-final, 17
-finally, 18
-float, 19
-for, 20
-function, 21
-goto, 22
-if, 23
-implements, 24
-import, 25
-in, 26
-instanceof, 27
-int, 28
-interface, 29
-long, 30
-native, 31
-new, 32
-null, 33
-package, 34
-private, 35
-protected, 36
-public, 37
-return, 38
-short, 39
-static, 40
-super, 41
-switch, 42
-synchronized, 43
-this, 44
-throw, 45
-throws, 46
-transient, 47
-true, 48
-try, 49
-var, 50
-void, 51
-while, 52
-with, 53
-%%
-#include <stdlib.h>
-#include <string.h>
-#if defined(__STDC__) || defined(__cplusplus)
-#define CONST const
-#else
-#define CONST
-#endif
-static CONST char* testdata[] = {
-  "bogus",
-  "abstract",
-  "boolean",
-  "break",
-  "byte",
-  "case",
-  "catch",
-  "char",
-  "class",
-  "const",
-  "continue",
-  "default",
-  "do",
-  "double",
-  "else",
-  "extends",
-  "false",
-  "final",
-  "finally",
-  "float",
-  "for",
-  "function",
-  "goto",
-  "if",
-  "implements",
-  "import",
-  "in",
-  "instanceof",
-  "int",
-  "interface",
-  "long",
-  "native",
-  "new",
-  "null",
-  "package",
-  "private",
-  "protected",
-  "public",
-  "return",
-  "short",
-  "static",
-  "super",
-  "switch",
-  "synchronized",
-  "this",
-  "throw",
-  "throws",
-  "transient",
-  "true",
-  "try",
-  "var",
-  "void",
-  "while",
-  "with"
-};
-int main ()
-{
-  int i;
-  for (i = 0; i < sizeof(testdata)/sizeof(testdata[0]); i++)
-    {
-#ifdef CPLUSPLUS_TEST
-      CONST struct js_keyword * resword = Perfect_Hash::in_word_set(testdata[i],strlen(testdata[i]));
-#else
-      CONST struct js_keyword * resword = in_word_set(testdata[i],strlen(testdata[i]));
-#endif
-      if (i > 0)
-        {
-          if (!resword)
-            exit (1);
-          if (strcmp(testdata[i],resword->name))
-            exit (1);
-        }
-      else
-        {
-          if (resword)
-            exit (1);
-        }
-    }
-  return 0;
-}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/tests/jstest3.gperf
--- a/head/contrib/gperf/tests/jstest3.gperf	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,147 +0,0 @@
-struct js_keyword {
-  const char * name;
-  int token;
-}
-%%
-abstract, 1
-boolean, 2
-break, 3
-byte, 4
-case, 5
-catch, 6
-char, 7
-class, 8
-const, 9
-continue, 10
-default, 11
-do, 12
-double, 13
-else, 14
-extends, 15
-false, 16
-final, 17
-finally, 18
-float, 19
-for, 20
-function, 21
-goto, 22
-if, 23
-implements, 24
-import, 25
-in, 26
-instanceof, 27
-int, 28
-interface, 29
-long, 30
-native, 31
-new, 32
-null, 33
-package, 34
-private, 35
-protected, 36
-public, 37
-return, 38
-short, 39
-static, 40
-super, 41
-switch, 42
-synchronized, 43
-this, 44
-throw, 45
-throws, 46
-transient, 47
-true, 48
-try, 49
-var, 50
-void, 51
-while, 52
-with, 53
-%%
-#include <stdlib.h>
-#include <string.h>
-#if defined(__STDC__) || defined(__cplusplus)
-#define CONST const
-#else
-#define CONST
-#endif
-static CONST char* testdata[] = {
-  "bogus",
-  "abstract",
-  "boolean",
-  "break",
-  "byte",
-  "case",
-  "catch",
-  "char",
-  "class",
-  "const",
-  "continue",
-  "default",
-  "do",
-  "double",
-  "else",
-  "extends",
-  "false",
-  "final",
-  "finally",
-  "float",
-  "for",
-  "function",
-  "goto",
-  "if",
-  "implements",
-  "import",
-  "in",
-  "instanceof",
-  "int",
-  "interface",
-  "long",
-  "native",
-  "new",
-  "null",
-  "package",
-  "private",
-  "protected",
-  "public",
-  "return",
-  "short",
-  "static",
-  "super",
-  "switch",
-  "synchronized",
-  "this",
-  "throw",
-  "throws",
-  "transient",
-  "true",
-  "try",
-  "var",
-  "void",
-  "while",
-  "with"
-};
-int main ()
-{
-  int i;
-  for (i = 0; i < sizeof(testdata)/sizeof(testdata[0]); i++)
-    {
-#ifdef CPLUSPLUS_TEST
-      CONST struct js_keyword * resword = Perfect_Hash::in_word_set(testdata[i],strlen(testdata[i]));
-#else
-      CONST struct js_keyword * resword = in_word_set(testdata[i],strlen(testdata[i]));
-#endif
-      if (i > 0)
-        {
-          if (!resword)
-            exit (1);
-          if (strcmp(testdata[i],resword->name))
-            exit (1);
-        }
-      else
-        {
-          if (resword)
-            exit (1);
-        }
-    }
-  return 0;
-}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/tests/makeinfo.gperf
--- a/head/contrib/gperf/tests/makeinfo.gperf	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,116 +0,0 @@
-COMMAND;
-%%
-!, cm_force_sentence_end, false
-', insert_self, false
-*, cm_asterisk, false
-., cm_force_sentence_end, false
-:, cm_force_abbreviated_whitespace, false
-?, cm_force_sentence_end, false
-@, insert_self, false
-TeX, cm_TeX, true
-`, insert_self, false
-appendix, cm_appendix, false
-appendixsec, cm_appendixsec, false
-appendixsubsec, cm_appendixsubsec, false
-asis, cm_asis, true
-b, cm_bold, true
-br, cm_br, false
-bullet, cm_bullet, true
-bye, cm_bye, false
-c, cm_comment, false
-center, cm_center, false
-chapter, cm_chapter, false
-cindex, cm_cindex, false
-cite, cm_cite, true
-code, cm_code, true
-comment, cm_comment, false
-contents, do_nothing, false
-copyright, cm_copyright, true
-ctrl, cm_ctrl, true
-defcodeindex, cm_defindex, false
-defindex, cm_defindex, false
-dfn, cm_dfn, true
-display, cm_display, false
-dots, cm_dots, true
-emph, cm_emph, true
-end, cm_end, false
-enumerate, cm_enumerate, false
-equiv, cm_equiv, true
-error, cm_error, true
-example, cm_example, false
-exdent, cm_exdent, false
-expansion, cm_expansion, true
-file, cm_file, true
-findex, cm_findex, false
-format, cm_format, false
-group, cm_group, false
-i, cm_italic, true
-iappendix, cm_appendix, false
-iappendixsec, cm_appendixsec, false
-iappendixsubsec, cm_appendixsubsec, false
-ichapter, cm_chapter, false
-ifinfo, cm_ifinfo, false
-iftex, cm_iftex, false
-ignore, cm_ignore, false
-include, cm_include, false
-inforef, cm_inforef, true
-input, cm_include, false
-isection, cm_section, false
-isubsection, cm_subsection, false
-isubsubsection, cm_subsubsection, false
-item, cm_item, false
-itemize, cm_itemize, false
-itemx, cm_itemx, false
-iunnumbered, cm_unnumbered, false
-iunnumberedsec, cm_unnumberedsec, false
-iunnumberedsubsec, cm_unnumberedsubsec, false
-kbd, cm_kbd, true
-key, cm_key, true
-kindex, cm_kindex, false
-lisp, cm_lisp, false
-menu, cm_menu
-minus, cm_minus, true
-need, cm_need, false
-node, cm_node, false
-noindent, cm_noindent, false
-page, do_nothing, false
-pindex, cm_pindex, false
-point, cm_point, true
-print, cm_print, true
-printindex, cm_printindex, false
-pxref, cm_pxref, true
-quotation, cm_quotation, false
-r, cm_roman, true
-ref, cm_xref, true
-refill, cm_refill, false
-result, cm_result, true
-samp, cm_samp, true
-sc, cm_sc, true
-section, cm_section, false
-setchapternewpage, cm_setchapternewpage, false
-setfilename, cm_setfilename, false
-settitle, cm_settitle, false
-smallexample, cm_smallexample, false
-sp, cm_sp, false
-strong, cm_strong, true
-subsection, cm_subsection, false
-subsubsection, cm_subsubsection, false
-summarycontents, do_nothing, false
-syncodeindex, cm_synindex, false
-synindex, cm_synindex, false
-t, cm_title, true
-table, cm_table, false
-tex, cm_tex, false
-tindex, cm_tindex, false
-titlepage, cm_titlepage, false
-unnumbered, cm_unnumbered, false
-unnumberedsec, cm_unnumberedsec, false
-unnumberedsubsec, cm_unnumberedsubsec, false
-var, cm_var, true
-vindex, cm_vindex, false
-w, cm_w, true
-xref, cm_xref, true
-{, insert_self, false
-}, insert_self, false
-infoinclude, cm_infoinclude, false
-footnote, cm_footnote, false
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/tests/modula.exp
--- a/head/contrib/gperf/tests/modula.exp	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,106 +0,0 @@
-in word set AND
-in word set ARRAY
-in word set BEGIN
-in word set BITS
-in word set BY
-in word set CASE
-in word set CONST
-in word set DIV
-in word set DO
-in word set ELSE
-in word set ELSIF
-in word set END
-in word set EVAL
-in word set EXCEPT
-in word set EXCEPTION
-in word set EXIT
-in word set EXPORTS
-in word set FINALLY
-in word set FOR
-in word set FROM
-in word set IF
-in word set IMPORT
-in word set INTERFACE
-in word set IN
-in word set INLINE
-in word set LOCK
-in word set METHODS
-in word set MOD
-in word set MODULE
-in word set NOT
-in word set OBJECT
-in word set OF
-in word set OR
-in word set PROCEDURE
-in word set RAISES
-in word set READONLY
-in word set RECORD
-in word set REF
-in word set REPEAT
-in word set RETURN
-in word set SET
-in word set THEN
-in word set TO
-in word set TRY
-in word set TYPE
-in word set TYPECASE
-in word set UNSAFE
-in word set UNTIL
-in word set UNTRACED
-in word set VALUE
-in word set VAR
-in word set WHILE
-in word set WITH
-in word set and
-in word set array
-in word set begin
-in word set bits
-in word set by
-in word set case
-in word set const
-in word set div
-in word set do
-in word set else
-in word set elsif
-in word set end
-in word set eval
-in word set except
-in word set exception
-in word set exit
-in word set exports
-in word set finally
-in word set for
-in word set from
-in word set if
-in word set import
-in word set interface
-in word set in
-in word set inline
-in word set lock
-in word set methods
-in word set mod
-in word set module
-in word set not
-in word set object
-in word set of
-in word set or
-in word set procedure
-in word set raises
-in word set readonly
-in word set record
-in word set ref
-in word set repeat
-in word set return
-in word set set
-in word set then
-in word set to
-in word set try
-in word set type
-in word set typecase
-in word set unsafe
-in word set until
-in word set untraced
-in word set value
-in word set var
-in word set while
-in word set with
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/tests/modula2.gperf
--- a/head/contrib/gperf/tests/modula2.gperf	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,40 +0,0 @@
-AND
-ARRAY
-BEGIN
-BY
-CASE
-CONST
-DEFINITION
-DIV
-DO
-ELSE
-ELSIF
-END
-EXIT
-EXPORT
-FOR
-FROM
-IF
-IMPLEMENTATION
-IMPORT
-IN
-LOOP
-MOD
-MODULE
-NOT
-OF
-OR
-POINTER
-PROCEDURE
-QUALIFIED
-RECORD
-REPEAT
-RETURN
-SET
-THEN
-TO
-TYPE
-UNTIL
-VAR
-WHILE
-WITH
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/tests/modula3.gperf
--- a/head/contrib/gperf/tests/modula3.gperf	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,106 +0,0 @@
-AND
-ARRAY
-BEGIN
-BITS
-BY
-CASE
-CONST
-DIV
-DO
-ELSE
-ELSIF
-END
-EVAL
-EXCEPT
-EXCEPTION
-EXIT
-EXPORTS
-FINALLY
-FOR
-FROM
-IF
-IMPORT
-INTERFACE
-IN
-INLINE
-LOCK
-METHODS
-MOD
-MODULE
-NOT
-OBJECT
-OF
-OR
-PROCEDURE
-RAISES
-READONLY
-RECORD
-REF
-REPEAT
-RETURN
-SET
-THEN
-TO
-TRY
-TYPE
-TYPECASE
-UNSAFE
-UNTIL
-UNTRACED
-VALUE
-VAR
-WHILE
-WITH
-and
-array
-begin
-bits
-by
-case
-const
-div
-do
-else
-elsif
-end
-eval
-except
-exception
-exit
-exports
-finally
-for
-from
-if
-import
-interface
-in
-inline
-lock
-methods
-mod
-module
-not
-object
-of
-or
-procedure
-raises
-readonly
-record
-ref
-repeat
-return
-set
-then
-to
-try
-type
-typecase
-unsafe
-until
-untraced
-value
-var
-while
-with
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/tests/pascal.exp
--- a/head/contrib/gperf/tests/pascal.exp	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,36 +0,0 @@
-in word set with
-in word set array
-in word set and
-in word set function
-in word set case
-in word set var
-in word set const
-in word set until
-in word set then
-in word set set
-in word set record
-in word set program
-in word set procedure
-in word set or
-in word set packed
-in word set not
-in word set nil
-in word set label
-in word set in
-in word set repeat
-in word set of
-in word set goto
-in word set forward
-in word set for
-in word set while
-in word set file
-in word set else
-in word set downto
-in word set do
-in word set div
-in word set to
-in word set type
-in word set end
-in word set mod
-in word set begin
-in word set if
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/tests/pascal.gperf
--- a/head/contrib/gperf/tests/pascal.gperf	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,36 +0,0 @@
-with
-array
-and
-function
-case
-var
-const
-until
-then
-set
-record
-program
-procedure
-or
-packed
-not
-nil
-label
-in
-repeat
-of
-goto
-forward
-for
-while
-file
-else
-downto
-do
-div
-to
-type
-end
-mod
-begin
-if
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/tests/test-1.exp
--- a/head/contrib/gperf/tests/test-1.exp	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,153 +0,0 @@
-/* C code produced by gperf version 2.7 */
-/* Command-line: ../src/gperf -p -j1 -g -o -t -N is_reserved_word -k1,3,$  */
-/* Command-line: gperf -p -j1 -i 1 -g -o -t -N is_reserved_word -k1,3,$ c-parse.gperf  */
-struct resword { char *name; short token; enum rid rid; };
-
-#define TOTAL_KEYWORDS 51
-#define MIN_WORD_LENGTH 2
-#define MAX_WORD_LENGTH 13
-#define MIN_HASH_VALUE 8
-#define MAX_HASH_VALUE 82
-/* maximum key range = 75, duplicates = 0 */
-
-#ifdef __GNUC__
-__inline
-#endif
-static unsigned int
-hash (str, len)
-     register const char *str;
-     register unsigned int len;
-{
-  static unsigned char asso_values[] =
-    {
-      83, 83, 83, 83, 83, 83, 83, 83, 83, 83,
-      83, 83, 83, 83, 83, 83, 83, 83, 83, 83,
-      83, 83, 83, 83, 83, 83, 83, 83, 83, 83,
-      83, 83, 83, 83, 83, 83, 83, 83, 83, 83,
-      83, 83, 83, 83, 83, 83, 83, 83, 83, 83,
-      83, 83, 83, 83, 83, 83, 83, 83, 83, 83,
-      83, 83, 83, 83, 83, 83, 83, 83, 83, 83,
-      83, 83, 83, 83, 83, 83, 83, 83, 83, 83,
-      83, 83, 83, 83, 83, 83, 83, 83, 83, 83,
-      83, 83, 83, 83, 83,  0, 83,  1,  2, 34,
-      19,  6, 11, 29,  0, 17, 83,  0, 23, 28,
-      26, 30, 31, 83, 15,  1,  0, 28, 13,  4,
-      83, 83,  5, 83, 83, 83, 83, 83, 83, 83,
-      83, 83, 83, 83, 83, 83, 83, 83, 83, 83,
-      83, 83, 83, 83, 83, 83, 83, 83, 83, 83,
-      83, 83, 83, 83, 83, 83, 83, 83, 83, 83,
-      83, 83, 83, 83, 83, 83, 83, 83, 83, 83,
-      83, 83, 83, 83, 83, 83, 83, 83, 83, 83,
-      83, 83, 83, 83, 83, 83, 83, 83, 83, 83,
-      83, 83, 83, 83, 83, 83, 83, 83, 83, 83,
-      83, 83, 83, 83, 83, 83, 83, 83, 83, 83,
-      83, 83, 83, 83, 83, 83, 83, 83, 83, 83,
-      83, 83, 83, 83, 83, 83, 83, 83, 83, 83,
-      83, 83, 83, 83, 83, 83, 83, 83, 83, 83,
-      83, 83, 83, 83, 83, 83, 83, 83, 83, 83,
-      83, 83, 83, 83, 83, 83
-    };
-  register int hval = len;
-
-  switch (hval)
-    {
-      default:
-      case 3:
-        hval += asso_values[(unsigned char)str[2]];
-      case 2:
-      case 1:
-        hval += asso_values[(unsigned char)str[0]];
-        break;
-    }
-  return hval + asso_values[(unsigned char)str[len - 1]];
-}
-
-#ifdef __GNUC__
-__inline
-#endif
-struct resword *
-is_reserved_word (str, len)
-     register const char *str;
-     register unsigned int len;
-{
-  static struct resword wordlist[] =
-    {
-      {""}, {""}, {""}, {""}, {""}, {""}, {""}, {""},
-      {"__asm__", ASM, NORID},
-      {""},
-      {"__typeof__", TYPEOF, NORID},
-      {"__signed__", TYPESPEC, RID_SIGNED},
-      {"__alignof__", ALIGNOF, NORID},
-      {"break", BREAK, NORID},
-      {"__attribute__", ATTRIBUTE, NORID},
-      {""}, {""},
-      {"else", ELSE, NORID},
-      {"__attribute", ATTRIBUTE, NORID},
-      {"__typeof", TYPEOF, NORID},
-      {"int", TYPESPEC, RID_INT},
-      {"__alignof", ALIGNOF, NORID},
-      {"struct", STRUCT, NORID},
-      {"sizeof", SIZEOF, NORID},
-      {"switch", SWITCH, NORID},
-      {"__volatile__", TYPE_QUAL, RID_VOLATILE},
-      {""},
-      {"__inline__", SCSPEC, RID_INLINE},
-      {"__signed", TYPESPEC, RID_SIGNED},
-      {"__volatile", TYPE_QUAL, RID_VOLATILE},
-      {"if", IF, NORID},
-      {"__inline", SCSPEC, RID_INLINE},
-      {"while", WHILE, NORID},
-      {""},
-      {"__asm", ASM, NORID},
-      {"auto", SCSPEC, RID_AUTO},
-      {"short", TYPESPEC, RID_SHORT},
-      {"default", DEFAULT, NORID},
-      {"extern", SCSPEC, RID_EXTERN},
-      {""}, {""},
-      {"__const", TYPE_QUAL, RID_CONST},
-      {"static", SCSPEC, RID_STATIC},
-      {"__const__", TYPE_QUAL, RID_CONST},
-      {"for", FOR, NORID},
-      {"case", CASE, NORID},
-      {"float", TYPESPEC, RID_FLOAT},
-      {"return", RETURN, NORID},
-      {"typeof", TYPEOF, NORID},
-      {"typedef", SCSPEC, RID_TYPEDEF},
-      {"volatile", TYPE_QUAL, RID_VOLATILE},
-      {"do", DO, NORID},
-      {"inline", SCSPEC, RID_INLINE},
-      {"void", TYPESPEC, RID_VOID},
-      {"char", TYPESPEC, RID_CHAR},
-      {"signed", TYPESPEC, RID_SIGNED},
-      {"unsigned", TYPESPEC, RID_UNSIGNED},
-      {""}, {""},
-      {"double", TYPESPEC, RID_DOUBLE},
-      {"asm", ASM, NORID},
-      {""}, {""},
-      {"goto", GOTO, NORID},
-      {""},
-      {"const", TYPE_QUAL, RID_CONST},
-      {"enum", ENUM, NORID},
-      {"register", SCSPEC, RID_REGISTER},
-      {""}, {""}, {""}, {""}, {""}, {""},
-      {"continue", CONTINUE, NORID},
-      {""},
-      {"union", UNION, NORID},
-      {""}, {""}, {""}, {""}, {""},
-      {"long", TYPESPEC, RID_LONG}
-    };
-
-  if (len <= MAX_WORD_LENGTH && len >= MIN_WORD_LENGTH)
-    {
-      register int key = hash (str, len);
-
-      if (key <= MAX_HASH_VALUE && key >= 0)
-        {
-          register const char *s = wordlist[key].name;
-
-          if (*str == *s && !strcmp (str + 1, s + 1))
-            return &wordlist[key];
-        }
-    }
-  return 0;
-}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/tests/test-2.exp
--- a/head/contrib/gperf/tests/test-2.exp	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,202 +0,0 @@
-/* C code produced by gperf version 2.7 */
-/* Command-line: ../src/gperf -n -k1-8 -l  */
-
-#define TOTAL_KEYWORDS 40
-#define MIN_WORD_LENGTH 2
-#define MAX_WORD_LENGTH 14
-#define MIN_HASH_VALUE 1
-#define MAX_HASH_VALUE 256
-/* maximum key range = 256, duplicates = 0 */
-
-#ifdef __GNUC__
-__inline
-#endif
-static unsigned int
-hash (str, len)
-     register const char *str;
-     register unsigned int len;
-{
-  static unsigned short asso_values[] =
-    {
-      257, 257, 257, 257, 257, 257, 257, 257, 257, 257,
-      257, 257, 257, 257, 257, 257, 257, 257, 257, 257,
-      257, 257, 257, 257, 257, 257, 257, 257, 257, 257,
-      257, 257, 257, 257, 257, 257, 257, 257, 257, 257,
-      257, 257, 257, 257, 257, 257, 257, 257, 257, 257,
-      257, 257, 257, 257, 257, 257, 257, 257, 257, 257,
-      257, 257, 257, 257, 257,  25,  30,  35,  21,   0,
-       30,  15,  30,  45, 257, 257,   0,   5,  45,   0,
-       10,   0,   1,  20,  25,  15,  30,  40,  15,   5,
-      257, 257, 257, 257, 257, 257, 257, 257, 257, 257,
-      257, 257, 257, 257, 257, 257, 257, 257, 257, 257,
-      257, 257, 257, 257, 257, 257, 257, 257, 257, 257,
-      257, 257, 257, 257, 257, 257, 257, 257, 257, 257,
-      257, 257, 257, 257, 257, 257, 257, 257, 257, 257,
-      257, 257, 257, 257, 257, 257, 257, 257, 257, 257,
-      257, 257, 257, 257, 257, 257, 257, 257, 257, 257,
-      257, 257, 257, 257, 257, 257, 257, 257, 257, 257,
-      257, 257, 257, 257, 257, 257, 257, 257, 257, 257,
-      257, 257, 257, 257, 257, 257, 257, 257, 257, 257,
-      257, 257, 257, 257, 257, 257, 257, 257, 257, 257,
-      257, 257, 257, 257, 257, 257, 257, 257, 257, 257,
-      257, 257, 257, 257, 257, 257, 257, 257, 257, 257,
-      257, 257, 257, 257, 257, 257, 257, 257, 257, 257,
-      257, 257, 257, 257, 257, 257, 257, 257, 257, 257,
-      257, 257, 257, 257, 257, 257, 257, 257, 257, 257,
-      257, 257, 257, 257, 257, 257
-    };
-  register int hval = 0;
-
-  switch (len)
-    {
-      default:
-      case 8:
-        hval += asso_values[(unsigned char)str[7]];
-      case 7:
-        hval += asso_values[(unsigned char)str[6]];
-      case 6:
-        hval += asso_values[(unsigned char)str[5]];
-      case 5:
-        hval += asso_values[(unsigned char)str[4]];
-      case 4:
-        hval += asso_values[(unsigned char)str[3]];
-      case 3:
-        hval += asso_values[(unsigned char)str[2]];
-      case 2:
-        hval += asso_values[(unsigned char)str[1]];
-      case 1:
-        hval += asso_values[(unsigned char)str[0]];
-        break;
-    }
-  return hval;
-}
-
-#ifdef __GNUC__
-__inline
-#endif
-const char *
-in_word_set (str, len)
-     register const char *str;
-     register unsigned int len;
-{
-  static unsigned char lengthtable[] =
-    {
-       0,  2,  0,  0,  0,  0,  0,  0,  0,  0,  4,  0,  0,  0,
-       0,  0,  0,  0,  0,  0,  4,  2,  0,  0,  0,  2,  3,  0,
-       0,  0,  2,  3,  0,  0,  0,  2,  4,  0,  0,  0,  4,  6,
-       0,  0,  0,  3,  0,  0,  0,  0,  0,  6,  0,  0,  0,  0,
-       3,  5,  6,  0,  0,  6,  0,  0,  0,  0,  3,  0,  0,  0,
-       3,  0,  0,  0,  0,  2,  0,  0,  0,  0,  4,  0,  0,  9,
-       0,  4,  6,  6,  0,  0,  2,  3,  0,  0,  0,  5,  3,  0,
-       0,  0,  4,  0,  0,  0,  0,  0,  0,  0,  0,  0, 14,  0,
-       0,  0,  0,  5,  0,  0,  0,  0,  0,  0,  0,  0,  0,  5,
-       7,  0,  0,  0,  5,  0,  0,  0,  0,  5,  0,  0,  0,  0,
-       4,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
-       0,  0,  0,  0,  0,  0,  9,  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,  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,  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,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
-       0,  0,  0,  0, 10
-    };
-  static const char * wordlist[] =
-    {
-      "",
-      "OR",
-      "", "", "", "", "", "", "", "",
-      "LOOP",
-      "", "", "", "", "", "", "", "", "",
-      "ELSE",
-      "DO",
-      "", "", "",
-      "TO",
-      "MOD",
-      "", "", "",
-      "OF",
-      "FOR",
-      "", "", "",
-      "BY",
-      "FROM",
-      "", "", "",
-      "TYPE",
-      "MODULE",
-      "", "", "",
-      "SET",
-      "", "", "", "", "",
-      "EXPORT",
-      "", "", "", "",
-      "VAR",
-      "ARRAY",
-      "RECORD",
-      "", "",
-      "REPEAT",
-      "", "", "", "",
-      "END",
-      "", "", "",
-      "NOT",
-      "", "", "", "",
-      "IF",
-      "", "", "", "",
-      "CASE",
-      "", "",
-      "PROCEDURE",
-      "",
-      "EXIT",
-      "IMPORT",
-      "RETURN",
-      "", "",
-      "IN",
-      "AND",
-      "", "", "",
-      "ELSIF",
-      "DIV",
-      "", "", "",
-      "THEN",
-      "", "", "", "", "", "", "", "", "",
-      "IMPLEMENTATION",
-      "", "", "", "",
-      "WHILE",
-      "", "", "", "", "", "", "", "", "",
-      "CONST",
-      "POINTER",
-      "", "", "",
-      "UNTIL",
-      "", "", "", "",
-      "BEGIN",
-      "", "", "", "",
-      "WITH",
-      "", "", "", "", "", "", "", "", "",
-      "", "", "", "", "", "", "", "", "",
-      "",
-      "QUALIFIED",
-      "", "", "", "", "", "", "", "", "",
-      "", "", "", "", "", "", "", "", "",
-      "", "", "", "", "", "", "", "", "",
-      "", "", "", "", "", "", "", "", "",
-      "", "", "", "", "", "", "", "", "",
-      "", "", "", "", "", "", "", "", "",
-      "", "", "", "", "", "", "", "", "",
-      "", "", "", "", "", "", "", "", "",
-      "", "", "", "", "", "", "", "", "",
-      "", "", "", "", "", "", "", "", "",
-      "", "", "", "", "",
-      "DEFINITION"
-    };
-
-  if (len <= MAX_WORD_LENGTH && len >= MIN_WORD_LENGTH)
-    {
-      register int key = hash (str, len);
-
-      if (key <= MAX_HASH_VALUE && key >= 0)
-        if (len == lengthtable[key])
-          {
-            register const char *s = wordlist[key];
-
-            if (*str == *s && !strcmp (str + 1, s + 1))
-              return s;
-          }
-    }
-  return 0;
-}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/tests/test-3.exp
--- a/head/contrib/gperf/tests/test-3.exp	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,186 +0,0 @@
-/* C code produced by gperf version 2.7 */
-/* Command-line: ../src/gperf -p -j 1 -o -a -C -g -t -k1,4,$  */
-/* Command-line: gperf -p -j1 -g -o -t -N is_reserved_word -k1,4,$ gplus.gperf  */
-struct resword { char *name; short token; enum rid rid;};
-
-#define TOTAL_KEYWORDS 71
-#define MIN_WORD_LENGTH 2
-#define MAX_WORD_LENGTH 13
-#define MIN_HASH_VALUE 4
-#define MAX_HASH_VALUE 147
-/* maximum key range = 144, duplicates = 0 */
-
-#ifdef __GNUC__
-__inline
-#endif
-static unsigned int
-hash (str, len)
-     register const char *str;
-     register unsigned int len;
-{
-  static const unsigned char asso_values[] =
-    {
-      148, 148, 148, 148, 148, 148, 148, 148, 148, 148,
-      148, 148, 148, 148, 148, 148, 148, 148, 148, 148,
-      148, 148, 148, 148, 148, 148, 148, 148, 148, 148,
-      148, 148, 148, 148, 148, 148, 148, 148, 148, 148,
-      148, 148, 148, 148, 148, 148, 148, 148, 148, 148,
-      148, 148, 148, 148, 148, 148, 148, 148, 148, 148,
-      148, 148, 148, 148, 148, 148, 148, 148, 148, 148,
-      148, 148, 148, 148, 148, 148, 148, 148, 148, 148,
-      148, 148, 148, 148, 148, 148, 148, 148, 148, 148,
-      148, 148, 148, 148, 148,   0, 148,  19,   6,  27,
-       37,   0,  12,   1,  15,  63, 148,   4,   0,  56,
-       20,  15,  42, 148,  31,   5,  26,  39,  32,  10,
-      148,  40, 148, 148, 148, 148, 148, 148, 148, 148,
-      148, 148, 148, 148, 148, 148, 148, 148, 148, 148,
-      148, 148, 148, 148, 148, 148, 148, 148, 148, 148,
-      148, 148, 148, 148, 148, 148, 148, 148, 148, 148,
-      148, 148, 148, 148, 148, 148, 148, 148, 148, 148,
-      148, 148, 148, 148, 148, 148, 148, 148, 148, 148,
-      148, 148, 148, 148, 148, 148, 148, 148, 148, 148,
-      148, 148, 148, 148, 148, 148, 148, 148, 148, 148,
-      148, 148, 148, 148, 148, 148, 148, 148, 148, 148,
-      148, 148, 148, 148, 148, 148, 148, 148, 148, 148,
-      148, 148, 148, 148, 148, 148, 148, 148, 148, 148,
-      148, 148, 148, 148, 148, 148, 148, 148, 148, 148,
-      148, 148, 148, 148, 148, 148, 148, 148, 148, 148,
-      148, 148, 148, 148, 148, 148
-    };
-  register int hval = len;
-
-  switch (hval)
-    {
-      default:
-      case 4:
-        hval += asso_values[(unsigned char)str[3]];
-      case 3:
-      case 2:
-      case 1:
-        hval += asso_values[(unsigned char)str[0]];
-        break;
-    }
-  return hval + asso_values[(unsigned char)str[len - 1]];
-}
-
-#ifdef __GNUC__
-__inline
-#endif
-const struct resword *
-in_word_set (str, len)
-     register const char *str;
-     register unsigned int len;
-{
-  static const struct resword wordlist[] =
-    {
-      {""}, {""}, {""}, {""},
-      {"else", ELSE, NORID,},
-      {""},
-      {"long", TYPESPEC, RID_LONG,},
-      {""}, {""}, {""}, {""},
-      {"__alignof__", ALIGNOF, NORID},
-      {"__asm__", ASM, NORID},
-      {""}, {""},
-      {"while", WHILE, NORID,},
-      {""}, {""}, {""}, {""}, {""},
-      {"__alignof", ALIGNOF, NORID},
-      {"all", ALL, NORID			/* Extension */,},
-      {"sizeof", SIZEOF, NORID,},
-      {"__const__", TYPE_QUAL, RID_CONST},
-      {"__volatile", TYPE_QUAL, RID_VOLATILE},
-      {"extern", SCSPEC, RID_EXTERN,},
-      {"__volatile__", TYPE_QUAL, RID_VOLATILE},
-      {"__inline", SCSPEC, RID_INLINE},
-      {"exception", AGGR, RID_EXCEPTION	/* Extension */,},
-      {"__inline__", SCSPEC, RID_INLINE},
-      {"case", CASE, NORID,},
-      {"except", EXCEPT, NORID		/* Extension */,},
-      {"new", NEW, NORID,},
-      {"break", BREAK, NORID,},
-      {"goto", GOTO, NORID,},
-      {""},
-      {"__attribute", ATTRIBUTE, NORID},
-      {""},
-      {"__attribute__", ATTRIBUTE, NORID},
-      {"this", THIS, NORID,},
-      {"raise", RAISE, NORID		/* Extension */,},
-      {"class", AGGR, RID_CLASS,},
-      {"delete", DELETE, NORID,},
-      {"typeof", TYPEOF, NORID,},
-      {"typedef", SCSPEC, RID_TYPEDEF,},
-      {"for", FOR, NORID,},
-      {"raises", RAISES, NORID		/* Extension */,},
-      {"__const", TYPE_QUAL, RID_CONST},
-      {"double", TYPESPEC, RID_DOUBLE,},
-      {"__typeof__", TYPEOF, NORID},
-      {""},
-      {"switch", SWITCH, NORID,},
-      {"auto", SCSPEC, RID_AUTO,},
-      {"do", DO, NORID,},
-      {"friend", SCSPEC, RID_FRIEND,},
-      {""},
-      {"reraise", RERAISE, NORID		/* Extension */,},
-      {""},
-      {"volatile", TYPE_QUAL, RID_VOLATILE,},
-      {"__typeof", TYPEOF, NORID},
-      {"continue", CONTINUE, NORID,},
-      {"float", TYPESPEC, RID_FLOAT,},
-      {"const", TYPE_QUAL, RID_CONST,},
-      {"static", SCSPEC, RID_STATIC,},
-      {"virtual", SCSPEC, RID_VIRTUAL,},
-      {"__asm", ASM, NORID},
-      {"short", TYPESPEC, RID_SHORT,},
-      {"signed", TYPESPEC, RID_SIGNED,},
-      {"try", TRY, NORID			/* Extension */,},
-      {""}, {""}, {""},
-      {"__signed__", TYPESPEC, RID_SIGNED},
-      {"catch", CATCH, NORID,},
-      {"public", PUBLIC, NORID,},
-      {"struct", AGGR, RID_RECORD,},
-      {"if", IF, NORID,},
-      {"asm", ASM, NORID,},
-      {"union", AGGR, RID_UNION,},
-      {""},
-      {"private", PRIVATE, NORID,},
-      {""}, {""}, {""},
-      {"operator", OPERATOR, NORID,},
-      {""}, {""}, {""},
-      {"default", DEFAULT, NORID,},
-      {"dynamic", DYNAMIC, NORID,},
-      {"overload", OVERLOAD, NORID,},
-      {"int", TYPESPEC, RID_INT,},
-      {"char", TYPESPEC, RID_CHAR,},
-      {""}, {""},
-      {"return", RETURN, NORID,},
-      {""}, {""}, {""}, {""}, {""}, {""}, {""}, {""}, {""},
-      {""}, {""},
-      {"__signed", TYPESPEC, RID_SIGNED},
-      {""},
-      {"void", TYPESPEC, RID_VOID,},
-      {""}, {""}, {""},
-      {"protected", PROTECTED, NORID,},
-      {""},
-      {"enum", ENUM, NORID,},
-      {""}, {""}, {""}, {""}, {""}, {""}, {""}, {""}, {""},
-      {""}, {""}, {""}, {""}, {""}, {""},
-      {"inline", SCSPEC, RID_INLINE,},
-      {"register", SCSPEC, RID_REGISTER,},
-      {""}, {""}, {""}, {""}, {""}, {""}, {""}, {""}, {""},
-      {""}, {""}, {""}, {""},
-      {"unsigned", TYPESPEC, RID_UNSIGNED,}
-    };
-
-  if (len <= MAX_WORD_LENGTH && len >= MIN_WORD_LENGTH)
-    {
-      register int key = hash (str, len);
-
-      if (key <= MAX_HASH_VALUE && key >= 0)
-        {
-          register const char *s = wordlist[key].name;
-
-          if (*str == *s && !strcmp (str + 1, s + 1))
-            return &wordlist[key];
-        }
-    }
-  return 0;
-}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/tests/test-4.exp
--- a/head/contrib/gperf/tests/test-4.exp	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,162 +0,0 @@
-/* C code produced by gperf version 2.7 */
-/* Command-line: ../src/gperf -D -p -t  */
-/* Command-line: gperf -p -j1 -i 1 -g -o -t -N is_reserved_word -k1,3,$ c-parse.gperf  */
-struct resword { char *name; short token; enum rid rid; };
-
-#define TOTAL_KEYWORDS 51
-#define MIN_WORD_LENGTH 2
-#define MAX_WORD_LENGTH 13
-#define MIN_HASH_VALUE 4
-#define MAX_HASH_VALUE 82
-/* maximum key range = 79, duplicates = 2 */
-
-#ifdef __GNUC__
-__inline
-#endif
-static unsigned int
-hash (str, len)
-     register const char *str;
-     register unsigned int len;
-{
-  static unsigned char asso_values[] =
-    {
-      83, 83, 83, 83, 83, 83, 83, 83, 83, 83,
-      83, 83, 83, 83, 83, 83, 83, 83, 83, 83,
-      83, 83, 83, 83, 83, 83, 83, 83, 83, 83,
-      83, 83, 83, 83, 83, 83, 83, 83, 83, 83,
-      83, 83, 83, 83, 83, 83, 83, 83, 83, 83,
-      83, 83, 83, 83, 83, 83, 83, 83, 83, 83,
-      83, 83, 83, 83, 83, 83, 83, 83, 83, 83,
-      83, 83, 83, 83, 83, 83, 83, 83, 83, 83,
-      83, 83, 83, 83, 83, 83, 83, 83, 83, 83,
-      83, 83, 83, 83, 83,  0, 83, 40, 20, 50,
-      25, 10, 30,  0,  0, 50, 83,  0, 15,  0,
-      35,  0, 83, 83, 20,  0, 10, 40,  5, 15,
-      83, 83, 83, 83, 83, 83, 83, 83, 83, 83,
-      83, 83, 83, 83, 83, 83, 83, 83, 83, 83,
-      83, 83, 83, 83, 83, 83, 83, 83, 83, 83,
-      83, 83, 83, 83, 83, 83, 83, 83, 83, 83,
-      83, 83, 83, 83, 83, 83, 83, 83, 83, 83,
-      83, 83, 83, 83, 83, 83, 83, 83, 83, 83,
-      83, 83, 83, 83, 83, 83, 83, 83, 83, 83,
-      83, 83, 83, 83, 83, 83, 83, 83, 83, 83,
-      83, 83, 83, 83, 83, 83, 83, 83, 83, 83,
-      83, 83, 83, 83, 83, 83, 83, 83, 83, 83,
-      83, 83, 83, 83, 83, 83, 83, 83, 83, 83,
-      83, 83, 83, 83, 83, 83, 83, 83, 83, 83,
-      83, 83, 83, 83, 83, 83, 83, 83, 83, 83,
-      83, 83, 83, 83, 83, 83
-    };
-  return len + asso_values[(unsigned char)str[len - 1]] + asso_values[(unsigned char)str[0]];
-}
-
-#ifdef __GNUC__
-__inline
-#endif
-struct resword *
-in_word_set (str, len)
-     register const char *str;
-     register unsigned int len;
-{
-  static struct resword wordlist[] =
-    {
-      {"goto", GOTO, NORID},
-      {"__asm", ASM, NORID},
-      {"switch", SWITCH, NORID},
-      {"__asm__", ASM, NORID},
-      {"__const__", TYPE_QUAL, RID_CONST},
-      {"__inline__", SCSPEC, RID_INLINE},
-      {"__typeof__", TYPEOF, NORID},
-      {"__signed__", TYPESPEC, RID_SIGNED},
-      {"__alignof__", ALIGNOF, NORID},
-      {"__volatile__", TYPE_QUAL, RID_VOLATILE},
-      {"__attribute__", ATTRIBUTE, NORID},
-      {"enum", ENUM, NORID},
-      {"short", TYPESPEC, RID_SHORT},
-      {"struct", STRUCT, NORID},
-      {"__const", TYPE_QUAL, RID_CONST},
-      {"__inline", SCSPEC, RID_INLINE},
-      {"long", TYPESPEC, RID_LONG},
-      {"__volatile", TYPE_QUAL, RID_VOLATILE},
-      {"__attribute", ATTRIBUTE, NORID},
-      {"volatile", TYPE_QUAL, RID_VOLATILE},
-      {"else", ELSE, NORID},
-      {"break", BREAK, NORID},
-      {"do", DO, NORID},
-      {"while", WHILE, NORID},
-      {"signed", TYPESPEC, RID_SIGNED},
-      {"__signed", TYPESPEC, RID_SIGNED},
-      {"void", TYPESPEC, RID_VOID},
-      {"sizeof", SIZEOF, NORID},
-      {"__typeof", TYPEOF, NORID},
-      {"__alignof", ALIGNOF, NORID},
-      {"double", TYPESPEC, RID_DOUBLE},
-      {"default", DEFAULT, NORID},
-      {"asm", ASM, NORID},
-      {"auto", SCSPEC, RID_AUTO},
-      {"float", TYPESPEC, RID_FLOAT},
-      {"typeof", TYPEOF, NORID},
-      {"typedef", SCSPEC, RID_TYPEDEF},
-      {"register", SCSPEC, RID_REGISTER},
-      {"extern", SCSPEC, RID_EXTERN},
-      {"for", FOR, NORID},
-      {"static", SCSPEC, RID_STATIC},
-      {"return", RETURN, NORID},
-      {"int", TYPESPEC, RID_INT},
-      {"case", CASE, NORID},
-      {"const", TYPE_QUAL, RID_CONST},
-      {"inline", SCSPEC, RID_INLINE},
-      {"continue", CONTINUE, NORID},
-      {"unsigned", TYPESPEC, RID_UNSIGNED},
-      {"char", TYPESPEC, RID_CHAR},
-      {"union", UNION, NORID},
-      {"if", IF, NORID}
-    };
-
-  static short lookup[] =
-    {
-       -1,  -1,  -1,  -1,   0,   1,   2,   3,  -1,   4,
-      -80,   8,   9,  10,  11,  12,  13,  14,  15,  16,
-       17,  18,  -1,  19,  20,  21,  -1,  22, -46,  -3,
-       23,  24,  -1,  25,  26,  -1,  27,  -1,  28,  29,
-       -1,  30,  31,  32,  33,  34,  35,  36,  37,  -1,
-       -1,  38,  -1,  39,  -1,  -1,  40,  -1,  -1,  -1,
-       -1,  41,  -1,  42,  43,  44,  45,  -1,  46,  -1,
-       -1,  -1,  -1,  47,  48,  -1,  -1,  -1,  -1,  -1,
-       49,  -1,  50
-    };
-
-  if (len <= MAX_WORD_LENGTH && len >= MIN_WORD_LENGTH)
-    {
-      register int key = hash (str, len);
-
-      if (key <= MAX_HASH_VALUE && key >= 0)
-        {
-          register int index = lookup[key];
-
-          if (index >= 0)
-            {
-              register const char *s = wordlist[index].name;
-
-              if (*str == *s && !strcmp (str + 1, s + 1))
-                return &wordlist[index];
-            }
-          else if (index < -TOTAL_KEYWORDS)
-            {
-              register int offset = - 1 - TOTAL_KEYWORDS - index;
-              register struct resword *wordptr = &wordlist[TOTAL_KEYWORDS + lookup[offset]];
-              register struct resword *wordendptr = wordptr + -lookup[offset + 1];
-
-              while (wordptr < wordendptr)
-                {
-                  register const char *s = wordptr->name;
-
-                  if (*str == *s && !strcmp (str + 1, s + 1))
-                    return wordptr;
-                  wordptr++;
-                }
-            }
-        }
-    }
-  return 0;
-}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/tests/test-5.exp
--- a/head/contrib/gperf/tests/test-5.exp	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,124 +0,0 @@
-/* C code produced by gperf version 2.7 */
-/* Command-line: ../src/gperf -g -o -j1 -t -p -N is_reserved_word  */
-/* ISO Pascal 7185 reserved words.
- *
- * For GNU Pascal compiler (GPC) by jtv at hut.fi
- *
- * run this through the Doug Schmidt's gperf program
- * with command
- * gperf  -g -o -j1 -t -p -N is_reserved_word
- *
- */
-struct resword { char *name; short token; short iclass;};
-
-#define TOTAL_KEYWORDS 35
-#define MIN_WORD_LENGTH 2
-#define MAX_WORD_LENGTH 9
-#define MIN_HASH_VALUE 2
-#define MAX_HASH_VALUE 43
-/* maximum key range = 42, duplicates = 0 */
-
-#ifdef __GNUC__
-__inline
-#endif
-static unsigned int
-hash (str, len)
-     register const char *str;
-     register unsigned int len;
-{
-  static unsigned char asso_values[] =
-    {
-      44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
-      44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
-      44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
-      44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
-      44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
-      44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
-      44, 44, 44, 44, 44, 18, 29, 14,  6,  7,
-      10, 20, 44, 28, 44, 44, 28, 19, 22, 15,
-       0, 44,  9, 23,  0, 23, 26,  2, 44, 44,
-      44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
-       0,  0, 13, 44, 30, 44, 44, 44,  0, 25,
-       1,  0, 44, 44,  0, 44,  1, 44, 25, 44,
-      44,  0, 44, 44, 44, 44, 44, 44, 44, 44,
-      44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
-      44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
-      44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
-      44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
-      44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
-      44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
-      44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
-      44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
-      44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
-      44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
-      44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
-      44, 44, 44, 44, 44, 44, 44, 44, 44, 44,
-      44, 44, 44, 44, 44, 44
-    };
-  return len + asso_values[(unsigned char)str[len - 1]] + asso_values[(unsigned char)str[0]];
-}
-
-#ifdef __GNUC__
-__inline
-#endif
-struct resword *
-is_reserved_word (str, len)
-     register const char *str;
-     register unsigned int len;
-{
-  static struct resword wordlist[] =
-    {
-      {""}, {""},
-      {"To", TO, PASCAL_ISO},
-      {""},
-      {"Type", TYPE, PASCAL_ISO},
-      {"Then", THEN, PASCAL_ISO},
-      {"Packed", PACKED, PASCAL_ISO},
-      {"While",  WHILE,  PASCAL_ISO},
-      {"Do", DO, PASCAL_ISO},
-      {"Procedure", PROCEDURE, PASCAL_ISO},
-      {"End",  END,  PASCAL_ISO},
-      {"Else", ELSE, PASCAL_ISO},
-      {"Downto", DOWNTO, PASCAL_ISO},
-      {"For",  FOR,  PASCAL_ISO},
-      {"File", FILE_,  PASCAL_ISO},
-      {"Record", RECORD, PASCAL_ISO},
-      {"Repeat", REPEAT, PASCAL_ISO},
-      {"Or", OR, PASCAL_ISO},
-      {"Case", CASE, PASCAL_ISO},
-      {"Function", FUNCTION, PASCAL_ISO},
-      {"Const",  CONST,  PASCAL_ISO},
-      {"And",  AND,  PASCAL_ISO},
-      {"Mod",  MOD,  PASCAL_ISO},
-      {"Array",  ARRAY,  PASCAL_ISO},
-      {"Goto", GOTO, PASCAL_ISO},
-      {"Nil",  NIL,  PASCAL_ISO},
-      {"Not",  NOT,  PASCAL_ISO},
-      {"Set",  SET,  PASCAL_ISO},
-      {"Until",  UNTIL,  PASCAL_ISO},
-      {"Var",  VAR,  PASCAL_ISO},
-      {"Of", OF, PASCAL_ISO},
-      {"In", IN, PASCAL_ISO},
-      {"Program",PROGRAM,PASCAL_ISO},
-      {"Label",  LABEL,  PASCAL_ISO},
-      {"Div",  DIV,  PASCAL_ISO},
-      {"Begin",  BEGIN_, PASCAL_ISO},
-      {"With", WITH, PASCAL_ISO},
-      {""}, {""}, {""}, {""}, {""}, {""},
-      {"If", IF, PASCAL_ISO}
-    };
-
-  if (len <= MAX_WORD_LENGTH && len >= MIN_WORD_LENGTH)
-    {
-      register int key = hash (str, len);
-
-      if (key <= MAX_HASH_VALUE && key >= 0)
-        {
-          register const char *s = wordlist[key].name;
-
-          if (*str == *s && !strcmp (str + 1, s + 1))
-            return &wordlist[key];
-        }
-    }
-  return 0;
-}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/tests/test-6.exp
--- a/head/contrib/gperf/tests/test-6.exp	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,119 +0,0 @@
-GNU `gperf' generates perfect hash functions.
-
-Usage: ../src/gperf [OPTION]... [INPUT-FILE]
-
-If a long option shows an argument as mandatory, then it is mandatory
-for the equivalent short option also.
-
-Input file interpretation:
-  -e, --delimiters=DELIMITER-LIST
-                         Allow user to provide a string containing delimiters
-                         used to separate keywords from their attributes.
-                         Default is ",\n".
-  -t, --struct-type      Allows the user to include a structured type
-                         declaration for generated code. Any text before %%
-                         is considered part of the type declaration. Key
-                         words and additional fields may follow this, one
-                         group of fields per line.
-
-Language for the output code:
-  -L, --language=LANGUAGE-NAME
-                         Generates code in the specified language. Languages
-                         handled are currently C++, ANSI-C, C, and KR-C. The
-                         default is C.
-
-Details in the output code:
-  -K, --slot-name=NAME   Select name of the keyword component in the keyword
-                         structure.
-  -H, --hash-fn-name=NAME
-                         Specify name of generated hash function. Default is
-                         `hash'.
-  -N, --lookup-fn-name=NAME
-                         Specify name of generated lookup function. Default
-                         name is `in_word_set'.
-  -Z, --class-name=NAME  Specify name of generated C++ class. Default name is
-                         `Perfect_Hash'.
-  -7, --seven-bit        Assume 7-bit characters.
-  -c, --compare-strncmp  Generate comparison code using strncmp rather than
-                         strcmp.
-  -C, --readonly-tables  Make the contents of generated lookup tables
-                         constant, i.e., readonly.
-  -E, --enum             Define constant values using an enum local to the
-                         lookup function rather than with defines.
-  -I, --includes         Include the necessary system include file <string.h>
-                         at the beginning of the code.
-  -G, --global           Generate the static table of keywords as a static
-                         global variable, rather than hiding it inside of the
-                         lookup function (which is the default behavior).
-  -W, --word-array-name=NAME
-                         Specify name of word list array. Default name is
-                         `wordlist'.
-  -S, --switch=COUNT     Causes the generated C code to use a switch
-                         statement scheme, rather than an array lookup table.
-                         This can lead to a reduction in both time and space
-                         requirements for some keyfiles. The COUNT argument
-                         determines how many switch statements are generated.
-                         A value of 1 generates 1 switch containing all the
-                         elements, a value of 2 generates 2 tables with 1/2
-                         the elements in each table, etc. If COUNT is very
-                         large, say 1000000, the generated C code does a
-                         binary search.
-  -T, --omit-struct-type
-                         Prevents the transfer of the type declaration to the
-                         output file. Use this option if the type is already
-                         defined elsewhere.
-
-Algorithm employed by gperf:
-  -k, --key-positions=KEYS
-                         Select the key positions used in the hash function.
-                         The allowable choices range between 1-126, inclusive.
-                         The positions are separated by commas, ranges may be
-                         used, and key positions may occur in any order.
-                         Also, the meta-character '*' causes the generated
-                         hash function to consider ALL key positions, and $
-                         indicates the ``final character'' of a key, e.g.,
-                         $,1,2,4,6-10.
-  -l, --compare-strlen   Compare key lengths before trying a string
-                         comparison. This helps cut down on the number of
-                         string comparisons made during the lookup.
-  -D, --duplicates       Handle keywords that hash to duplicate values. This
-                         is useful for certain highly redundant keyword sets.
-  -f, --fast=ITERATIONS  Generate the gen-perf.hash function ``fast''. This
-                         decreases gperf's running time at the cost of
-                         minimizing generated table size. The numeric
-                         argument represents the number of times to iterate
-                         when resolving a collision. `0' means ``iterate by
-                         the number of keywords''.
-  -i, --initial-asso=N   Provide an initial value for the associate values
-                         array. Default is 0. Setting this value larger helps
-                         inflate the size of the final table.
-  -j, --jump=JUMP-VALUE  Affects the ``jump value'', i.e., how far to advance
-                         the associated character value upon collisions. Must
-                         be an odd number, default is 5.
-  -n, --no-strlen        Do not include the length of the keyword when
-                         computing the hash function.
-  -o, --occurrence-sort  Reorders input keys by frequency of occurrence of
-                         the key sets. This should decrease the search time
-                         dramatically.
-  -r, --random           Utilizes randomness to initialize the associated
-                         values table.
-  -s, --size-multiple=N  Affects the size of the generated hash table. The
-                         numeric argument N indicates ``how many times larger
-                         or smaller'' the associated value range should be,
-                         in relationship to the number of keys, e.g. a value
-                         of 3 means ``allow the maximum associated value to
-                         be about 3 times larger than the number of input
-                         keys.'' Conversely, a value of -3 means ``make the
-                         maximum associated value about 3 times smaller than
-                         the number of input keys. A larger table should
-                         decrease the time required for an unsuccessful
-                         search, at the expense of extra table space. Default
-                         value is 1.
-
-Informative output:
-  -h, --help             Print this message.
-  -v, --version          Print the gperf version number.
-  -d, --debug            Enables the debugging option (produces verbose
-                         output to the standard error).
-
-Report bugs to <bug-gnu-utils at gnu.org>.
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/tests/test-7.exp
--- a/head/contrib/gperf/tests/test-7.exp	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,32 +0,0 @@
-in word set if
-in word set do
-NOT in word set int
-in word set for
-in word set case
-NOT in word set char
-NOT in word set auto
-in word set goto
-in word set else
-NOT in word set long
-NOT in word set void
-NOT in word set enum
-NOT in word set float
-NOT in word set short
-NOT in word set union
-NOT in word set break
-in word set while
-NOT in word set const
-NOT in word set double
-NOT in word set static
-NOT in word set extern
-NOT in word set struct
-in word set return
-NOT in word set sizeof
-NOT in word set switch
-NOT in word set signed
-NOT in word set typedef
-NOT in word set default
-NOT in word set unsigned
-NOT in word set continue
-NOT in word set register
-NOT in word set volatile
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/tests/test.c
--- a/head/contrib/gperf/tests/test.c	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,26 +0,0 @@
-/*
-   Tests the generated perfect hash function.
-   The -v option prints diagnostics as to whether a word is in 
-   the set or not.  Without -v the program is useful for timing.
-*/ 
-  
-#include <stdio.h>
-
-#define MAX_LEN 80
-
-int 
-main (argc, argv) 
-     int   argc;
-     char *argv[];
-{
-  int  verbose = argc > 1 ? 1 : 0;
-  char buf[MAX_LEN];
-
-  while (gets (buf)) 
-    if (in_word_set (buf, strlen (buf)) && verbose) 
-      printf ("in word set %s\n", buf);
-    else if (verbose) 
-      printf ("NOT in word set %s\n", buf);
-
-  return 0;
-}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/gperf/tests/validate
--- a/head/contrib/gperf/tests/validate	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,54 +0,0 @@
-#! /bin/sh
-# Validate gperf's operation on a given input file.
-# Usage: validate languages input.gperf [more gperf options]
-# Uses the environment variables GPERF, CC, CFLAGS, CXX, CXXFLAGS.
-# Supposes gcc and g++.
-
-# Exit on error
-set -e
-
-verbose () {
-  echo "$@"
-  "$@"
-}
-
-languages=$1
-shift
-
-for lang in `echo $languages | sed -e 's/,/ /g'`; do
-  case "$lang" in
-    KR-C )
-      echo "${GPERF} -I -L KR-C $@ > valitest.c"
-      ${GPERF} -I -L KR-C "$@" > valitest.c
-      grep -n ' const ' valitest.c /dev/null && exit 1
-      verbose ${CC} ${CFLAGS} -traditional valitest.c -o valitest
-      ./valitest
-      verbose ${CC} ${CFLAGS} -ansi -pedantic valitest.c -o valitest
-      ./valitest
-      ;;
-    C )
-      echo "${GPERF} -I -L C $@ > valitest.c"
-      ${GPERF} -I -L C "$@" > valitest.c
-      verbose ${CC} ${CFLAGS} -traditional -Dconst= valitest.c -o valitest
-      ./valitest
-      verbose ${CC} ${CFLAGS} -ansi -pedantic -pedantic-errors valitest.c -o valitest
-      ./valitest
-      ;;
-    ANSI-C )
-      echo "${GPERF} -I -L ANSI-C $@ > valitest.c"
-      ${GPERF} -I -L ANSI-C "$@" > valitest.c
-      verbose ${CC} ${CFLAGS} -ansi -pedantic -pedantic-errors valitest.c -o valitest
-      ./valitest
-      verbose ${CXX} ${CXXFLAGS} -ansi -pedantic -pedantic-errors valitest.c -o valitest
-      ./valitest
-      ;;
-    "C++" )
-      echo "${GPERF} -I -L C++ $@ > valitest.c"
-      ${GPERF} -I -L C++ "$@" > valitest.c
-      verbose ${CXX} ${CXXFLAGS} -ansi -pedantic -pedantic-errors -DCPLUSPLUS_TEST valitest.c -o valitest
-      ./valitest
-      ;;
-  esac
-done
-
-exit 0
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/libcxxrt/FREEBSD-upgrade
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/contrib/libcxxrt/FREEBSD-upgrade	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,6 @@
+$FreeBSD$
+
+This is the FreeBSD copy of libcxxrt.  It contains the src directory from the 
+upstream repository.
+
+When updating, copy *.{c,cc,h} and typeinfo from the upstream src/.
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/libcxxrt/LICENSE
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/contrib/libcxxrt/LICENSE	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,14 @@
+The BSD License
+
+Copyright 2010-2011 PathScale, 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 COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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 views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of PathScale, Inc.
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/libcxxrt/abi_namespace.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/contrib/libcxxrt/abi_namespace.h	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,5 @@
+/**
+ * The namespace used for the ABI declarations.  This is currently defined to
+ * be the same as GNU libsupc++, however this may change in the future.
+ */
+#define ABI_NAMESPACE __cxxabiv1
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/libcxxrt/auxhelper.cc
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/contrib/libcxxrt/auxhelper.cc	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,41 @@
+/**
+ * aux.cc - Compiler helper functions. 
+ *
+ * The functions declared in this file are intended to be called only by code
+ * that is automatically generated by C++ compilers for some common cases.  
+ */
+
+#include <stdlib.h>
+#include "stdexcept.h"
+
+/**
+ * Called to generate a bad cast exception.  This function is intended to allow
+ * compilers to insert code generating this exception without needing to
+ * duplicate the code for throwing the exception in every call site.
+ */
+extern "C" void __cxa_bad_cast()
+{
+    throw std::bad_cast();
+}
+
+/**
+ * Called to generate a bad typeid exception.  This function is intended to
+ * allow compilers to insert code generating this exception without needing to
+ * duplicate the code for throwing the exception in every call site.
+ */
+extern "C" void __cxa_bad_typeid()
+{
+    throw std::bad_typeid();
+}
+
+/**
+ * Compilers may (but are not required to) set any pure-virtual function's
+ * vtable entry to this function.  This makes debugging slightly easier, as
+ * users can add a breakpoint on this function to tell if they've accidentally
+ * called a pure-virtual function.
+ */
+extern "C" void __cxa_pure_virtual()
+{
+    abort();
+}
+
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/libcxxrt/cxxabi.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/contrib/libcxxrt/cxxabi.h	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,219 @@
+#ifndef __CXXABI_H_
+#define __CXXABI_H_
+#include <stdint.h>
+#include "unwind.h"
+namespace std 
+{
+	class type_info;
+}
+/*
+ * The cxxabi.h header provides a set of public definitions for types and
+ * functions defined by the Itanium C++ ABI specification.  For reference, see
+ * the ABI specification here:
+ *
+ * http://sourcery.mentor.com/public/cxx-abi/abi.html
+ *
+ * All deviations from this specification, unless otherwise noted, are
+ * accidental.
+ */
+
+#ifdef __cplusplus
+namespace __cxxabiv1 {
+extern "C" {
+#endif
+/**
+ * Function type to call when an unexpected exception is encountered.
+ */
+typedef void (*unexpected_handler)();
+/**
+ * Function type to call when an unrecoverable condition is encountered.
+ */
+typedef void (*terminate_handler)();
+
+
+/**
+ * Structure used as a header on thrown exceptions.  This is the same layout as
+ * defined by the Itanium ABI spec, so should be interoperable with any other
+ * implementation of this spec, such as GNU libsupc++.
+ *
+ * This structure is allocated when an exception is thrown.  Unwinding happens
+ * in two phases, the first looks for a handler and the second installs the
+ * context.  This structure stores a cache of the handler location between
+ * phase 1 and phase 2.  Unfortunately, cleanup information is not cached, so
+ * must be looked up in both phases.  This happens for two reasons.  The first
+ * is that we don't know how many frames containing cleanups there will be, and
+ * we should avoid dynamic allocation during unwinding (the exception may be
+ * reporting that we've run out of memory).  The second is that finding
+ * cleanups is much cheaper than finding handlers, because we don't have to
+ * look at the type table at all.
+ *
+ * Note: Several fields of this structure have not-very-informative names.
+ * These are taken from the ABI spec and have not been changed to make it
+ * easier for people referring to to the spec while reading this code.
+ */
+struct __cxa_exception
+{
+#if __LP64__
+	/**
+	 * Reference count.  Used to support the C++11 exception_ptr class.  This
+	 * is prepended to the structure in 64-bit mode and squeezed in to the
+	 * padding left before the 64-bit aligned _Unwind_Exception at the end in
+	 * 32-bit mode.
+	 *
+	 * Note that it is safe to extend this structure at the beginning, rather
+	 * than the end, because the public API for creating it returns the address
+	 * of the end (where the exception object can be stored).
+	 */
+	uintptr_t referenceCount;
+#endif
+	/** Type info for the thrown object. */
+	std::type_info *exceptionType;
+	/** Destructor for the object, if one exists. */
+	void (*exceptionDestructor) (void *); 
+	/** Handler called when an exception specification is violated. */
+	unexpected_handler unexpectedHandler;
+	/** Hander called to terminate. */
+	terminate_handler terminateHandler;
+	/**
+	 * Next exception in the list.  If an exception is thrown inside a catch
+	 * block and caught in a nested catch, this points to the exception that
+	 * will be handled after the inner catch block completes.
+	 */
+	__cxa_exception *nextException;
+	/**
+	 * The number of handlers that currently have references to this
+	 * exception.  The top (non-sign) bit of this is used as a flag to indicate
+	 * that the exception is being rethrown, so should not be deleted when its
+	 * handler count reaches 0 (which it doesn't with the top bit set).
+	 */
+	int handlerCount;
+#ifdef __arm__
+	/**
+	 * The ARM EH ABI requires the unwind library to keep track of exceptions
+	 * during cleanups.  These support nesting, so we need to keep a list of
+	 * them.
+	 */
+	_Unwind_Exception *nextCleanup;
+	/**
+	 * The number of cleanups that are currently being run on this exception. 
+	 */
+	int cleanupCount;
+#endif
+	/**
+	 * The selector value to be returned when installing the catch handler.
+	 * Used at the call site to determine which catch() block should execute.
+	 * This is found in phase 1 of unwinding then installed in phase 2.
+	 */
+	int handlerSwitchValue;
+	/**
+	 * The action record for the catch.  This is cached during phase 1
+	 * unwinding.
+	 */
+	const char *actionRecord;
+	/**
+	 * Pointer to the language-specific data area (LSDA) for the handler
+	 * frame.  This is unused in this implementation, but set for ABI
+	 * compatibility in case we want to mix code in very weird ways.
+	 */
+	const char *languageSpecificData;
+	/** The cached landing pad for the catch handler.*/
+	void *catchTemp;
+	/**
+	 * The pointer that will be returned as the pointer to the object.  When
+	 * throwing a class and catching a virtual superclass (for example), we
+	 * need to adjust the thrown pointer to make it all work correctly.
+	 */
+	void *adjustedPtr;
+#if !__LP64__
+	/**
+	 * Reference count.  Used to support the C++11 exception_ptr class.  This
+	 * is prepended to the structure in 64-bit mode and squeezed in to the
+	 * padding left before the 64-bit aligned _Unwind_Exception at the end in
+	 * 32-bit mode.
+	 *
+	 * Note that it is safe to extend this structure at the beginning, rather
+	 * than the end, because the public API for creating it returns the address
+	 * of the end (where the exception object can be stored) 
+	 */
+	uintptr_t referenceCount;
+#endif
+	/** The language-agnostic part of the exception header. */
+	_Unwind_Exception unwindHeader;
+};
+
+/**
+ * ABI-specified globals structure.  Returned by the __cxa_get_globals()
+ * function and its fast variant.  This is a per-thread structure - every
+ * thread will have one lazily allocated.
+ *
+ * This structure is defined by the ABI, so may be used outside of this
+ * library.
+ */
+struct __cxa_eh_globals
+{
+	/**
+	 * A linked list of exceptions that are currently caught.  There may be
+	 * several of these in nested catch() blocks.
+	 */
+	__cxa_exception *caughtExceptions;
+	/**
+	 * The number of uncaught exceptions.
+	 */
+	unsigned int uncaughtExceptions;
+};
+/**
+ * ABI function returning the __cxa_eh_globals structure.
+ */
+__cxa_eh_globals *__cxa_get_globals(void);
+/**
+ * Version of __cxa_get_globals() assuming that __cxa_get_globals() has already
+ * been called at least once by this thread.
+ */
+__cxa_eh_globals *__cxa_get_globals_fast(void);
+
+/**
+ * Throws an exception returned by __cxa_current_primary_exception().  This
+ * exception may have been caught in another thread.
+ */
+void __cxa_rethrow_primary_exception(void* thrown_exception);
+/**
+ * Returns the current exception in a form that can be stored in an
+ * exception_ptr object and then rethrown by a call to
+ * __cxa_rethrow_primary_exception().
+ */
+void *__cxa_current_primary_exception(void);
+/**
+ * Increments the reference count of an exception.  Called when an
+ * exception_ptr is copied.
+ */
+void __cxa_increment_exception_refcount(void* thrown_exception);
+/**
+ * Decrements the reference count of an exception.  Called when an
+ * exception_ptr is deleted.
+ */
+void __cxa_decrement_exception_refcount(void* thrown_exception);
+/**
+ * Demangles a C++ symbol or type name.  The buffer, if non-NULL, must be
+ * allocated with malloc() and must be *n bytes or more long.  This function
+ * may call realloc() on the value pointed to by buf, and will return the
+ * length of the string via *n.
+ *
+ * The value pointed to by status is set to one of the following:
+ *
+ * 0: success
+ * -1: memory allocation failure
+ * -2: invalid mangled name
+ * -3: invalid arguments
+ */
+char* __cxa_demangle(const char* mangled_name,
+                     char* buf,
+                     size_t* n,
+                     int* status);
+#ifdef __cplusplus
+} // extern "C"
+} // namespace
+
+namespace abi = __cxxabiv1;
+
+#endif /* __cplusplus */
+#endif /* __CXXABI_H_ */
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/libcxxrt/dwarf_eh.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/contrib/libcxxrt/dwarf_eh.h	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,454 @@
+/**
+ * dwarf_eh.h - Defines some helper functions for parsing DWARF exception
+ * handling tables.
+ *
+ * This file contains various helper functions that are independent of the
+ * language-specific code.  It can be used in any personality function for the
+ * Itanium ABI.
+ */
+#include <assert.h>
+
+// TODO: Factor out Itanium / ARM differences.  We probably want an itanium.h
+// and arm.h that can be included by this file depending on the target ABI.
+
+// _GNU_SOURCE must be defined for unwind.h to expose some of the functions
+// that we want.  If it isn't, then we define it and undefine it to make sure
+// that it doesn't impact the rest of the program.
+#ifndef _GNU_SOURCE
+#	define _GNU_SOURCE 1
+#	include "unwind.h"
+#	undef _GNU_SOURCE
+#else
+#	include "unwind.h"
+#endif
+
+#include <stdint.h>
+
+/// Type used for pointers into DWARF data
+typedef unsigned char *dw_eh_ptr_t;
+
+// Flag indicating a signed quantity
+#define DW_EH_PE_signed 0x08
+/// DWARF data encoding types.  
+enum dwarf_data_encoding
+{
+	/// Unsigned, little-endian, base 128-encoded (variable length).
+	DW_EH_PE_uleb128 = 0x01,
+	/// Unsigned 16-bit integer.
+	DW_EH_PE_udata2  = 0x02,
+	/// Unsigned 32-bit integer.
+	DW_EH_PE_udata4  = 0x03,
+	/// Unsigned 64-bit integer.
+	DW_EH_PE_udata8  = 0x04,
+	/// Signed, little-endian, base 128-encoded (variable length)
+	DW_EH_PE_sleb128 = DW_EH_PE_uleb128 | DW_EH_PE_signed,
+	/// Signed 16-bit integer.
+	DW_EH_PE_sdata2  = DW_EH_PE_udata2 | DW_EH_PE_signed,
+	/// Signed 32-bit integer.
+	DW_EH_PE_sdata4  = DW_EH_PE_udata4 | DW_EH_PE_signed,
+	/// Signed 32-bit integer.
+	DW_EH_PE_sdata8  = DW_EH_PE_udata8 | DW_EH_PE_signed
+};
+
+/**
+ * Returns the encoding for a DWARF EH table entry.  The encoding is stored in
+ * the low four of an octet.  The high four bits store the addressing mode.
+ */
+static inline enum dwarf_data_encoding get_encoding(unsigned char x)
+{
+	return (enum dwarf_data_encoding)(x & 0xf);
+}
+
+/**
+ * DWARF addressing mode constants.  When reading a pointer value from a DWARF
+ * exception table, you must know how it is stored and what the addressing mode
+ * is.  The low four bits tell you the encoding, allowing you to decode a
+ * number.  The high four bits tell you the addressing mode, allowing you to
+ * turn that number into an address in memory.
+ */
+enum dwarf_data_relative
+{
+	/// Value is omitted
+	DW_EH_PE_omit     = 0xff,
+	/// Absolute pointer value
+	DW_EH_PE_absptr   = 0x00,
+	/// Value relative to program counter
+	DW_EH_PE_pcrel    = 0x10,
+	/// Value relative to the text segment
+	DW_EH_PE_textrel  = 0x20,
+	/// Value relative to the data segment
+	DW_EH_PE_datarel  = 0x30,
+	/// Value relative to the start of the function
+	DW_EH_PE_funcrel  = 0x40,
+	/// Aligned pointer (Not supported yet - are they actually used?)
+	DW_EH_PE_aligned  = 0x50,
+	/// Pointer points to address of real value
+	DW_EH_PE_indirect = 0x80
+};
+/**
+ * Returns the addressing mode component of this encoding.
+ */
+static inline enum dwarf_data_relative get_base(unsigned char x)
+{
+	return (enum dwarf_data_relative)(x & 0x70);
+}
+/**
+ * Returns whether an encoding represents an indirect address.
+ */
+static int is_indirect(unsigned char x)
+{
+	return ((x & DW_EH_PE_indirect) == DW_EH_PE_indirect);
+}
+
+/**
+ * Returns the size of a fixed-size encoding.  This function will abort if
+ * called with a value that is not a fixed-size encoding.
+ */
+static inline int dwarf_size_of_fixed_size_field(unsigned char type)
+{
+	switch (get_encoding(type))
+	{
+		default: abort();
+		case DW_EH_PE_sdata2: 
+		case DW_EH_PE_udata2: return 2;
+		case DW_EH_PE_sdata4:
+		case DW_EH_PE_udata4: return 4;
+		case DW_EH_PE_sdata8:
+		case DW_EH_PE_udata8: return 8;
+		case DW_EH_PE_absptr: return sizeof(void*);
+	}
+}
+
+/** 
+ * Read an unsigned, little-endian, base-128, DWARF value.  Updates *data to
+ * point to the end of the value.  Stores the number of bits read in the value
+ * pointed to by b, allowing you to determine the value of the highest bit, and
+ * therefore the sign of a signed value.
+ *
+ * This function is not intended to be called directly.  Use read_sleb128() or
+ * read_uleb128() for reading signed and unsigned versions, respectively.
+ */
+static uint64_t read_leb128(dw_eh_ptr_t *data, int *b)
+{
+	uint64_t uleb = 0;
+	unsigned int bit = 0;
+	unsigned char digit = 0;
+	// We have to read at least one octet, and keep reading until we get to one
+	// with the high bit unset
+	do
+	{
+		// This check is a bit too strict - we should also check the highest
+		// bit of the digit.
+		assert(bit < sizeof(uint64_t) * 8);
+		// Get the base 128 digit 
+		digit = (**data) & 0x7f;
+		// Add it to the current value
+		uleb += digit << bit;
+		// Increase the shift value
+		bit += 7;
+		// Proceed to the next octet
+		(*data)++;
+		// Terminate when we reach a value that does not have the high bit set
+		// (i.e. which was not modified when we mask it with 0x7f)
+	} while ((*(*data - 1)) != digit);
+	*b = bit;
+
+	return uleb;
+}
+
+/**
+ * Reads an unsigned little-endian base-128 value starting at the address
+ * pointed to by *data.  Updates *data to point to the next byte after the end
+ * of the variable-length value.
+ */
+static int64_t read_uleb128(dw_eh_ptr_t *data)
+{
+	int b;
+	return read_leb128(data, &b);
+}
+
+/**
+ * Reads a signed little-endian base-128 value starting at the address pointed
+ * to by *data.  Updates *data to point to the next byte after the end of the
+ * variable-length value.
+ */
+static int64_t read_sleb128(dw_eh_ptr_t *data)
+{
+	int bits;
+	// Read as if it's signed
+	uint64_t uleb = read_leb128(data, &bits);
+	// If the most significant bit read is 1, then we need to sign extend it
+	if ((uleb >> (bits-1)) == 1)
+	{
+		// Sign extend by setting all bits in front of it to 1
+		uleb |= ((int64_t)-1) << bits;
+	}
+	return (int64_t)uleb;
+}
+/**
+ * Reads a value using the specified encoding from the address pointed to by
+ * *data.  Updates the value of *data to point to the next byte after the end
+ * of the data.
+ */
+static uint64_t read_value(char encoding, dw_eh_ptr_t *data)
+{
+	enum dwarf_data_encoding type = get_encoding(encoding);
+	uint64_t v;
+	switch (type)
+	{
+		// Read fixed-length types
+#define READ(dwarf, type) \
+		case dwarf:\
+			v = (uint64_t)(*(type*)(*data));\
+			*data += sizeof(type);\
+			break;
+		READ(DW_EH_PE_udata2, uint16_t)
+		READ(DW_EH_PE_udata4, uint32_t)
+		READ(DW_EH_PE_udata8, uint64_t)
+		READ(DW_EH_PE_sdata2, int16_t)
+		READ(DW_EH_PE_sdata4, int32_t)
+		READ(DW_EH_PE_sdata8, int64_t)
+		READ(DW_EH_PE_absptr, intptr_t)
+#undef READ
+		// Read variable-length types
+		case DW_EH_PE_sleb128:
+			v = read_sleb128(data);
+			break;
+		case DW_EH_PE_uleb128:
+			v = read_uleb128(data);
+			break;
+		default: abort();
+	}
+
+	return v;
+}
+
+/**
+ * Resolves an indirect value.  This expects an unwind context, an encoding, a
+ * decoded value, and the start of the region as arguments.  The returned value
+ * is a pointer to the address identified by the encoded value.
+ *
+ * If the encoding does not specify an indirect value, then this returns v.
+ */
+static uint64_t resolve_indirect_value(_Unwind_Context *c,
+                                       unsigned char encoding,
+                                       int64_t v,
+                                       dw_eh_ptr_t start)
+{
+	switch (get_base(encoding))
+	{
+		case DW_EH_PE_pcrel:
+			v += (uint64_t)start;
+			break;
+		case DW_EH_PE_textrel:
+			v += (uint64_t)_Unwind_GetTextRelBase(c);
+			break;
+		case DW_EH_PE_datarel:
+			v += (uint64_t)_Unwind_GetDataRelBase(c);
+			break;
+		case DW_EH_PE_funcrel:
+			v += (uint64_t)_Unwind_GetRegionStart(c);
+		default:
+			break;
+	}
+	// If this is an indirect value, then it is really the address of the real
+	// value
+	// TODO: Check whether this should really always be a pointer - it seems to
+	// be a GCC extensions, so not properly documented...
+	if (is_indirect(encoding))
+	{
+		v = (uint64_t)(uintptr_t)*(void**)v;
+	}
+	return v;
+}
+
+
+/**
+ * Reads an encoding and a value, updating *data to point to the next byte.  
+ */
+static inline void read_value_with_encoding(_Unwind_Context *context,
+                                            dw_eh_ptr_t *data,
+                                            uint64_t *out)
+{
+	dw_eh_ptr_t start = *data;
+	unsigned char encoding = *((*data)++);
+	// If this value is omitted, skip it and don't touch the output value
+	if (encoding == DW_EH_PE_omit) { return; }
+
+	*out = read_value(encoding, data);
+	*out = resolve_indirect_value(context, encoding, *out, start);
+}
+
+/**
+ * Structure storing a decoded language-specific data area.  Use parse_lsda()
+ * to generate an instance of this structure from the address returned by the
+ * generic unwind library.  
+ *
+ * You should not need to inspect the fields of this structure directly if you
+ * are just using this header.  The structure stores the locations of the
+ * various tables used for unwinding exceptions and is used by the functions
+ * for reading values from these tables.
+ */
+struct dwarf_eh_lsda
+{
+	/// The start of the region.  This is a cache of the value returned by
+	/// _Unwind_GetRegionStart().
+	dw_eh_ptr_t region_start;
+	/// The start of the landing pads table.
+	dw_eh_ptr_t landing_pads;
+	/// The start of the type table.
+	dw_eh_ptr_t type_table;
+	/// The encoding used for entries in the type tables.
+	unsigned char type_table_encoding;
+	/// The location of the call-site table.
+	dw_eh_ptr_t call_site_table;
+	/// The location of the action table.
+	dw_eh_ptr_t action_table;
+	/// The encoding used for entries in the call-site table.
+	unsigned char callsite_encoding;
+};
+
+/**
+ * Parse the header on the language-specific data area and return a structure
+ * containing the addresses and encodings of the various tables.
+ */
+static inline struct dwarf_eh_lsda parse_lsda(_Unwind_Context *context,
+                                              unsigned char *data)
+{
+	struct dwarf_eh_lsda lsda;
+
+	lsda.region_start = (dw_eh_ptr_t)(uintptr_t)_Unwind_GetRegionStart(context);
+
+	// If the landing pads are relative to anything other than the start of
+	// this region, find out where.  This is @LPStart in the spec, although the
+	// encoding that GCC uses does not quite match the spec.
+	uint64_t v = (uint64_t)(uintptr_t)lsda.region_start;
+	read_value_with_encoding(context, &data, &v);
+	lsda.landing_pads = (dw_eh_ptr_t)(uintptr_t)v;
+
+	// If there is a type table, find out where it is.  This is @TTBase in the
+	// spec.  Note: we find whether there is a type table pointer by checking
+	// whether the leading byte is DW_EH_PE_omit (0xff), which is not what the
+	// spec says, but does seem to be how G++ indicates this.
+	lsda.type_table = 0;
+	lsda.type_table_encoding = *data++;
+	if (lsda.type_table_encoding != DW_EH_PE_omit)
+	{
+		v = read_uleb128(&data);
+		dw_eh_ptr_t type_table = data;
+		type_table += v;
+		lsda.type_table = type_table;
+		//lsda.type_table = (uintptr_t*)(data + v);
+	}
+#if __arm__
+	lsda.type_table_encoding = (DW_EH_PE_pcrel | DW_EH_PE_indirect);
+#endif
+
+	lsda.callsite_encoding = (enum dwarf_data_encoding)(*(data++));
+
+	// Action table is immediately after the call site table
+	lsda.action_table = data;
+	uintptr_t callsite_size = (uintptr_t)read_uleb128(&data);
+	lsda.action_table = data + callsite_size;
+	// Call site table is immediately after the header
+	lsda.call_site_table = (dw_eh_ptr_t)data;
+
+
+	return lsda;
+}
+
+/**
+ * Structure representing an action to be performed while unwinding.  This
+ * contains the address that should be unwound to and the action record that
+ * provoked this action.
+ */
+struct dwarf_eh_action
+{
+	/** 
+	 * The address that this action directs should be the new program counter
+	 * value after unwinding.
+	 */
+	dw_eh_ptr_t landing_pad;
+	/// The address of the action record.
+	dw_eh_ptr_t action_record;
+};
+
+/**
+ * Look up the landing pad that corresponds to the current invoke.
+ * Returns true if record exists.  The context is provided by the generic
+ * unwind library and the lsda should be the result of a call to parse_lsda().
+ *
+ * The action record is returned via the result parameter.  
+ */
+static bool dwarf_eh_find_callsite(struct _Unwind_Context *context,
+                                   struct dwarf_eh_lsda *lsda,
+                                   struct dwarf_eh_action *result)
+{
+	result->action_record = 0;
+	result->landing_pad = 0;
+	// The current instruction pointer offset within the region
+	uint64_t ip = _Unwind_GetIP(context) - _Unwind_GetRegionStart(context);
+	unsigned char *callsite_table = (unsigned char*)lsda->call_site_table;
+
+	while (callsite_table <= lsda->action_table)
+	{
+		// Once again, the layout deviates from the spec.
+		uint64_t call_site_start, call_site_size, landing_pad, action;
+		call_site_start = read_value(lsda->callsite_encoding, &callsite_table);
+		call_site_size = read_value(lsda->callsite_encoding, &callsite_table);
+
+		// Call site entries are sorted, so if we find a call site that's after
+		// the current instruction pointer then there is no action associated
+		// with this call and we should unwind straight through this frame
+		// without doing anything.
+		if (call_site_start > ip) { break; }
+
+		// Read the address of the landing pad and the action from the call
+		// site table.
+		landing_pad = read_value(lsda->callsite_encoding, &callsite_table);
+		action = read_uleb128(&callsite_table);
+
+		// We should not include the call_site_start (beginning of the region)
+		// address in the ip range. For each call site:
+		//
+		// address1: call proc
+		// address2: next instruction
+		//
+		// The call stack contains address2 and not address1, address1 can be
+		// at the end of another EH region.
+		if (call_site_start < ip && ip <= call_site_start + call_site_size)
+		{
+			if (action)
+			{
+				// Action records are 1-biased so both no-record and zeroth
+				// record can be stored.
+				result->action_record = lsda->action_table + action - 1;
+			}
+			// No landing pad means keep unwinding.
+			if (landing_pad)
+			{
+				// Landing pad is the offset from the value in the header
+				result->landing_pad = lsda->landing_pads + landing_pad;
+			}
+			return true;
+		}
+	}
+	return false;
+}
+
+/// Defines an exception class from 8 bytes (endian independent)
+#define EXCEPTION_CLASS(a,b,c,d,e,f,g,h) \
+	(((uint64_t)a << 56) +\
+	 ((uint64_t)b << 48) +\
+	 ((uint64_t)c << 40) +\
+	 ((uint64_t)d << 32) +\
+	 ((uint64_t)e << 24) +\
+	 ((uint64_t)f << 16) +\
+	 ((uint64_t)g << 8) +\
+	 ((uint64_t)h))
+
+#define GENERIC_EXCEPTION_CLASS(e,f,g,h) \
+	 ((uint32_t)e << 24) +\
+	 ((uint32_t)f << 16) +\
+	 ((uint32_t)g << 8) +\
+	 ((uint32_t)h)
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/libcxxrt/dynamic_cast.cc
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/contrib/libcxxrt/dynamic_cast.cc	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,133 @@
+#include "typeinfo.h"
+#include <stdio.h>
+
+using namespace ABI_NAMESPACE;
+
+/**
+ * Vtable header.
+ */
+struct vtable_header
+{
+	/** Offset of the leaf object. */
+	ptrdiff_t leaf_offset;
+	/** Type of the object. */
+	const __class_type_info *type;
+};
+
+/**
+ * Simple macro that does pointer arithmetic in bytes but returns a value of
+ * the same type as the original.
+ */
+#define ADD_TO_PTR(x, off) (__typeof__(x))(((char*)x) + off)
+
+bool __class_type_info::can_cast_to(const struct __class_type_info *other) const
+{
+    return this == other;
+}
+
+void *__class_type_info::cast_to(void *obj, const struct __class_type_info *other) const
+{
+	if (this == other)
+	{
+		return obj;
+	}
+	return 0;
+}
+
+
+bool __si_class_type_info::can_cast_to(const struct __class_type_info *other) const
+{
+    return this == other || __base_type->can_cast_to(other);
+}
+
+void *__si_class_type_info::cast_to(void *obj, const struct __class_type_info *other) const
+{
+	if (this == other)
+	{
+		return obj;
+	}
+	return __base_type->cast_to(obj, other);
+}
+
+
+bool __vmi_class_type_info::can_cast_to(const struct __class_type_info *other) const
+{
+	if (this == other)
+	{
+		return true;
+	}
+	for (unsigned int i=0 ; i<__base_count ; i++)
+	{
+		const __base_class_type_info *info = &__base_info[i];
+        if(info->isPublic() && info->__base_type->can_cast_to(other))
+        {
+            return true;
+        }
+	}
+	return false;
+}
+
+void *__vmi_class_type_info::cast_to(void *obj, const struct __class_type_info *other) const
+{
+	if (this == other)
+	{
+		return obj;
+	}
+	for (unsigned int i=0 ; i<__base_count ; i++)
+	{
+		const __base_class_type_info *info = &__base_info[i];
+		ptrdiff_t offset = info->offset();
+		// If this is a virtual superclass, the offset is stored in the
+		// object's vtable at the offset requested; 2.9.5.6.c:
+		//
+		// 'For a non-virtual base, this is the offset in the object of the
+		// base subobject. For a virtual base, this is the offset in the
+		// virtual table of the virtual base offset for the virtual base
+		// referenced (negative).'
+
+		if (info->isVirtual())
+		{
+			// Object's vtable
+			ptrdiff_t *off = *(ptrdiff_t**)obj;
+			// Offset location in vtable
+			off = ADD_TO_PTR(off, offset);
+			offset = *off;
+		}
+		void *cast = ADD_TO_PTR(obj, offset);
+
+		if (info->__base_type == other)
+		{
+			return cast;
+		}
+		if ((cast = info->__base_type->cast_to(cast, other)))
+		{
+			return cast;
+		}
+	}
+	return 0;
+}
+
+/**
+ * ABI function used to implement the dynamic_cast<> operator.  Some cases of
+ * this operator are implemented entirely in the compiler (e.g. to void*).
+ * This function implements the dynamic casts of the form dynamic_cast<T>(v).
+ * This will be translated to a call to this function with the value v as the
+ * first argument.  The type id of the static type of v is the second argument
+ * and the type id of the destination type (T) is the third argument.
+ *
+ * The third argument is a hint about the compiler's guess at the correct
+ * pointer offset.  If this value is negative, then -1 indicates no hint, -2
+ * that src is not a public base of dst, and -3 that src is a multiple public
+ * base type but never a virtual base type
+ */
+extern "C" void* __dynamic_cast(const void *sub,
+                                const __class_type_info *src,
+                                const __class_type_info *dst,
+                                ptrdiff_t src2dst_offset)
+{
+	char *vtable_location = *(char**)sub;
+	const vtable_header *header =
+		(const vtable_header*)(vtable_location - sizeof(vtable_header));
+	void *leaf = ADD_TO_PTR((void*)sub, header->leaf_offset);
+	return header->type->cast_to(leaf, dst);
+}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/libcxxrt/exception.cc
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/contrib/libcxxrt/exception.cc	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,1483 @@
+#include <stdlib.h>
+#include <dlfcn.h>
+#include <stdio.h>
+#include <string.h>
+#include <stdint.h>
+#include <pthread.h>
+#include "typeinfo.h"
+#include "dwarf_eh.h"
+#include "cxxabi.h"
+
+#pragma weak pthread_key_create
+#pragma weak pthread_setspecific
+#pragma weak pthread_getspecific
+#pragma weak pthread_once
+#pragma weak pthread_once
+#pragma weak pthread_cond_signal
+#pragma weak pthread_cond_wait
+#pragma weak pthread_mutex_lock
+#pragma weak pthread_mutex_unlock
+
+
+using namespace ABI_NAMESPACE;
+
+/**
+ * Saves the result of the landing pad that we have found.  For ARM, this is
+ * stored in the generic unwind structure, while on other platforms it is
+ * stored in the C++ exception.
+ */
+static void saveLandingPad(struct _Unwind_Context *context,
+                           struct _Unwind_Exception *ucb,
+                           struct __cxa_exception *ex,
+                           int selector,
+                           dw_eh_ptr_t landingPad)
+{
+#ifdef __arm__
+	// On ARM, we store the saved exception in the generic part of the structure
+	ucb->barrier_cache.sp = _Unwind_GetGR(context, 13);
+	ucb->barrier_cache.bitpattern[1] = (uint32_t)selector;
+	ucb->barrier_cache.bitpattern[3] = (uint32_t)landingPad;
+#endif
+	// Cache the results for the phase 2 unwind, if we found a handler
+	// and this is not a foreign exception.  
+	if (ex)
+	{
+		ex->handlerSwitchValue = selector;
+		ex->catchTemp = landingPad;
+	}
+}
+
+/**
+ * Loads the saved landing pad.  Returns 1 on success, 0 on failure.
+ */
+static int loadLandingPad(struct _Unwind_Context *context,
+                          struct _Unwind_Exception *ucb,
+                          struct __cxa_exception *ex,
+                          unsigned long *selector,
+                          dw_eh_ptr_t *landingPad)
+{
+#ifdef __arm__
+	*selector = ucb->barrier_cache.bitpattern[1];
+	*landingPad = (dw_eh_ptr_t)ucb->barrier_cache.bitpattern[3];
+	return 1;
+#else
+	if (ex)
+	{
+		*selector = ex->handlerSwitchValue;
+		*landingPad = (dw_eh_ptr_t)ex->catchTemp;
+		return 0;
+	}
+	return 0;
+#endif
+}
+
+static inline _Unwind_Reason_Code continueUnwinding(struct _Unwind_Exception *ex,
+                                                    struct _Unwind_Context *context)
+{
+#ifdef __arm__
+	if (__gnu_unwind_frame(ex, context) != _URC_OK) { return _URC_FAILURE; }
+#endif
+	return _URC_CONTINUE_UNWIND;
+}
+
+
+extern "C" void __cxa_free_exception(void *thrown_exception);
+extern "C" void __cxa_free_dependent_exception(void *thrown_exception);
+extern "C" void* __dynamic_cast(const void *sub,
+                                const __class_type_info *src,
+                                const __class_type_info *dst,
+                                ptrdiff_t src2dst_offset);
+
+/**
+ * The type of a handler that has been found.
+ */
+typedef enum
+{
+	/** No handler. */
+	handler_none,
+	/**
+	 * A cleanup - the exception will propagate through this frame, but code
+	 * must be run when this happens.
+	 */
+	handler_cleanup,
+	/**
+	 * A catch statement.  The exception will not propagate past this frame
+	 * (without an explicit rethrow).
+	 */
+	handler_catch
+} handler_type;
+
+/**
+ * Per-thread info required by the runtime.  We store a single structure
+ * pointer in thread-local storage, because this tends to be a scarce resource
+ * and it's impolite to steal all of it and not leave any for the rest of the
+ * program.
+ *
+ * Instances of this structure are allocated lazily - at most one per thread -
+ * and are destroyed on thread termination.
+ */
+struct __cxa_thread_info
+{
+	/** The termination handler for this thread. */
+	terminate_handler terminateHandler;
+	/** The unexpected exception handler for this thread. */
+	unexpected_handler unexpectedHandler;
+	/**
+	 * The number of emergency buffers held by this thread.  This is 0 in
+	 * normal operation - the emergency buffers are only used when malloc()
+	 * fails to return memory for allocating an exception.  Threads are not
+	 * permitted to hold more than 4 emergency buffers (as per recommendation
+	 * in ABI spec [3.3.1]).
+	 */
+	int emergencyBuffersHeld;
+	/**
+	 * The exception currently running in a cleanup.
+	 */
+	_Unwind_Exception *currentCleanup;
+	/**
+	 * The public part of this structure, accessible from outside of this
+	 * module.
+	 */
+	__cxa_eh_globals globals;
+};
+/**
+ * Dependent exception.  This 
+ */
+struct __cxa_dependent_exception
+{
+#if __LP64__
+	void *primaryException;
+#endif
+	std::type_info *exceptionType;
+	void (*exceptionDestructor) (void *); 
+	unexpected_handler unexpectedHandler;
+	terminate_handler terminateHandler;
+	__cxa_exception *nextException;
+	int handlerCount;
+#ifdef __arm__
+	_Unwind_Exception *nextCleanup;
+	int cleanupCount;
+#endif
+	int handlerSwitchValue;
+	const char *actionRecord;
+	const char *languageSpecificData;
+	void *catchTemp;
+	void *adjustedPtr;
+#if !__LP64__
+	void *primaryException;
+#endif
+	_Unwind_Exception unwindHeader;
+};
+
+
+namespace std
+{
+	void unexpected();
+	class exception
+	{
+		public:
+			virtual ~exception() throw();
+			virtual const char* what() const throw();
+	};
+
+}
+
+extern "C" std::type_info *__cxa_current_exception_type();
+
+/**
+ * Class of exceptions to distinguish between this and other exception types.
+ *
+ * The first four characters are the vendor ID.  Currently, we use GNUC,
+ * because we aim for ABI-compatibility with the GNU implementation, and
+ * various checks may test for equality of the class, which is incorrect.
+ */
+static const uint64_t exception_class =
+	EXCEPTION_CLASS('G', 'N', 'U', 'C', 'C', '+', '+', '\0');
+/**
+ * Class used for dependent exceptions.  
+ */
+static const uint64_t dependent_exception_class =
+	EXCEPTION_CLASS('G', 'N', 'U', 'C', 'C', '+', '+', '\x01');
+/**
+ * The low four bytes of the exception class, indicating that we conform to the
+ * Itanium C++ ABI.  This is currently unused, but should be used in the future
+ * if we change our exception class, to allow this library and libsupc++ to be
+ * linked to the same executable and both to interoperate.
+ */
+static const uint32_t abi_exception_class = 
+	GENERIC_EXCEPTION_CLASS('C', '+', '+', '\0');
+
+static bool isCXXException(uint64_t cls)
+{
+	return (cls == exception_class) || (cls == dependent_exception_class);
+}
+
+static bool isDependentException(uint64_t cls)
+{
+	return cls == dependent_exception_class;
+}
+
+static __cxa_exception *exceptionFromPointer(void *ex)
+{
+	return (__cxa_exception*)((char*)ex -
+			offsetof(struct __cxa_exception, unwindHeader));
+}
+static __cxa_exception *realExceptionFromException(__cxa_exception *ex)
+{
+	if (!isDependentException(ex->unwindHeader.exception_class)) { return ex; }
+	return ((__cxa_exception*)(((__cxa_dependent_exception*)ex)->primaryException))-1;
+}
+
+
+namespace std
+{
+	// Forward declaration of standard library terminate() function used to
+	// abort execution.
+	void terminate(void);
+}
+
+using namespace ABI_NAMESPACE;
+
+
+
+/** The global termination handler. */
+static terminate_handler terminateHandler = abort;
+/** The global unexpected exception handler. */
+static unexpected_handler unexpectedHandler = std::terminate;
+
+/** Key used for thread-local data. */
+static pthread_key_t eh_key;
+
+
+/**
+ * Cleanup function, allowing foreign exception handlers to correctly destroy
+ * this exception if they catch it.
+ */
+static void exception_cleanup(_Unwind_Reason_Code reason, 
+                              struct _Unwind_Exception *ex)
+{
+	__cxa_free_exception((void*)ex);
+}
+static void dependent_exception_cleanup(_Unwind_Reason_Code reason, 
+                              struct _Unwind_Exception *ex)
+{
+
+	__cxa_free_dependent_exception((void*)ex);
+}
+
+/**
+ * Recursively walk a list of exceptions and delete them all in post-order.
+ */
+static void free_exception_list(__cxa_exception *ex)
+{
+	if (0 != ex->nextException)
+	{
+		free_exception_list(ex->nextException);
+	}
+	// __cxa_free_exception() expects to be passed the thrown object, which
+	// immediately follows the exception, not the exception itself
+	__cxa_free_exception(ex+1);
+}
+
+/**
+ * Cleanup function called when a thread exists to make certain that all of the
+ * per-thread data is deleted.
+ */
+static void thread_cleanup(void* thread_info)
+{
+	__cxa_thread_info *info = (__cxa_thread_info*)thread_info;
+	if (info->globals.caughtExceptions)
+	{
+		free_exception_list(info->globals.caughtExceptions);
+	}
+	free(thread_info);
+}
+
+
+/**
+ * Once control used to protect the key creation.
+ */
+static pthread_once_t once_control = PTHREAD_ONCE_INIT;
+
+/**
+ * We may not be linked against a full pthread implementation.  If we're not,
+ * then we need to fake the thread-local storage by storing 'thread-local'
+ * things in a global.
+ */
+static bool fakeTLS;
+/**
+ * Thread-local storage for a single-threaded program.
+ */
+static __cxa_thread_info singleThreadInfo;
+/**
+ * Initialise eh_key.
+ */
+static void init_key(void)
+{
+	if ((0 == pthread_key_create) ||
+	    (0 == pthread_setspecific) ||
+	    (0 == pthread_getspecific))
+	{
+		fakeTLS = true;
+		return;
+	}
+	pthread_key_create(&eh_key, thread_cleanup);
+	pthread_setspecific(eh_key, (void*)0x42);
+	fakeTLS = (pthread_getspecific(eh_key) != (void*)0x42);
+	pthread_setspecific(eh_key, 0);
+}
+
+/**
+ * Returns the thread info structure, creating it if it is not already created.
+ */
+static __cxa_thread_info *thread_info()
+{
+	if ((0 == pthread_once) || pthread_once(&once_control, init_key))
+	{
+		fakeTLS = true;
+	}
+	if (fakeTLS) { return &singleThreadInfo; }
+	__cxa_thread_info *info = (__cxa_thread_info*)pthread_getspecific(eh_key);
+	if (0 == info)
+	{
+		info = (__cxa_thread_info*)calloc(1, sizeof(__cxa_thread_info));
+		pthread_setspecific(eh_key, info);
+	}
+	return info;
+}
+/**
+ * Fast version of thread_info().  May fail if thread_info() is not called on
+ * this thread at least once already.
+ */
+static __cxa_thread_info *thread_info_fast()
+{
+	if (fakeTLS) { return &singleThreadInfo; }
+	return (__cxa_thread_info*)pthread_getspecific(eh_key);
+}
+/**
+ * ABI function returning the __cxa_eh_globals structure.
+ */
+extern "C" __cxa_eh_globals *ABI_NAMESPACE::__cxa_get_globals(void)
+{
+	return &(thread_info()->globals);
+}
+/**
+ * Version of __cxa_get_globals() assuming that __cxa_get_globals() has already
+ * been called at least once by this thread.
+ */
+extern "C" __cxa_eh_globals *ABI_NAMESPACE::__cxa_get_globals_fast(void)
+{
+	return &(thread_info_fast()->globals);
+}
+
+/**
+ * An emergency allocation reserved for when malloc fails.  This is treated as
+ * 16 buffers of 1KB each.
+ */
+static char emergency_buffer[16384];
+/**
+ * Flag indicating whether each buffer is allocated.
+ */
+static bool buffer_allocated[16];
+/**
+ * Lock used to protect emergency allocation.
+ */
+static pthread_mutex_t emergency_malloc_lock = PTHREAD_MUTEX_INITIALIZER;
+/**
+ * Condition variable used to wait when two threads are both trying to use the
+ * emergency malloc() buffer at once.
+ */
+static pthread_cond_t emergency_malloc_wait = PTHREAD_COND_INITIALIZER;
+
+/**
+ * Allocates size bytes from the emergency allocation mechanism, if possible.
+ * This function will fail if size is over 1KB or if this thread already has 4
+ * emergency buffers.  If all emergency buffers are allocated, it will sleep
+ * until one becomes available.
+ */
+static char *emergency_malloc(size_t size)
+{
+	if (size > 1024) { return 0; }
+
+	__cxa_thread_info *info = thread_info();
+	// Only 4 emergency buffers allowed per thread!
+	if (info->emergencyBuffersHeld > 3) { return 0; }
+
+	if (pthread_mutex_lock)
+	{
+		pthread_mutex_lock(&emergency_malloc_lock);
+	}
+	int buffer = -1;
+	while (buffer < 0)
+	{
+		// While we were sleeping on the lock, another thread might have free'd
+		// enough memory for us to use, so try the allocation again - no point
+		// using the emergency buffer if there is some real memory that we can
+		// use...
+		void *m = calloc(1, size);
+		if (0 != m)
+		{
+			if (pthread_mutex_unlock)
+			{
+				pthread_mutex_unlock(&emergency_malloc_lock);
+			}
+			return (char*)m;
+		}
+		for (int i=0 ; i<16 ; i++)
+		{
+			if (!buffer_allocated[i])
+			{
+				buffer = i;
+				buffer_allocated[i] = true;
+				break;
+			}
+		}
+		// If there still isn't a buffer available, then sleep on the condition
+		// variable.  This will be signalled when another thread releases one
+		// of the emergency buffers.
+		if (buffer < 0)
+		{
+			// If we don't have pthread_cond_wait, then there is only one
+			// thread and it's already used all of the emergency buffers, so we
+			// have no alternative but to die.  Calling abort() instead of
+			// terminate, because terminate can throw exceptions, which can
+			// bring us back here and infinite loop.
+			if (!pthread_cond_wait)
+			{
+				fputs("Terminating while out of memory trying to throw an exception",
+				      stderr);
+				abort();
+			}
+			pthread_cond_wait(&emergency_malloc_wait, &emergency_malloc_lock);
+		}
+	}
+	if (pthread_mutex_unlock)
+	{
+		pthread_mutex_unlock(&emergency_malloc_lock);
+	}
+	info->emergencyBuffersHeld++;
+	return emergency_buffer + (1024 * buffer);
+}
+
+/**
+ * Frees a buffer returned by emergency_malloc().
+ *
+ * Note: Neither this nor emergency_malloc() is particularly efficient.  This
+ * should not matter, because neither will be called in normal operation - they
+ * are only used when the program runs out of memory, which should not happen
+ * often.
+ */
+static void emergency_malloc_free(char *ptr)
+{
+	int buffer = -1;
+	// Find the buffer corresponding to this pointer.
+	for (int i=0 ; i<16 ; i++)
+	{
+		if (ptr == (void*)(emergency_buffer + (1024 * i)))
+		{
+			buffer = i;
+			break;
+		}
+	}
+	assert(buffer > 0 &&
+	       "Trying to free something that is not an emergency buffer!");
+	// emergency_malloc() is expected to return 0-initialized data.  We don't
+	// zero the buffer when allocating it, because the static buffers will
+	// begin life containing 0 values.
+	memset((void*)ptr, 0, 1024);
+	// Signal the condition variable to wake up any threads that are blocking
+	// waiting for some space in the emergency buffer
+	if (pthread_mutex_lock)
+	{
+		pthread_mutex_lock(&emergency_malloc_lock);
+	}
+	// In theory, we don't need to do this with the lock held.  In practice,
+	// our array of bools will probably be updated using 32-bit or 64-bit
+	// memory operations, so this update may clobber adjacent values.
+	buffer_allocated[buffer] = false;
+	if (pthread_cond_signal && pthread_mutex_unlock)
+	{
+		pthread_cond_signal(&emergency_malloc_wait);
+		pthread_mutex_unlock(&emergency_malloc_lock);
+	}
+}
+
+static char *alloc_or_die(size_t size)
+{
+	char *buffer = (char*)calloc(1, size);
+
+	// If calloc() doesn't want to give us any memory, try using an emergency
+	// buffer.
+	if (0 == buffer)
+	{
+		buffer = emergency_malloc(size);
+		// This is only reached if the allocation is greater than 1KB, and
+		// anyone throwing objects that big really should know better.  
+		if (0 == buffer)
+		{
+			fprintf(stderr, "Out of memory attempting to allocate exception\n");
+			std::terminate();
+		}
+	}
+	return buffer;
+}
+static void free_exception(char *e)
+{
+	// If this allocation is within the address range of the emergency buffer,
+	// don't call free() because it was not allocated with malloc()
+	if ((e > emergency_buffer) &&
+	    (e < (emergency_buffer + sizeof(emergency_buffer))))
+	{
+		emergency_malloc_free(e);
+	}
+	else
+	{
+		free(e);
+	}
+}
+
+/**
+ * Allocates an exception structure.  Returns a pointer to the space that can
+ * be used to store an object of thrown_size bytes.  This function will use an
+ * emergency buffer if malloc() fails, and may block if there are no such
+ * buffers available.
+ */
+extern "C" void *__cxa_allocate_exception(size_t thrown_size)
+{
+	size_t size = thrown_size + sizeof(__cxa_exception);
+	char *buffer = alloc_or_die(size);
+	return buffer+sizeof(__cxa_exception);
+}
+
+extern "C" void *__cxa_allocate_dependent_exception(void)
+{
+	size_t size = sizeof(__cxa_dependent_exception);
+	char *buffer = alloc_or_die(size);
+	return buffer+sizeof(__cxa_dependent_exception);
+}
+
+/**
+ * __cxa_free_exception() is called when an exception was thrown in between
+ * calling __cxa_allocate_exception() and actually throwing the exception.
+ * This happens when the object's copy constructor throws an exception.
+ *
+ * In this implementation, it is also called by __cxa_end_catch() and during
+ * thread cleanup.
+ */
+extern "C" void __cxa_free_exception(void *thrown_exception)
+{
+	__cxa_exception *ex = ((__cxa_exception*)thrown_exception) - 1;
+	// Free the object that was thrown, calling its destructor
+	if (0 != ex->exceptionDestructor)
+	{
+		try
+		{
+			ex->exceptionDestructor(thrown_exception);
+		}
+		catch(...)
+		{
+			// FIXME: Check that this is really what the spec says to do.
+			std::terminate();
+		}
+	}
+
+	free_exception((char*)ex);
+}
+
+static void releaseException(__cxa_exception *exception)
+{
+	if (isDependentException(exception->unwindHeader.exception_class))
+	{
+		__cxa_free_dependent_exception(exception+1);
+		return;
+	}
+	if (__sync_sub_and_fetch(&exception->referenceCount, 1) == 0)
+	{
+		// __cxa_free_exception() expects to be passed the thrown object,
+		// which immediately follows the exception, not the exception
+		// itself
+		__cxa_free_exception(exception+1);
+	}
+}
+
+void __cxa_free_dependent_exception(void *thrown_exception)
+{
+	__cxa_dependent_exception *ex = ((__cxa_dependent_exception*)thrown_exception) - 1;
+	assert(isDependentException(ex->unwindHeader.exception_class));
+	if (ex->primaryException)
+	{
+		releaseException(realExceptionFromException((__cxa_exception*)ex));
+	}
+	free_exception((char*)ex);
+}
+
+/**
+ * Callback function used with _Unwind_Backtrace().
+ *
+ * Prints a stack trace.  Used only for debugging help.
+ *
+ * Note: As of FreeBSD 8.1, dladd() still doesn't work properly, so this only
+ * correctly prints function names from public, relocatable, symbols.
+ */
+static _Unwind_Reason_Code trace(struct _Unwind_Context *context, void *c)
+{
+	Dl_info myinfo;
+	int mylookup =
+		dladdr((void*)(uintptr_t)__cxa_current_exception_type, &myinfo);
+	void *ip = (void*)_Unwind_GetIP(context);
+	Dl_info info;
+	if (dladdr(ip, &info) != 0)
+	{
+		if (mylookup == 0 || strcmp(info.dli_fname, myinfo.dli_fname) != 0)
+		{
+			printf("%p:%s() in %s\n", ip, info.dli_sname, info.dli_fname);
+		}
+	}
+	return _URC_CONTINUE_UNWIND;
+}
+
+/**
+ * Report a failure that occurred when attempting to throw an exception.
+ *
+ * If the failure happened by falling off the end of the stack without finding
+ * a handler, prints a back trace before aborting.
+ */
+static void report_failure(_Unwind_Reason_Code err, __cxa_exception *thrown_exception)
+{
+	switch (err)
+	{
+		default: break;
+		case _URC_FATAL_PHASE1_ERROR:
+			fprintf(stderr, "Fatal error during phase 1 unwinding\n");
+			break;
+#ifndef __arm__
+		case _URC_FATAL_PHASE2_ERROR:
+			fprintf(stderr, "Fatal error during phase 2 unwinding\n");
+			break;
+#endif
+		case _URC_END_OF_STACK:
+			fprintf(stderr, "Terminating due to uncaught exception %p", 
+					(void*)thrown_exception);
+			thrown_exception = realExceptionFromException(thrown_exception);
+			static const __class_type_info *e_ti =
+				static_cast<const __class_type_info*>(&typeid(std::exception));
+			const __class_type_info *throw_ti =
+				dynamic_cast<const __class_type_info*>(thrown_exception->exceptionType);
+			if (throw_ti)
+			{
+				std::exception *e =
+					(std::exception*)e_ti->cast_to((void*)(thrown_exception+1),
+							throw_ti);
+				if (e)
+				{
+					fprintf(stderr, " '%s'", e->what());
+				}
+			}
+
+			size_t bufferSize = 128;
+			char *demangled = (char*)malloc(bufferSize);
+			const char *mangled = thrown_exception->exceptionType->name();
+			int status;
+			demangled = __cxa_demangle(mangled, demangled, &bufferSize, &status);
+			fprintf(stderr, " of type %s\n", 
+				status == 0 ? (const char*)demangled : mangled);
+			if (status == 0) { free(demangled); }
+			// Print a back trace if no handler is found.
+			// TODO: Make this optional
+			_Unwind_Backtrace(trace, 0);
+			break;
+	}
+	std::terminate();
+}
+
+static void throw_exception(__cxa_exception *ex)
+{
+	__cxa_thread_info *info = thread_info();
+	ex->unexpectedHandler = info->unexpectedHandler;
+	if (0 == ex->unexpectedHandler)
+	{
+		ex->unexpectedHandler = unexpectedHandler;
+	}
+	ex->terminateHandler  = info->terminateHandler;
+	if (0 == ex->terminateHandler)
+	{
+		ex->terminateHandler = terminateHandler;
+	}
+	info->globals.uncaughtExceptions++;
+
+	_Unwind_Reason_Code err = _Unwind_RaiseException(&ex->unwindHeader);
+	// The _Unwind_RaiseException() function should not return, it should
+	// unwind the stack past this function.  If it does return, then something
+	// has gone wrong.
+	report_failure(err, ex);
+}
+
+
+/**
+ * ABI function for throwing an exception.  Takes the object to be thrown (the
+ * pointer returned by __cxa_allocate_exception()), the type info for the
+ * pointee, and the destructor (if there is one) as arguments.
+ */
+extern "C" void __cxa_throw(void *thrown_exception,
+                            std::type_info *tinfo,
+                            void(*dest)(void*))
+{
+	__cxa_exception *ex = ((__cxa_exception*)thrown_exception) - 1;
+
+	ex->referenceCount = 1;
+	ex->exceptionType = tinfo;
+	
+	ex->exceptionDestructor = dest;
+	
+	ex->unwindHeader.exception_class = exception_class;
+	ex->unwindHeader.exception_cleanup = exception_cleanup;
+
+	throw_exception(ex);
+}
+
+extern "C" void __cxa_rethrow_primary_exception(void* thrown_exception)
+{
+	if (NULL == thrown_exception) { return; }
+
+	__cxa_exception *original = exceptionFromPointer(thrown_exception);
+	__cxa_dependent_exception *ex = ((__cxa_dependent_exception*)__cxa_allocate_dependent_exception())-1;
+
+	ex->primaryException = thrown_exception;
+	__cxa_increment_exception_refcount(thrown_exception);
+
+	ex->exceptionType = original->exceptionType;
+	ex->unwindHeader.exception_class = dependent_exception_class;
+	ex->unwindHeader.exception_cleanup = dependent_exception_cleanup;
+
+	throw_exception((__cxa_exception*)ex);
+}
+
+extern "C" void *__cxa_current_primary_exception(void)
+{
+	__cxa_eh_globals* globals = __cxa_get_globals();
+	__cxa_exception *ex = globals->caughtExceptions;
+
+	if (0 == ex) { return NULL; }
+	ex = realExceptionFromException(ex);
+	__sync_fetch_and_add(&ex->referenceCount, 1);
+	return ex + 1;
+}
+
+extern "C" void __cxa_increment_exception_refcount(void* thrown_exception)
+{
+	if (NULL == thrown_exception) { return; }
+	__cxa_exception *ex = ((__cxa_exception*)thrown_exception) - 1;
+	if (isDependentException(ex->unwindHeader.exception_class)) { return; }
+	__sync_fetch_and_add(&ex->referenceCount, 1);
+}
+extern "C" void __cxa_decrement_exception_refcount(void* thrown_exception)
+{
+	if (NULL == thrown_exception) { return; }
+	__cxa_exception *ex = ((__cxa_exception*)thrown_exception) - 1;
+	releaseException(ex);
+}
+
+/**
+ * ABI function.  Rethrows the current exception.  Does not remove the
+ * exception from the stack or decrement its handler count - the compiler is
+ * expected to set the landing pad for this function to the end of the catch
+ * block, and then call _Unwind_Resume() to continue unwinding once
+ * __cxa_end_catch() has been called and any cleanup code has been run.
+ */
+extern "C" void __cxa_rethrow()
+{
+	__cxa_eh_globals *globals = __cxa_get_globals();
+	// Note: We don't remove this from the caught list here, because
+	// __cxa_end_catch will be called when we unwind out of the try block.  We
+	// could probably make this faster by providing an alternative rethrow
+	// function and ensuring that all cleanup code is run before calling it, so
+	// we can skip the top stack frame when unwinding.
+	__cxa_exception *ex = globals->caughtExceptions;
+
+	if (0 == ex)
+	{
+		fprintf(stderr,
+		        "Attempting to rethrow an exception that doesn't exist!\n");
+		std::terminate();
+	}
+
+	assert(ex->handlerCount > 0 && "Rethrowing uncaught exception!");
+
+	// ex->handlerCount will be decremented in __cxa_end_catch in enclosing
+	// catch block
+	
+	// Make handler count negative. This will tell __cxa_end_catch that
+	// exception was rethrown and exception object should not be destroyed
+	// when handler count become zero
+	ex->handlerCount = -ex->handlerCount;
+
+	// Continue unwinding the stack with this exception.  This should unwind to
+	// the place in the caller where __cxa_end_catch() is called.  The caller
+	// will then run cleanup code and bounce the exception back with
+	// _Unwind_Resume().
+	_Unwind_Reason_Code err = _Unwind_Resume_or_Rethrow(&ex->unwindHeader);
+	report_failure(err, ex);
+}
+
+/**
+ * Returns the type_info object corresponding to the filter.
+ */
+static std::type_info *get_type_info_entry(_Unwind_Context *context,
+                                           dwarf_eh_lsda *lsda,
+                                           int filter)
+{
+	// Get the address of the record in the table.
+	dw_eh_ptr_t record = lsda->type_table - 
+		dwarf_size_of_fixed_size_field(lsda->type_table_encoding)*filter;
+	//record -= 4;
+	dw_eh_ptr_t start = record;
+	// Read the value, but it's probably an indirect reference...
+	int64_t offset = read_value(lsda->type_table_encoding, &record);
+
+	// (If the entry is 0, don't try to dereference it.  That would be bad.)
+	if (offset == 0) { return 0; }
+
+	// ...so we need to resolve it
+	return (std::type_info*)resolve_indirect_value(context,
+			lsda->type_table_encoding, offset, start);
+}
+
+
+
+/**
+ * Checks the type signature found in a handler against the type of the thrown
+ * object.  If ex is 0 then it is assumed to be a foreign exception and only
+ * matches cleanups.
+ */
+static bool check_type_signature(__cxa_exception *ex,
+                                 const std::type_info *type,
+                                 void *&adjustedPtr)
+{
+	// TODO: For compatibility with the GNU implementation, we should move this
+	// out into a __do_catch() virtual function in std::type_info
+	void *exception_ptr = (void*)(ex+1);
+    const std::type_info *ex_type = ex->exceptionType;
+
+	const __pointer_type_info *ptr_type =
+		dynamic_cast<const __pointer_type_info*>(ex_type);
+	if (0 != ptr_type)
+	{
+		exception_ptr = *(void**)exception_ptr;
+	}
+	// Always match a catchall, even with a foreign exception
+	//
+	// Note: A 0 here is a catchall, not a cleanup, so we return true to
+	// indicate that we found a catch.
+	//
+	// TODO: Provide a class for matching against foreign exceptions.  This is
+	// already done in libobjc2, allowing C++ exceptions to be boxed as
+	// Objective-C objects.  We should do something similar, allowing foreign
+	// exceptions to be wrapped in a C++ exception and delivered.
+	if (0 == type)
+	{
+		if (ex)
+		{
+			adjustedPtr = exception_ptr;
+		}
+		return true;
+	}
+
+	if (0 == ex) { return false; }
+
+	const __pointer_type_info *target_ptr_type =
+		dynamic_cast<const __pointer_type_info*>(type);
+
+	if (0 != ptr_type && 0 != target_ptr_type)
+	{
+		if (ptr_type->__flags & ~target_ptr_type->__flags)
+		{
+			// Handler pointer is less qualified
+			return false;
+		}
+
+		// Special case for void* handler.  
+		if(*target_ptr_type->__pointee == typeid(void))
+		{
+			adjustedPtr = exception_ptr;
+			return true;
+		}
+
+		ex_type = ptr_type->__pointee;
+		type = target_ptr_type->__pointee;
+	}
+
+	// If the types are the same, no casting is needed.
+	if (*type == *ex_type)
+	{
+		adjustedPtr = exception_ptr;
+		return true;
+	}
+
+	const __class_type_info *cls_type =
+		dynamic_cast<const __class_type_info*>(ex_type);
+	const __class_type_info *target_cls_type =
+		dynamic_cast<const __class_type_info*>(type);
+
+	if (0 != cls_type &&
+		0 != target_cls_type &&
+		cls_type->can_cast_to(target_cls_type))
+	{
+		adjustedPtr = cls_type->cast_to(exception_ptr, target_cls_type);
+		return true;
+	}
+	return false;
+}
+/**
+ * Checks whether the exception matches the type specifiers in this action
+ * record.  If the exception only matches cleanups, then this returns false.
+ * If it matches a catch (including a catchall) then it returns true.
+ *
+ * The selector argument is used to return the selector that is passed in the
+ * second exception register when installing the context.
+ */
+static handler_type check_action_record(_Unwind_Context *context,
+                                        dwarf_eh_lsda *lsda,
+                                        dw_eh_ptr_t action_record,
+                                        __cxa_exception *ex,
+                                        unsigned long *selector,
+                                        void *&adjustedPtr)
+{
+	if (!action_record) { return handler_cleanup; }
+	handler_type found = handler_none;
+	while (action_record)
+	{
+		int filter = read_sleb128(&action_record);
+		dw_eh_ptr_t action_record_offset_base = action_record;
+		int displacement = read_sleb128(&action_record);
+		action_record = displacement ? 
+			action_record_offset_base + displacement : 0;
+		// We only check handler types for C++ exceptions - foreign exceptions
+		// are only allowed for cleanup.
+		if (filter > 0 && 0 != ex)
+		{
+			std::type_info *handler_type = get_type_info_entry(context, lsda, filter);
+			if (check_type_signature(ex, handler_type, adjustedPtr))
+			{
+				*selector = filter;
+				return handler_catch;
+			}
+		}
+		else if (filter < 0 && 0 != ex)
+		{
+			bool matched = false;
+			*selector = filter;
+#ifdef __arm__
+			filter++;
+			std::type_info *handler_type = get_type_info_entry(context, lsda, filter--);
+			while (handler_type)
+			{
+				if (check_type_signature(ex, handler_type, adjustedPtr))
+				{
+					matched = true;
+					break;
+				}
+				handler_type = get_type_info_entry(context, lsda, filter--);
+			}
+#else
+			unsigned char *type_index = ((unsigned char*)lsda->type_table - filter - 1);
+			while (*type_index)
+			{
+				std::type_info *handler_type = get_type_info_entry(context, lsda, *(type_index++));
+				// If the exception spec matches a permitted throw type for
+				// this function, don't report a handler - we are allowed to
+				// propagate this exception out.
+				if (check_type_signature(ex, handler_type, adjustedPtr))
+				{
+					matched = true;
+					break;
+				}
+			}
+#endif
+			if (matched) { continue; }
+			// If we don't find an allowed exception spec, we need to install
+			// the context for this action.  The landing pad will then call the
+			// unexpected exception function.  Treat this as a catch
+			return handler_catch;
+		}
+		else if (filter == 0)
+		{
+			*selector = filter;
+			found = handler_cleanup;
+		}
+	}
+	return found;
+}
+
+static void pushCleanupException(_Unwind_Exception *exceptionObject,
+                                 __cxa_exception *ex)
+{
+#ifdef __arm__
+	__cxa_thread_info *info = thread_info_fast();
+	if (ex)
+	{
+		ex->cleanupCount++;
+		if (ex->cleanupCount > 1)
+		{
+			assert(exceptionObject == info->currentCleanup);
+			return;
+		}
+		ex->nextCleanup = info->currentCleanup;
+	}
+	info->currentCleanup = exceptionObject;
+#endif
+}
+
+/**
+ * The exception personality function.  This is referenced in the unwinding
+ * DWARF metadata and is called by the unwind library for each C++ stack frame
+ * containing catch or cleanup code.
+ */
+extern "C"
+BEGIN_PERSONALITY_FUNCTION(__gxx_personality_v0)
+	// This personality function is for version 1 of the ABI.  If you use it
+	// with a future version of the ABI, it won't know what to do, so it
+	// reports a fatal error and give up before it breaks anything.
+	if (1 != version)
+	{
+		return _URC_FATAL_PHASE1_ERROR;
+	}
+	__cxa_exception *ex = 0;
+	__cxa_exception *realEx = 0;
+
+	// If this exception is throw by something else then we can't make any
+	// assumptions about its layout beyond the fields declared in
+	// _Unwind_Exception.
+	bool foreignException = !isCXXException(exceptionClass);
+
+	// If this isn't a foreign exception, then we have a C++ exception structure
+	if (!foreignException)
+	{
+		ex = exceptionFromPointer(exceptionObject);
+		realEx = realExceptionFromException(ex);
+	}
+
+	unsigned char *lsda_addr =
+		(unsigned char*)_Unwind_GetLanguageSpecificData(context);
+
+	// No LSDA implies no landing pads - try the next frame
+	if (0 == lsda_addr) { return continueUnwinding(exceptionObject, context); }
+
+	// These two variables define how the exception will be handled.
+	dwarf_eh_action action = {0};
+	unsigned long selector = 0;
+	
+	// During the search phase, we do a complete lookup.  If we return
+	// _URC_HANDLER_FOUND, then the phase 2 unwind will call this function with
+	// a _UA_HANDLER_FRAME action, telling us to install the handler frame.  If
+	// we return _URC_CONTINUE_UNWIND, we may be called again later with a
+	// _UA_CLEANUP_PHASE action for this frame.
+	//
+	// The point of the two-stage unwind allows us to entirely avoid any stack
+	// unwinding if there is no handler.  If there are just cleanups found,
+	// then we can just panic call an abort function.
+	//
+	// Matching a handler is much more expensive than matching a cleanup,
+	// because we don't need to bother doing type comparisons (or looking at
+	// the type table at all) for a cleanup.  This means that there is no need
+	// to cache the result of finding a cleanup, because it's (quite) quick to
+	// look it up again from the action table.
+	if (actions & _UA_SEARCH_PHASE)
+	{
+		struct dwarf_eh_lsda lsda = parse_lsda(context, lsda_addr);
+
+		if (!dwarf_eh_find_callsite(context, &lsda, &action))
+		{
+			// EH range not found. This happens if exception is thrown and not
+			// caught inside a cleanup (destructor).  We should call
+			// terminate() in this case.  The catchTemp (landing pad) field of
+			// exception object will contain null when personality function is
+			// called with _UA_HANDLER_FRAME action for phase 2 unwinding.  
+			return _URC_HANDLER_FOUND;
+		}
+
+		handler_type found_handler = check_action_record(context, &lsda,
+				action.action_record, realEx, &selector, ex->adjustedPtr);
+		// If there's no action record, we've only found a cleanup, so keep
+		// searching for something real
+		if (found_handler == handler_catch)
+		{
+			// Cache the results for the phase 2 unwind, if we found a handler
+			// and this is not a foreign exception.
+			if (ex)
+			{
+				saveLandingPad(context, exceptionObject, ex, selector, action.landing_pad);
+				ex->languageSpecificData = (const char*)lsda_addr;
+				ex->actionRecord = (const char*)action.action_record;
+				// ex->adjustedPtr is set when finding the action record.
+			}
+			return _URC_HANDLER_FOUND;
+		}
+		return continueUnwinding(exceptionObject, context);
+	}
+
+
+	// If this is a foreign exception, we didn't have anywhere to cache the
+	// lookup stuff, so we need to do it again.  If this is either a forced
+	// unwind, a foreign exception, or a cleanup, then we just install the
+	// context for a cleanup.
+	if (!(actions & _UA_HANDLER_FRAME))
+	{
+		// cleanup
+		struct dwarf_eh_lsda lsda = parse_lsda(context, lsda_addr);
+		dwarf_eh_find_callsite(context, &lsda, &action);
+		if (0 == action.landing_pad) { return continueUnwinding(exceptionObject, context); }
+		handler_type found_handler = check_action_record(context, &lsda,
+				action.action_record, realEx, &selector, ex->adjustedPtr);
+		// Ignore handlers this time.
+		if (found_handler != handler_cleanup) { return continueUnwinding(exceptionObject, context); }
+		pushCleanupException(exceptionObject, ex);
+	}
+	else if (foreignException)
+	{
+		struct dwarf_eh_lsda lsda = parse_lsda(context, lsda_addr);
+		dwarf_eh_find_callsite(context, &lsda, &action);
+		check_action_record(context, &lsda, action.action_record, realEx,
+				&selector, ex->adjustedPtr);
+	}
+	else if (ex->catchTemp == 0)
+	{
+		// Uncaught exception in cleanup, calling terminate
+		std::terminate();
+	}
+	else
+	{
+		// Restore the saved info if we saved some last time.
+		loadLandingPad(context, exceptionObject, ex, &selector, &action.landing_pad);
+		ex->catchTemp = 0;
+		ex->handlerSwitchValue = 0;
+	}
+
+
+	_Unwind_SetIP(context, (unsigned long)action.landing_pad);
+	_Unwind_SetGR(context, __builtin_eh_return_data_regno(0),
+	              (unsigned long)exceptionObject);
+	_Unwind_SetGR(context, __builtin_eh_return_data_regno(1), selector);
+
+	return _URC_INSTALL_CONTEXT;
+}
+
+/**
+ * ABI function called when entering a catch statement.  The argument is the
+ * pointer passed out of the personality function.  This is always the start of
+ * the _Unwind_Exception object.  The return value for this function is the
+ * pointer to the caught exception, which is either the adjusted pointer (for
+ * C++ exceptions) of the unadjusted pointer (for foreign exceptions).
+ */
+#if __GNUC__ > 3 && __GNUC_MINOR__ > 2
+extern "C" void *__cxa_begin_catch(void *e) throw()
+#else
+extern "C" void *__cxa_begin_catch(void *e)
+#endif
+{
+	// Decrement the uncaught exceptions count
+	__cxa_eh_globals *globals = __cxa_get_globals();
+	globals->uncaughtExceptions--;
+	_Unwind_Exception *exceptionObject = (_Unwind_Exception*)e;
+
+	if (isCXXException(exceptionObject->exception_class))
+	{
+		__cxa_exception *ex =  exceptionFromPointer(exceptionObject);
+
+		if (ex->handlerCount == 0)
+		{
+			// Add this to the front of the list of exceptions being handled
+			// and increment its handler count so that it won't be deleted
+			// prematurely.
+			ex->nextException = globals->caughtExceptions;
+			globals->caughtExceptions = ex;
+		}
+
+		if (ex->handlerCount < 0)
+		{
+			// Rethrown exception is catched before end of catch block.
+			// Clear the rethrow flag (make value positive) - we are allowed
+			// to delete this exception at the end of the catch block, as long
+			// as it isn't thrown again later.
+			
+			// Code pattern:
+			//
+			// try {
+			//     throw x;
+			// }
+			// catch() {
+			//     try {
+			//         throw;
+			//     }
+			//     catch() {
+			//         __cxa_begin_catch() <- we are here
+			//     }
+			// }
+			ex->handlerCount = -ex->handlerCount + 1;
+		}
+		else
+		{
+			ex->handlerCount++;
+		}
+		
+		return ex->adjustedPtr;
+	}
+	// exceptionObject is the pointer to the _Unwind_Exception within the
+	// __cxa_exception.  The throw object is after this
+	return ((char*)exceptionObject + sizeof(_Unwind_Exception));
+}
+
+
+
+/**
+ * ABI function called when exiting a catch block.  This will free the current
+ * exception if it is no longer referenced in other catch blocks.
+ */
+extern "C" void __cxa_end_catch()
+{
+	// We can call the fast version here because the slow version is called in
+	// __cxa_throw(), which must have been called before we end a catch block
+	__cxa_eh_globals *globals = __cxa_get_globals_fast();
+	__cxa_exception *ex = globals->caughtExceptions;
+
+	assert(0 != ex && "Ending catch when no exception is on the stack!");
+
+	bool deleteException = true;
+
+	if (ex->handlerCount < 0)
+	{
+		// exception was rethrown. Exception should not be deleted even if
+		// handlerCount become zero.
+		// Code pattern:
+		// try {
+		//     throw x;
+		// }
+		// catch() {
+		//     {
+		//         throw;
+		//     }
+		//     cleanup {
+		//         __cxa_end_catch();   <- we are here
+		//     }
+		// }
+		//
+		
+		ex->handlerCount++;
+		deleteException = false;
+	}
+	else
+	{
+		ex->handlerCount--;
+	}
+
+	if (ex->handlerCount == 0)
+	{
+		globals->caughtExceptions = ex->nextException;
+		if (deleteException)
+		{
+			releaseException(ex);
+		}
+	}
+}
+
+/**
+ * ABI function.  Returns the type of the current exception.
+ */
+extern "C" std::type_info *__cxa_current_exception_type()
+{
+	__cxa_eh_globals *globals = __cxa_get_globals();
+	__cxa_exception *ex = globals->caughtExceptions;
+	return ex ? ex->exceptionType : 0;
+}
+
+/**
+ * ABI function, called when an exception specification is violated.
+ *
+ * This function does not return.
+ */
+extern "C" void __cxa_call_unexpected(void*exception) 
+{
+	_Unwind_Exception *exceptionObject = (_Unwind_Exception*)exception;
+	if (exceptionObject->exception_class == exception_class)
+	{
+		__cxa_exception *ex =  exceptionFromPointer(exceptionObject);
+		if (ex->unexpectedHandler)
+		{
+			ex->unexpectedHandler();
+			// Should not be reached.  
+			abort();
+		}
+	}
+	std::unexpected();
+	// Should not be reached.  
+	abort();
+}
+
+/**
+ * ABI function, returns the adjusted pointer to the exception object.
+ */
+extern "C" void *__cxa_get_exception_ptr(void *exceptionObject)
+{
+	return exceptionFromPointer(exceptionObject)->adjustedPtr;
+}
+
+/**
+ * As an extension, we provide the ability for the unexpected and terminate
+ * handlers to be thread-local.  We default to the standards-compliant
+ * behaviour where they are global.
+ */
+static bool thread_local_handlers = false;
+
+
+namespace pathscale
+{
+	/**
+	 * Sets whether unexpected and terminate handlers should be thread-local.
+	 */
+	void set_use_thread_local_handlers(bool flag) throw()
+	{
+		thread_local_handlers = flag;
+	}
+	/**
+	 * Sets a thread-local unexpected handler.  
+	 */
+	unexpected_handler set_unexpected(unexpected_handler f) throw()
+	{
+		static __cxa_thread_info *info = thread_info();
+		unexpected_handler old = info->unexpectedHandler;
+		info->unexpectedHandler = f;
+		return old;
+	}
+	/**
+	 * Sets a thread-local terminate handler.  
+	 */
+	terminate_handler set_terminate(terminate_handler f) throw()
+	{
+		static __cxa_thread_info *info = thread_info();
+		terminate_handler old = info->terminateHandler;
+		info->terminateHandler = f;
+		return old;
+	}
+}
+
+namespace std
+{
+	/**
+	 * Sets the function that will be called when an exception specification is
+	 * violated.
+	 */
+	unexpected_handler set_unexpected(unexpected_handler f) throw()
+	{
+		if (thread_local_handlers) { return pathscale::set_unexpected(f); }
+
+		return __sync_lock_test_and_set(&unexpectedHandler, f);
+	}
+	/**
+	 * Sets the function that is called to terminate the program.
+	 */
+	terminate_handler set_terminate(terminate_handler f) throw()
+	{
+		if (thread_local_handlers) { return pathscale::set_terminate(f); }
+		return __sync_lock_test_and_set(&terminateHandler, f);
+	}
+	/**
+	 * Terminates the program, calling a custom terminate implementation if
+	 * required.
+	 */
+	void terminate()
+	{
+		static __cxa_thread_info *info = thread_info_fast();
+		if (0 != info && 0 != info->terminateHandler)
+		{
+			info->terminateHandler();
+			// Should not be reached - a terminate handler is not expected to
+			// return.
+			abort();
+		}
+		terminateHandler();
+	}
+	/**
+	 * Called when an unexpected exception is encountered (i.e. an exception
+	 * violates an exception specification).  This calls abort() unless a
+	 * custom handler has been set..
+	 */
+	void unexpected()
+	{
+		static __cxa_thread_info *info = thread_info_fast();
+		if (0 != info && 0 != info->unexpectedHandler)
+		{
+			info->unexpectedHandler();
+			// Should not be reached - a terminate handler is not expected to
+			// return.
+			abort();
+		}
+		unexpectedHandler();
+	}
+	/**
+	 * Returns whether there are any exceptions currently being thrown that
+	 * have not been caught.  This can occur inside a nested catch statement.
+	 */
+	bool uncaught_exception() throw()
+	{
+		__cxa_thread_info *info = thread_info();
+		return info->globals.uncaughtExceptions != 0;
+	}
+	/**
+	 * Returns the current unexpected handler.
+	 */
+	unexpected_handler get_unexpected() throw()
+	{
+		__cxa_thread_info *info = thread_info();
+		if (info->unexpectedHandler)
+		{
+			return info->unexpectedHandler;
+		}
+		return unexpectedHandler;
+	}
+	/**
+	 * Returns the current terminate handler.
+	 */
+	terminate_handler get_terminate() throw()
+	{
+		__cxa_thread_info *info = thread_info();
+		if (info->terminateHandler)
+		{
+			return info->terminateHandler;
+		}
+		return terminateHandler;
+	}
+}
+#ifdef __arm__
+extern "C" _Unwind_Exception *__cxa_get_cleanup(void)
+{
+	__cxa_thread_info *info = thread_info_fast();
+	_Unwind_Exception *exceptionObject = info->currentCleanup;
+	if (isCXXException(exceptionObject->exception_class))
+	{
+		__cxa_exception *ex =  exceptionFromPointer(exceptionObject);
+		ex->cleanupCount--;
+		if (ex->cleanupCount == 0)
+		{
+			info->currentCleanup = ex->nextCleanup;
+			ex->nextCleanup = 0;
+		}
+	}
+	else
+	{
+		info->currentCleanup = 0;
+	}
+	return exceptionObject;
+}
+
+asm (
+".pushsection .text.__cxa_end_cleanup    \n"
+".global __cxa_end_cleanup               \n"
+".type __cxa_end_cleanup, \"function\"   \n"
+"__cxa_end_cleanup:                      \n"
+"	push {r1, r2, r3, r4}                \n"
+"	bl __cxa_get_cleanup                 \n"
+"	push {r1, r2, r3, r4}                \n"
+"	b _Unwind_Resume                     \n"
+"	bl abort                             \n"
+".popsection                             \n"
+);
+#endif
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/libcxxrt/guard.cc
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/contrib/libcxxrt/guard.cc	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,134 @@
+/**
+ * guard.cc: Functions for thread-safe static initialisation.
+ *
+ * Static values in C++ can be initialised lazily their first use.  This file
+ * contains functions that are used to ensure that two threads attempting to
+ * initialize the same static do not call the constructor twice.  This is
+ * important because constructors can have side effects, so calling the
+ * constructor twice may be very bad.
+ *
+ * Statics that require initialisation are protected by a 64-bit value.  Any
+ * platform that can do 32-bit atomic test and set operations can use this
+ * value as a low-overhead lock.  Because statics (in most sane code) are
+ * accessed far more times than they are initialised, this lock implementation
+ * is heavily optimised towards the case where the static has already been
+ * initialised.  
+ */
+#include <stdint.h>
+#include <pthread.h>
+#include <assert.h>
+
+#ifdef __arm__
+// ARM ABI - 32-bit guards.
+
+/**
+ * Acquires a lock on a guard, returning 0 if the object has already been
+ * initialised, and 1 if it has not.  If the object is already constructed then
+ * this function just needs to read a byte from memory and return.
+ */
+extern "C" int __cxa_guard_acquire(volatile int32_t *guard_object)
+{
+	if ((1<<31) == *guard_object) { return 0; }
+	// If we can atomically move the value from 0 -> 1, then this is
+	// uninitialised.
+	if (__sync_bool_compare_and_swap(guard_object, 0, 1))
+	{
+		return 1;
+	}
+	// If the value is not 0, some other thread was initialising this.  Spin
+	// until it's finished.
+	while (__sync_bool_compare_and_swap(guard_object, (1<<31), (1<<31)))
+	{
+		// If the other thread aborted, then we grab the lock
+		if (__sync_bool_compare_and_swap(guard_object, 0, 1))
+		{
+			return 1;
+		}
+		sched_yield();
+	}
+	return 0;
+}
+
+/**
+ * Releases the lock without marking the object as initialised.  This function
+ * is called if initialising a static causes an exception to be thrown.
+ */
+extern "C" void __cxa_guard_abort(int32_t *guard_object)
+{
+	assert(__sync_bool_compare_and_swap(guard_object, 1, 0));
+}
+/**
+ * Releases the guard and marks the object as initialised.  This function is
+ * called after successful initialisation of a static.
+ */
+extern "C" void __cxa_guard_release(int32_t *guard_object)
+{
+	assert(__sync_bool_compare_and_swap(guard_object, 1, (1<<31)));
+}
+
+
+#else
+// Itanium ABI: 64-bit guards
+
+/**
+ * Returns a pointer to the low 32 bits in a 64-bit value, respecting the
+ * platform's byte order.
+ */
+static int32_t *low_32_bits(volatile int64_t *ptr)
+{
+	int32_t *low= (int32_t*)ptr;
+	// Test if the machine is big endian - constant propagation at compile time
+	// should eliminate this completely.
+	int one = 1;
+	if (*(char*)&one != 1)
+	{
+		low++;
+	}
+	return low;
+}
+
+/**
+ * Acquires a lock on a guard, returning 0 if the object has already been
+ * initialised, and 1 if it has not.  If the object is already constructed then
+ * this function just needs to read a byte from memory and return.
+ */
+extern "C" int __cxa_guard_acquire(volatile int64_t *guard_object)
+{
+	char first_byte = (*guard_object) >> 56;
+	if (1 == first_byte) { return 0; }
+	int32_t *lock = low_32_bits(guard_object);
+	// Simple spin lock using the low 32 bits.  We assume that concurrent
+	// attempts to initialize statics are very rare, so we don't need to
+	// optimise for the case where we have lots of threads trying to acquire
+	// the lock at the same time.
+	while (!__sync_bool_compare_and_swap_4(lock, 0, 1))
+	{
+		sched_yield();
+	}
+	// We have to test the guard again, in case another thread has performed
+	// the initialisation while we were trying to acquire the lock.
+	first_byte = (*guard_object) >> 56;
+	return (1 != first_byte);
+}
+
+/**
+ * Releases the lock without marking the object as initialised.  This function
+ * is called if initialising a static causes an exception to be thrown.
+ */
+extern "C" void __cxa_guard_abort(int64_t *guard_object)
+{
+	int32_t *lock = low_32_bits(guard_object);
+	*lock = 0;
+}
+/**
+ * Releases the guard and marks the object as initialised.  This function is
+ * called after successful initialisation of a static.
+ */
+extern "C" void __cxa_guard_release(int64_t *guard_object)
+{
+	// Set the first byte to 1
+	*guard_object |= ((int64_t)1) << 56;
+	__cxa_guard_abort(guard_object);
+}
+
+#endif
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/libcxxrt/libelftc_dem_gnu3.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/contrib/libcxxrt/libelftc_dem_gnu3.c	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,3473 @@
+/*-
+ * Copyright (c) 2007, 2008 Hyogeol Lee <hyogeollee at gmail.com>
+ * 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
+ *    in this position and unchanged.
+ * 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 ``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 <sys/types.h>
+#include <assert.h>
+#include <ctype.h>
+#include <errno.h>
+#include <limits.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+/**
+ * @file cpp_demangle.c
+ * @brief Decode IA-64 C++ ABI style implementation.
+ *
+ * IA-64 standard ABI(Itanium C++ ABI) references.
+ *
+ * http://www.codesourcery.com/cxx-abi/abi.html#mangling \n
+ * http://www.codesourcery.com/cxx-abi/abi-mangling.html
+ */
+
+/** @brief Dynamic vector data for string. */
+struct vector_str {
+	/** Current size */
+	size_t		size;
+	/** Total capacity */
+	size_t		capacity;
+	/** String array */
+	char		**container;
+};
+
+#define BUFFER_GROWFACTOR	1.618
+#define VECTOR_DEF_CAPACITY	8
+#define	ELFTC_ISDIGIT(C) 	(isdigit((C) & 0xFF))
+
+enum type_qualifier {
+	TYPE_PTR, TYPE_REF, TYPE_CMX, TYPE_IMG, TYPE_EXT, TYPE_RST, TYPE_VAT,
+	TYPE_CST
+};
+
+struct vector_type_qualifier {
+	size_t size, capacity;
+	enum type_qualifier *q_container;
+	struct vector_str ext_name;
+};
+
+enum read_cmd {
+	READ_FAIL, READ_NEST, READ_TMPL, READ_EXPR, READ_EXPL, READ_LOCAL,
+	READ_TYPE, READ_FUNC, READ_PTRMEM
+};
+
+struct vector_read_cmd {
+	size_t size, capacity;
+	enum read_cmd *r_container;
+};
+
+struct cpp_demangle_data {
+	struct vector_str	 output;	/* output string vector */
+	struct vector_str	 output_tmp;
+	struct vector_str	 subst;		/* substitution string vector */
+	struct vector_str	 tmpl;
+	struct vector_str	 class_type;
+	struct vector_read_cmd	 cmd;
+	bool			 paren;		/* parenthesis opened */
+	bool			 pfirst;	/* first element of parameter */
+	bool			 mem_rst;	/* restrict member function */
+	bool			 mem_vat;	/* volatile member function */
+	bool			 mem_cst;	/* const member function */
+	int			 func_type;
+	const char		*cur;		/* current mangled name ptr */
+	const char		*last_sname;	/* last source name */
+	int			 push_head;
+};
+
+#define	CPP_DEMANGLE_TRY_LIMIT	128
+#define	FLOAT_SPRINTF_TRY_LIMIT	5
+#define	FLOAT_QUADRUPLE_BYTES	16
+#define	FLOAT_EXTENED_BYTES	10
+
+#define SIMPLE_HASH(x,y)	(64 * x + y)
+
+static size_t	get_strlen_sum(const struct vector_str *v);
+static bool	vector_str_grow(struct vector_str *v);
+
+static size_t
+get_strlen_sum(const struct vector_str *v)
+{
+	size_t i, len = 0;
+
+	if (v == NULL)
+		return (0);
+
+	assert(v->size > 0);
+
+	for (i = 0; i < v->size; ++i)
+		len += strlen(v->container[i]);
+
+	return (len);
+}
+
+/**
+ * @brief Deallocate resource in vector_str.
+ */
+static void
+vector_str_dest(struct vector_str *v)
+{
+	size_t i;
+
+	if (v == NULL)
+		return;
+
+	for (i = 0; i < v->size; ++i)
+		free(v->container[i]);
+
+	free(v->container);
+}
+
+/**
+ * @brief Find string in vector_str.
+ * @param v Destination vector.
+ * @param o String to find.
+ * @param l Length of the string.
+ * @return -1 at failed, 0 at not found, 1 at found.
+ */
+static int
+vector_str_find(const struct vector_str *v, const char *o, size_t l)
+{
+	size_t i;
+
+	if (v == NULL || o == NULL)
+		return (-1);
+
+	for (i = 0; i < v->size; ++i)
+		if (strncmp(v->container[i], o, l) == 0)
+			return (1);
+
+	return (0);
+}
+
+/**
+ * @brief Get new allocated flat string from vector.
+ *
+ * If l is not NULL, return length of the string.
+ * @param v Destination vector.
+ * @param l Length of the string.
+ * @return NULL at failed or NUL terminated new allocated string.
+ */
+static char *
+vector_str_get_flat(const struct vector_str *v, size_t *l)
+{
+	ssize_t elem_pos, elem_size, rtn_size;
+	size_t i;
+	char *rtn;
+
+	if (v == NULL || v->size == 0)
+		return (NULL);
+
+	if ((rtn_size = get_strlen_sum(v)) == 0)
+		return (NULL);
+
+	if ((rtn = malloc(sizeof(char) * (rtn_size + 1))) == NULL)
+		return (NULL);
+
+	elem_pos = 0;
+	for (i = 0; i < v->size; ++i) {
+		elem_size = strlen(v->container[i]);
+
+		memcpy(rtn + elem_pos, v->container[i], elem_size);
+
+		elem_pos += elem_size;
+	}
+
+	rtn[rtn_size] = '\0';
+
+	if (l != NULL)
+		*l = rtn_size;
+
+	return (rtn);
+}
+
+static bool
+vector_str_grow(struct vector_str *v)
+{
+	size_t i, tmp_cap;
+	char **tmp_ctn;
+
+	if (v == NULL)
+		return (false);
+
+	assert(v->capacity > 0);
+
+	tmp_cap = v->capacity * BUFFER_GROWFACTOR;
+
+	assert(tmp_cap > v->capacity);
+
+	if ((tmp_ctn = malloc(sizeof(char *) * tmp_cap)) == NULL)
+		return (false);
+
+	for (i = 0; i < v->size; ++i)
+		tmp_ctn[i] = v->container[i];
+
+	free(v->container);
+
+	v->container = tmp_ctn;
+	v->capacity = tmp_cap;
+
+	return (true);
+}
+
+/**
+ * @brief Initialize vector_str.
+ * @return false at failed, true at success.
+ */
+static bool
+vector_str_init(struct vector_str *v)
+{
+
+	if (v == NULL)
+		return (false);
+
+	v->size = 0;
+	v->capacity = VECTOR_DEF_CAPACITY;
+
+	assert(v->capacity > 0);
+
+	if ((v->container = malloc(sizeof(char *) * v->capacity)) == NULL)
+		return (false);
+
+	assert(v->container != NULL);
+
+	return (true);
+}
+
+/**
+ * @brief Remove last element in vector_str.
+ * @return false at failed, true at success.
+ */
+static bool
+vector_str_pop(struct vector_str *v)
+{
+
+	if (v == NULL)
+		return (false);
+
+	if (v->size == 0)
+		return (true);
+
+	--v->size;
+
+	free(v->container[v->size]);
+	v->container[v->size] = NULL;
+
+	return (true);
+}
+
+/**
+ * @brief Push back string to vector.
+ * @return false at failed, true at success.
+ */
+static bool
+vector_str_push(struct vector_str *v, const char *str, size_t len)
+{
+
+	if (v == NULL || str == NULL)
+		return (false);
+
+	if (v->size == v->capacity && vector_str_grow(v) == false)
+		return (false);
+
+	if ((v->container[v->size] = malloc(sizeof(char) * (len + 1))) == NULL)
+		return (false);
+
+	snprintf(v->container[v->size], len + 1, "%s", str);
+
+	++v->size;
+
+	return (true);
+}
+
+/**
+ * @brief Push front org vector to det vector.
+ * @return false at failed, true at success.
+ */
+static bool
+vector_str_push_vector_head(struct vector_str *dst, struct vector_str *org)
+{
+	size_t i, j, tmp_cap;
+	char **tmp_ctn;
+
+	if (dst == NULL || org == NULL)
+		return (false);
+
+	tmp_cap = (dst->size + org->size) * BUFFER_GROWFACTOR;
+
+	if ((tmp_ctn = malloc(sizeof(char *) * tmp_cap)) == NULL)
+		return (false);
+
+	for (i = 0; i < org->size; ++i)
+		if ((tmp_ctn[i] = strdup(org->container[i])) == NULL) {
+			for (j = 0; j < i; ++j)
+				free(tmp_ctn[j]);
+
+			free(tmp_ctn);
+
+			return (false);
+		}
+
+	for (i = 0; i < dst->size; ++i)
+		tmp_ctn[i + org->size] = dst->container[i];
+
+	free(dst->container);
+
+	dst->container = tmp_ctn;
+	dst->capacity = tmp_cap;
+	dst->size += org->size;
+
+	return (true);
+}
+
+/**
+ * @brief Get new allocated flat string from vector between begin and end.
+ *
+ * If r_len is not NULL, string length will be returned.
+ * @return NULL at failed or NUL terminated new allocated string.
+ */
+static char *
+vector_str_substr(const struct vector_str *v, size_t begin, size_t end,
+    size_t *r_len)
+{
+	size_t cur, i, len;
+	char *rtn;
+
+	if (v == NULL || begin > end)
+		return (NULL);
+
+	len = 0;
+	for (i = begin; i < end + 1; ++i)
+		len += strlen(v->container[i]);
+
+	if ((rtn = malloc(sizeof(char) * (len + 1))) == NULL)
+		return (NULL);
+
+	if (r_len != NULL)
+		*r_len = len;
+
+	cur = 0;
+	for (i = begin; i < end + 1; ++i) {
+		len = strlen(v->container[i]);
+		memcpy(rtn + cur, v->container[i], len);
+		cur += len;
+	}
+	rtn[cur] = '\0';
+
+	return (rtn);
+}
+
+static void	cpp_demangle_data_dest(struct cpp_demangle_data *);
+static int	cpp_demangle_data_init(struct cpp_demangle_data *,
+		    const char *);
+static int	cpp_demangle_get_subst(struct cpp_demangle_data *, size_t);
+static int	cpp_demangle_get_tmpl_param(struct cpp_demangle_data *, size_t);
+static int	cpp_demangle_push_fp(struct cpp_demangle_data *,
+		    char *(*)(const char *, size_t));
+static int	cpp_demangle_push_str(struct cpp_demangle_data *, const char *,
+		    size_t);
+static int	cpp_demangle_push_subst(struct cpp_demangle_data *,
+		    const char *, size_t);
+static int	cpp_demangle_push_subst_v(struct cpp_demangle_data *,
+		    struct vector_str *);
+static int	cpp_demangle_push_type_qualifier(struct cpp_demangle_data *,
+		    struct vector_type_qualifier *, const char *);
+static int	cpp_demangle_read_array(struct cpp_demangle_data *);
+static int	cpp_demangle_read_encoding(struct cpp_demangle_data *);
+static int	cpp_demangle_read_expr_primary(struct cpp_demangle_data *);
+static int	cpp_demangle_read_expression(struct cpp_demangle_data *);
+static int	cpp_demangle_read_expression_binary(struct cpp_demangle_data *,
+		    const char *, size_t);
+static int	cpp_demangle_read_expression_unary(struct cpp_demangle_data *,
+		    const char *, size_t);
+static int	cpp_demangle_read_expression_trinary(struct cpp_demangle_data *,
+		    const char *, size_t, const char *, size_t);
+static int	cpp_demangle_read_function(struct cpp_demangle_data *, int *,
+		    struct vector_type_qualifier *);
+static int	cpp_demangle_read_local_name(struct cpp_demangle_data *);
+static int	cpp_demangle_read_name(struct cpp_demangle_data *);
+static int	cpp_demangle_read_nested_name(struct cpp_demangle_data *);
+static int	cpp_demangle_read_number(struct cpp_demangle_data *, long *);
+static int	cpp_demangle_read_nv_offset(struct cpp_demangle_data *);
+static int	cpp_demangle_read_offset(struct cpp_demangle_data *);
+static int	cpp_demangle_read_offset_number(struct cpp_demangle_data *);
+static int	cpp_demangle_read_pointer_to_member(struct cpp_demangle_data *);
+static int	cpp_demangle_read_sname(struct cpp_demangle_data *);
+static int	cpp_demangle_read_subst(struct cpp_demangle_data *);
+static int	cpp_demangle_read_subst_std(struct cpp_demangle_data *);
+static int	cpp_demangle_read_subst_stdtmpl(struct cpp_demangle_data *,
+		    const char *, size_t);
+static int	cpp_demangle_read_tmpl_arg(struct cpp_demangle_data *);
+static int	cpp_demangle_read_tmpl_args(struct cpp_demangle_data *);
+static int	cpp_demangle_read_tmpl_param(struct cpp_demangle_data *);
+static int	cpp_demangle_read_type(struct cpp_demangle_data *, int);
+static int	cpp_demangle_read_uqname(struct cpp_demangle_data *);
+static int	cpp_demangle_read_v_offset(struct cpp_demangle_data *);
+static char	*decode_fp_to_double(const char *, size_t);
+static char	*decode_fp_to_float(const char *, size_t);
+static char	*decode_fp_to_float128(const char *, size_t);
+static char	*decode_fp_to_float80(const char *, size_t);
+static char	*decode_fp_to_long_double(const char *, size_t);
+static int	hex_to_dec(char);
+static void	vector_read_cmd_dest(struct vector_read_cmd *);
+static int	vector_read_cmd_find(struct vector_read_cmd *, enum read_cmd);
+static int	vector_read_cmd_init(struct vector_read_cmd *);
+static int	vector_read_cmd_pop(struct vector_read_cmd *);
+static int	vector_read_cmd_push(struct vector_read_cmd *, enum read_cmd);
+static void	vector_type_qualifier_dest(struct vector_type_qualifier *);
+static int	vector_type_qualifier_init(struct vector_type_qualifier *);
+static int	vector_type_qualifier_push(struct vector_type_qualifier *,
+		    enum type_qualifier);
+
+/**
+ * @brief Decode the input string by IA-64 C++ ABI style.
+ *
+ * GNU GCC v3 use IA-64 standard ABI.
+ * @return New allocated demangled string or NULL if failed.
+ * @todo 1. Testing and more test case. 2. Code cleaning.
+ */
+char *
+__cxa_demangle_gnu3(const char *org)
+{
+	struct cpp_demangle_data ddata;
+	ssize_t org_len;
+	unsigned int limit;
+	char *rtn;
+
+	if (org == NULL)
+		return (NULL);
+
+	// Try demangling as a type for short encodings
+	if (((org_len = strlen(org)) < 2) || (org[0] != '_' || org[1] != 'Z' )) {
+		if (!cpp_demangle_data_init(&ddata, org))
+			return (NULL);
+		if (!cpp_demangle_read_type(&ddata, 0))
+			goto clean;
+		rtn = vector_str_get_flat(&ddata.output, (size_t *) NULL);
+		goto clean;
+	}
+	if (org_len > 11 && !strncmp(org, "_GLOBAL__I_", 11)) {
+		if ((rtn = malloc(org_len + 19)) == NULL)
+			return (NULL);
+		snprintf(rtn, org_len + 19,
+		    "global constructors keyed to %s", org + 11);
+		return (rtn);
+	}
+
+
+	if (!cpp_demangle_data_init(&ddata, org + 2))
+		return (NULL);
+
+	rtn = NULL;
+
+	if (!cpp_demangle_read_encoding(&ddata))
+		goto clean;
+
+	limit = 0;
+	while (*ddata.cur != '\0') {
+		/*
+		 * Breaking at some gcc info at tail. e.g) @@GLIBCXX_3.4
+		 */
+		if (*ddata.cur == '@' && *(ddata.cur + 1) == '@')
+			break;
+		if (!cpp_demangle_read_type(&ddata, 1))
+			goto clean;
+		if (limit++ > CPP_DEMANGLE_TRY_LIMIT)
+			goto clean;
+	}
+
+	if (ddata.output.size == 0)
+		goto clean;
+	if (ddata.paren && !vector_str_push(&ddata.output, ")", 1))
+		goto clean;
+	if (ddata.mem_vat && !vector_str_push(&ddata.output, " volatile", 9))
+		goto clean;
+	if (ddata.mem_cst && !vector_str_push(&ddata.output, " const", 6))
+		goto clean;
+	if (ddata.mem_rst && !vector_str_push(&ddata.output, " restrict", 9))
+		goto clean;
+
+	rtn = vector_str_get_flat(&ddata.output, (size_t *) NULL);
+
+clean:
+	cpp_demangle_data_dest(&ddata);
+
+	return (rtn);
+}
+
+static void
+cpp_demangle_data_dest(struct cpp_demangle_data *d)
+{
+
+	if (d == NULL)
+		return;
+
+	vector_read_cmd_dest(&d->cmd);
+	vector_str_dest(&d->class_type);
+	vector_str_dest(&d->tmpl);
+	vector_str_dest(&d->subst);
+	vector_str_dest(&d->output_tmp);
+	vector_str_dest(&d->output);
+}
+
+static int
+cpp_demangle_data_init(struct cpp_demangle_data *d, const char *cur)
+{
+
+	if (d == NULL || cur == NULL)
+		return (0);
+
+	if (!vector_str_init(&d->output))
+		return (0);
+	if (!vector_str_init(&d->output_tmp))
+		goto clean1;
+	if (!vector_str_init(&d->subst))
+		goto clean2;
+	if (!vector_str_init(&d->tmpl))
+		goto clean3;
+	if (!vector_str_init(&d->class_type))
+		goto clean4;
+	if (!vector_read_cmd_init(&d->cmd))
+		goto clean5;
+
+	assert(d->output.container != NULL);
+	assert(d->output_tmp.container != NULL);
+	assert(d->subst.container != NULL);
+	assert(d->tmpl.container != NULL);
+	assert(d->class_type.container != NULL);
+
+	d->paren = false;
+	d->pfirst = false;
+	d->mem_rst = false;
+	d->mem_vat = false;
+	d->mem_cst = false;
+	d->func_type = 0;
+	d->cur = cur;
+	d->last_sname = NULL;
+	d->push_head = 0;
+
+	return (1);
+
+clean5:
+	vector_str_dest(&d->class_type);
+clean4:
+	vector_str_dest(&d->tmpl);
+clean3:
+	vector_str_dest(&d->subst);
+clean2:
+	vector_str_dest(&d->output_tmp);
+clean1:
+	vector_str_dest(&d->output);
+
+	return (0);
+}
+
+static int
+cpp_demangle_push_fp(struct cpp_demangle_data *ddata,
+    char *(*decoder)(const char *, size_t))
+{
+	size_t len;
+	int rtn;
+	const char *fp;
+	char *f;
+
+	if (ddata == NULL || decoder == NULL)
+		return (0);
+
+	fp = ddata->cur;
+	while (*ddata->cur != 'E')
+		++ddata->cur;
+	++ddata->cur;
+
+	if ((f = decoder(fp, ddata->cur - fp)) == NULL)
+		return (0);
+
+	rtn = 0;
+	if ((len = strlen(f)) > 0 &&
+	    cpp_demangle_push_str(ddata, f, len))
+		rtn = 1;
+
+	free(f);
+
+	return (0);
+}
+
+static int
+cpp_demangle_push_str(struct cpp_demangle_data *ddata, const char *str,
+    size_t len)
+{
+
+	if (ddata == NULL || str == NULL || len == 0)
+		return (0);
+
+	if (ddata->push_head > 0)
+		return (vector_str_push(&ddata->output_tmp, str, len));
+
+	return (vector_str_push(&ddata->output, str, len));
+}
+
+static int
+cpp_demangle_push_subst(struct cpp_demangle_data *ddata, const char *str,
+    size_t len)
+{
+
+	if (ddata == NULL || str == NULL || len == 0)
+		return (0);
+
+	if (!vector_str_find(&ddata->subst, str, len))
+		return (vector_str_push(&ddata->subst, str, len));
+
+	return (1);
+}
+
+static int
+cpp_demangle_push_subst_v(struct cpp_demangle_data *ddata, struct vector_str *v)
+{
+	size_t str_len;
+	int rtn;
+	char *str;
+
+	if (ddata == NULL || v == NULL)
+		return (0);
+
+	if ((str = vector_str_get_flat(v, &str_len)) == NULL)
+		return (0);
+
+	rtn = cpp_demangle_push_subst(ddata, str, str_len);
+	free(str);
+
+	return (rtn);
+}
+
+static int
+cpp_demangle_push_type_qualifier(struct cpp_demangle_data *ddata,
+    struct vector_type_qualifier *v, const char *type_str)
+{
+	struct vector_str subst_v;
+	size_t idx, e_idx, e_len;
+	int rtn;
+	char *buf;
+
+	if (ddata == NULL || v == NULL)
+		return (0);
+
+	if ((idx = v->size) == 0)
+		return (1);
+
+	rtn = 0;
+	if (type_str != NULL) {
+		if (!vector_str_init(&subst_v))
+			return (0);
+		if (!vector_str_push(&subst_v, type_str, strlen(type_str)))
+			goto clean;
+	}
+
+	e_idx = 0;
+	while (idx > 0) {
+		switch (v->q_container[idx - 1]) {
+		case TYPE_PTR:
+			if (!cpp_demangle_push_str(ddata, "*", 1))
+				goto clean;
+			if (type_str != NULL) {
+				if (!vector_str_push(&subst_v, "*", 1))
+					goto clean;
+				if (!cpp_demangle_push_subst_v(ddata, &subst_v))
+					goto clean;
+			}
+			break;
+
+		case TYPE_REF:
+			if (!cpp_demangle_push_str(ddata, "&", 1))
+				goto clean;
+			if (type_str != NULL) {
+				if (!vector_str_push(&subst_v, "&", 1))
+					goto clean;
+				if (!cpp_demangle_push_subst_v(ddata, &subst_v))
+					goto clean;
+			}
+			break;
+
+		case TYPE_CMX:
+			if (!cpp_demangle_push_str(ddata, " complex", 8))
+				goto clean;
+			if (type_str != NULL) {
+				if (!vector_str_push(&subst_v, " complex", 8))
+					goto clean;
+				if (!cpp_demangle_push_subst_v(ddata, &subst_v))
+					goto clean;
+			}
+			break;
+
+		case TYPE_IMG:
+			if (!cpp_demangle_push_str(ddata, " imaginary", 10))
+				goto clean;
+			if (type_str != NULL) {
+				if (!vector_str_push(&subst_v, " imaginary", 10))
+					goto clean;
+				if (!cpp_demangle_push_subst_v(ddata, &subst_v))
+					goto clean;
+			}
+			break;
+
+		case TYPE_EXT:
+			if (e_idx > v->ext_name.size - 1)
+				goto clean;
+			if ((e_len = strlen(v->ext_name.container[e_idx])) == 0)
+				goto clean;
+			if ((buf = malloc(sizeof(char) * (e_len + 1))) == NULL)
+				goto clean;
+
+			memcpy(buf, " ", 1);
+			memcpy(buf + 1, v->ext_name.container[e_idx], e_len);
+
+			if (!cpp_demangle_push_str(ddata, buf, e_len + 1)) {
+				free(buf);
+				goto clean;
+			}
+
+			if (type_str != NULL) {
+				if (!vector_str_push(&subst_v, buf,
+				    e_len + 1)) {
+					free(buf);
+					goto clean;
+				}
+				if (!cpp_demangle_push_subst_v(ddata, &subst_v)) {
+					free(buf);
+					goto clean;
+				}
+			}
+			free(buf);
+			++e_idx;
+			break;
+
+		case TYPE_RST:
+			if (!cpp_demangle_push_str(ddata, " restrict", 9))
+				goto clean;
+			if (type_str != NULL) {
+				if (!vector_str_push(&subst_v, " restrict", 9))
+					goto clean;
+				if (!cpp_demangle_push_subst_v(ddata, &subst_v))
+					goto clean;
+			}
+			break;
+
+		case TYPE_VAT:
+			if (!cpp_demangle_push_str(ddata, " volatile", 9))
+				goto clean;
+			if (type_str != NULL) {
+				if (!vector_str_push(&subst_v, " volatile", 9))
+					goto clean;
+				if (!cpp_demangle_push_subst_v(ddata, &subst_v))
+					goto clean;
+			}
+			break;
+
+		case TYPE_CST:
+			if (!cpp_demangle_push_str(ddata, " const", 6))
+				goto clean;
+			if (type_str != NULL) {
+				if (!vector_str_push(&subst_v, " const", 6))
+					goto clean;
+				if (!cpp_demangle_push_subst_v(ddata, &subst_v))
+					goto clean;
+			}
+			break;
+
+		};
+		--idx;
+	}
+
+	rtn = 1;
+clean:
+	if (type_str != NULL)
+		vector_str_dest(&subst_v);
+
+	return (rtn);
+}
+
+static int
+cpp_demangle_get_subst(struct cpp_demangle_data *ddata, size_t idx)
+{
+	size_t len;
+
+	if (ddata == NULL || ddata->subst.size <= idx)
+		return (0);
+	if ((len = strlen(ddata->subst.container[idx])) == 0)
+		return (0);
+	if (!cpp_demangle_push_str(ddata, ddata->subst.container[idx], len))
+		return (0);
+
+	/* skip '_' */
+	++ddata->cur;
+
+	return (1);
+}
+
+static int
+cpp_demangle_get_tmpl_param(struct cpp_demangle_data *ddata, size_t idx)
+{
+	size_t len;
+
+	if (ddata == NULL || ddata->tmpl.size <= idx)
+		return (0);
+	if ((len = strlen(ddata->tmpl.container[idx])) == 0)
+		return (0);
+	if (!cpp_demangle_push_str(ddata, ddata->tmpl.container[idx], len))
+		return (0);
+
+	++ddata->cur;
+
+	return (1);
+}
+
+static int
+cpp_demangle_read_array(struct cpp_demangle_data *ddata)
+{
+	size_t i, num_len, exp_len, p_idx, idx;
+	const char *num;
+	char *exp;
+
+	if (ddata == NULL || *(++ddata->cur) == '\0')
+		return (0);
+
+	if (*ddata->cur == '_') {
+		if (*(++ddata->cur) == '\0')
+			return (0);
+
+		if (!cpp_demangle_read_type(ddata, 0))
+			return (0);
+
+		if (!cpp_demangle_push_str(ddata, "[]", 2))
+			return (0);
+	} else {
+		if (ELFTC_ISDIGIT(*ddata->cur) != 0) {
+			num = ddata->cur;
+			while (ELFTC_ISDIGIT(*ddata->cur) != 0)
+				++ddata->cur;
+			if (*ddata->cur != '_')
+				return (0);
+			num_len = ddata->cur - num;
+			assert(num_len > 0);
+			if (*(++ddata->cur) == '\0')
+				return (0);
+			if (!cpp_demangle_read_type(ddata, 0))
+				return (0);
+			if (!cpp_demangle_push_str(ddata, "[", 1))
+				return (0);
+			if (!cpp_demangle_push_str(ddata, num, num_len))
+				return (0);
+			if (!cpp_demangle_push_str(ddata, "]", 1))
+				return (0);
+		} else {
+			p_idx = ddata->output.size;
+			if (!cpp_demangle_read_expression(ddata))
+				return (0);
+			if ((exp = vector_str_substr(&ddata->output, p_idx,
+				 ddata->output.size - 1, &exp_len)) == NULL)
+				return (0);
+			idx = ddata->output.size;
+			for (i = p_idx; i < idx; ++i)
+				if (!vector_str_pop(&ddata->output)) {
+					free(exp);
+					return (0);
+				}
+			if (*ddata->cur != '_') {
+				free(exp);
+				return (0);
+			}
+			++ddata->cur;
+			if (*ddata->cur == '\0') {
+				free(exp);
+				return (0);
+			}
+			if (!cpp_demangle_read_type(ddata, 0)) {
+				free(exp);
+				return (0);
+			}
+			if (!cpp_demangle_push_str(ddata, "[", 1)) {
+				free(exp);
+				return (0);
+			}
+			if (!cpp_demangle_push_str(ddata, exp, exp_len)) {
+				free(exp);
+				return (0);
+			}
+			if (!cpp_demangle_push_str(ddata, "]", 1)) {
+				free(exp);
+				return (0);
+			}
+			free(exp);
+		}
+	}
+
+	return (1);
+}
+
+static int
+cpp_demangle_read_expr_primary(struct cpp_demangle_data *ddata)
+{
+	const char *num;
+
+	if (ddata == NULL || *(++ddata->cur) == '\0')
+		return (0);
+
+	if (*ddata->cur == '_' && *(ddata->cur + 1) == 'Z') {
+		ddata->cur += 2;
+		if (*ddata->cur == '\0')
+			return (0);
+		if (!cpp_demangle_read_encoding(ddata))
+			return (0);
+		++ddata->cur;
+		return (1);
+	}
+
+	switch (*ddata->cur) {
+	case 'b':
+		switch (*(++ddata->cur)) {
+		case '0':
+			return (cpp_demangle_push_str(ddata, "false", 5));
+		case '1':
+			return (cpp_demangle_push_str(ddata, "true", 4));
+		default:
+			return (0);
+		};
+
+	case 'd':
+		++ddata->cur;
+		return (cpp_demangle_push_fp(ddata, decode_fp_to_double));
+
+	case 'e':
+		++ddata->cur;
+		if (sizeof(long double) == 10)
+			return (cpp_demangle_push_fp(ddata,
+			    decode_fp_to_double));
+		return (cpp_demangle_push_fp(ddata, decode_fp_to_float80));
+
+	case 'f':
+		++ddata->cur;
+		return (cpp_demangle_push_fp(ddata, decode_fp_to_float));
+
+	case 'g':
+		++ddata->cur;
+		if (sizeof(long double) == 16)
+			return (cpp_demangle_push_fp(ddata,
+			    decode_fp_to_double));
+		return (cpp_demangle_push_fp(ddata, decode_fp_to_float128));
+
+	case 'i':
+	case 'j':
+	case 'l':
+	case 'm':
+	case 'n':
+	case 's':
+	case 't':
+	case 'x':
+	case 'y':
+		if (*(++ddata->cur) == 'n') {
+			if (!cpp_demangle_push_str(ddata, "-", 1))
+				return (0);
+			++ddata->cur;
+		}
+		num = ddata->cur;
+		while (*ddata->cur != 'E') {
+			if (!ELFTC_ISDIGIT(*ddata->cur))
+				return (0);
+			++ddata->cur;
+		}
+		++ddata->cur;
+		return (cpp_demangle_push_str(ddata, num, ddata->cur - num));
+
+	default:
+		return (0);
+	};
+}
+
+static int
+cpp_demangle_read_expression(struct cpp_demangle_data *ddata)
+{
+
+	if (ddata == NULL || *ddata->cur == '\0')
+		return (0);
+
+	switch (SIMPLE_HASH(*ddata->cur, *(ddata->cur + 1))) {
+	case SIMPLE_HASH('s', 't'):
+		ddata->cur += 2;
+		return (cpp_demangle_read_type(ddata, 0));
+
+	case SIMPLE_HASH('s', 'r'):
+		ddata->cur += 2;
+		if (!cpp_demangle_read_type(ddata, 0))
+			return (0);
+		if (!cpp_demangle_read_uqname(ddata))
+			return (0);
+		if (*ddata->cur == 'I')
+			return (cpp_demangle_read_tmpl_args(ddata));
+		return (1);
+
+	case SIMPLE_HASH('a', 'a'):
+		/* operator && */
+		ddata->cur += 2;
+		return (cpp_demangle_read_expression_binary(ddata, "&&", 2));
+
+	case SIMPLE_HASH('a', 'd'):
+		/* operator & (unary) */
+		ddata->cur += 2;
+		return (cpp_demangle_read_expression_unary(ddata, "&", 1));
+
+	case SIMPLE_HASH('a', 'n'):
+		/* operator & */
+		ddata->cur += 2;
+		return (cpp_demangle_read_expression_binary(ddata, "&", 1));
+
+	case SIMPLE_HASH('a', 'N'):
+		/* operator &= */
+		ddata->cur += 2;
+		return (cpp_demangle_read_expression_binary(ddata, "&=", 2));
+
+	case SIMPLE_HASH('a', 'S'):
+		/* operator = */
+		ddata->cur += 2;
+		return (cpp_demangle_read_expression_binary(ddata, "=", 1));
+
+	case SIMPLE_HASH('c', 'l'):
+		/* operator () */
+		ddata->cur += 2;
+		return (cpp_demangle_read_expression_binary(ddata, "()", 2));
+
+	case SIMPLE_HASH('c', 'm'):
+		/* operator , */
+		ddata->cur += 2;
+		return (cpp_demangle_read_expression_binary(ddata, ",", 1));
+
+	case SIMPLE_HASH('c', 'o'):
+		/* operator ~ */
+		ddata->cur += 2;
+		return (cpp_demangle_read_expression_binary(ddata, "~", 1));
+
+	case SIMPLE_HASH('c', 'v'):
+		/* operator (cast) */
+		ddata->cur += 2;
+		return (cpp_demangle_read_expression_binary(ddata, "(cast)", 6));
+
+	case SIMPLE_HASH('d', 'a'):
+		/* operator delete [] */
+		ddata->cur += 2;
+		return (cpp_demangle_read_expression_unary(ddata, "delete []", 9));
+
+	case SIMPLE_HASH('d', 'e'):
+		/* operator * (unary) */
+		ddata->cur += 2;
+		return (cpp_demangle_read_expression_unary(ddata, "*", 1));
+
+	case SIMPLE_HASH('d', 'l'):
+		/* operator delete */
+		ddata->cur += 2;
+		return (cpp_demangle_read_expression_unary(ddata, "delete", 6));
+
+	case SIMPLE_HASH('d', 'v'):
+		/* operator / */
+		ddata->cur += 2;
+		return (cpp_demangle_read_expression_binary(ddata, "/", 1));
+
+	case SIMPLE_HASH('d', 'V'):
+		/* operator /= */
+		ddata->cur += 2;
+		return (cpp_demangle_read_expression_binary(ddata, "/=", 2));
+
+	case SIMPLE_HASH('e', 'o'):
+		/* operator ^ */
+		ddata->cur += 2;
+		return (cpp_demangle_read_expression_binary(ddata, "^", 1));
+
+	case SIMPLE_HASH('e', 'O'):
+		/* operator ^= */
+		ddata->cur += 2;
+		return (cpp_demangle_read_expression_binary(ddata, "^=", 2));
+
+	case SIMPLE_HASH('e', 'q'):
+		/* operator == */
+		ddata->cur += 2;
+		return (cpp_demangle_read_expression_binary(ddata, "==", 2));
+
+	case SIMPLE_HASH('g', 'e'):
+		/* operator >= */
+		ddata->cur += 2;
+		return (cpp_demangle_read_expression_binary(ddata, ">=", 2));
+
+	case SIMPLE_HASH('g', 't'):
+		/* operator > */
+		ddata->cur += 2;
+		return (cpp_demangle_read_expression_binary(ddata, ">", 1));
+
+	case SIMPLE_HASH('i', 'x'):
+		/* operator [] */
+		ddata->cur += 2;
+		return (cpp_demangle_read_expression_binary(ddata, "[]", 2));
+
+	case SIMPLE_HASH('l', 'e'):
+		/* operator <= */
+		ddata->cur += 2;
+		return (cpp_demangle_read_expression_binary(ddata, "<=", 2));
+
+	case SIMPLE_HASH('l', 's'):
+		/* operator << */
+		ddata->cur += 2;
+		return (cpp_demangle_read_expression_binary(ddata, "<<", 2));
+
+	case SIMPLE_HASH('l', 'S'):
+		/* operator <<= */
+		ddata->cur += 2;
+		return (cpp_demangle_read_expression_binary(ddata, "<<=", 3));
+
+	case SIMPLE_HASH('l', 't'):
+		/* operator < */
+		ddata->cur += 2;
+		return (cpp_demangle_read_expression_binary(ddata, "<", 1));
+
+	case SIMPLE_HASH('m', 'i'):
+		/* operator - */
+		ddata->cur += 2;
+		return (cpp_demangle_read_expression_binary(ddata, "-", 1));
+
+	case SIMPLE_HASH('m', 'I'):
+		/* operator -= */
+		ddata->cur += 2;
+		return (cpp_demangle_read_expression_binary(ddata, "-=", 2));
+
+	case SIMPLE_HASH('m', 'l'):
+		/* operator * */
+		ddata->cur += 2;
+		return (cpp_demangle_read_expression_binary(ddata, "*", 1));
+
+	case SIMPLE_HASH('m', 'L'):
+		/* operator *= */
+		ddata->cur += 2;
+		return (cpp_demangle_read_expression_binary(ddata, "*=", 2));
+
+	case SIMPLE_HASH('m', 'm'):
+		/* operator -- */
+		ddata->cur += 2;
+		return (cpp_demangle_read_expression_binary(ddata, "--", 2));
+
+	case SIMPLE_HASH('n', 'a'):
+		/* operator new[] */
+		ddata->cur += 2;
+		return (cpp_demangle_read_expression_unary(ddata, "new []", 6));
+
+	case SIMPLE_HASH('n', 'e'):
+		/* operator != */
+		ddata->cur += 2;
+		return (cpp_demangle_read_expression_binary(ddata, "!=", 2));
+
+	case SIMPLE_HASH('n', 'g'):
+		/* operator - (unary) */
+		ddata->cur += 2;
+		return (cpp_demangle_read_expression_unary(ddata, "-", 1));
+
+	case SIMPLE_HASH('n', 't'):
+		/* operator ! */
+		ddata->cur += 2;
+		return (cpp_demangle_read_expression_binary(ddata, "!", 1));
+
+	case SIMPLE_HASH('n', 'w'):
+		/* operator new */
+		ddata->cur += 2;
+		return (cpp_demangle_read_expression_unary(ddata, "new", 3));
+
+	case SIMPLE_HASH('o', 'o'):
+		/* operator || */
+		ddata->cur += 2;
+		return (cpp_demangle_read_expression_binary(ddata, "||", 2));
+
+	case SIMPLE_HASH('o', 'r'):
+		/* operator | */
+		ddata->cur += 2;
+		return (cpp_demangle_read_expression_binary(ddata, "|", 1));
+
+	case SIMPLE_HASH('o', 'R'):
+		/* operator |= */
+		ddata->cur += 2;
+		return (cpp_demangle_read_expression_binary(ddata, "|=", 2));
+
+	case SIMPLE_HASH('p', 'l'):
+		/* operator + */
+		ddata->cur += 2;
+		return (cpp_demangle_read_expression_binary(ddata, "+", 1));
+
+	case SIMPLE_HASH('p', 'L'):
+		/* operator += */
+		ddata->cur += 2;
+		return (cpp_demangle_read_expression_binary(ddata, "+=", 2));
+
+	case SIMPLE_HASH('p', 'm'):
+		/* operator ->* */
+		ddata->cur += 2;
+		return (cpp_demangle_read_expression_binary(ddata, "->*", 3));
+
+	case SIMPLE_HASH('p', 'p'):
+		/* operator ++ */
+		ddata->cur += 2;
+		return (cpp_demangle_read_expression_binary(ddata, "++", 2));
+
+	case SIMPLE_HASH('p', 's'):
+		/* operator + (unary) */
+		ddata->cur += 2;
+		return (cpp_demangle_read_expression_unary(ddata, "+", 1));
+
+	case SIMPLE_HASH('p', 't'):
+		/* operator -> */
+		ddata->cur += 2;
+		return (cpp_demangle_read_expression_binary(ddata, "->", 2));
+
+	case SIMPLE_HASH('q', 'u'):
+		/* operator ? */
+		ddata->cur += 2;
+		return (cpp_demangle_read_expression_trinary(ddata, "?", 1,
+		    ":", 1));
+
+	case SIMPLE_HASH('r', 'm'):
+		/* operator % */
+		ddata->cur += 2;
+		return (cpp_demangle_read_expression_binary(ddata, "%", 1));
+
+	case SIMPLE_HASH('r', 'M'):
+		/* operator %= */
+		ddata->cur += 2;
+		return (cpp_demangle_read_expression_binary(ddata, "%=", 2));
+
+	case SIMPLE_HASH('r', 's'):
+		/* operator >> */
+		ddata->cur += 2;
+		return (cpp_demangle_read_expression_binary(ddata, ">>", 2));
+
+	case SIMPLE_HASH('r', 'S'):
+		/* operator >>= */
+		ddata->cur += 2;
+		return (cpp_demangle_read_expression_binary(ddata, ">>=", 3));
+
+	case SIMPLE_HASH('r', 'z'):
+		/* operator sizeof */
+		ddata->cur += 2;
+		return (cpp_demangle_read_expression_unary(ddata, "sizeof", 6));
+
+	case SIMPLE_HASH('s', 'v'):
+		/* operator sizeof */
+		ddata->cur += 2;
+		return (cpp_demangle_read_expression_unary(ddata, "sizeof", 6));
+	};
+
+	switch (*ddata->cur) {
+	case 'L':
+		return (cpp_demangle_read_expr_primary(ddata));
+	case 'T':
+		return (cpp_demangle_read_tmpl_param(ddata));
+	};
+
+	return (0);
+}
+
+static int
+cpp_demangle_read_expression_binary(struct cpp_demangle_data *ddata,
+    const char *name, size_t len)
+{
+
+	if (ddata == NULL || name == NULL || len == 0)
+		return (0);
+	if (!cpp_demangle_read_expression(ddata))
+		return (0);
+	if (!cpp_demangle_push_str(ddata, name, len))
+		return (0);
+
+	return (cpp_demangle_read_expression(ddata));
+}
+
+static int
+cpp_demangle_read_expression_unary(struct cpp_demangle_data *ddata,
+    const char *name, size_t len)
+{
+
+	if (ddata == NULL || name == NULL || len == 0)
+		return (0);
+	if (!cpp_demangle_read_expression(ddata))
+		return (0);
+
+	return (cpp_demangle_push_str(ddata, name, len));
+}
+
+static int
+cpp_demangle_read_expression_trinary(struct cpp_demangle_data *ddata,
+    const char *name1, size_t len1, const char *name2, size_t len2)
+{
+
+	if (ddata == NULL || name1 == NULL || len1 == 0 || name2 == NULL ||
+	    len2 == 0)
+		return (0);
+
+	if (!cpp_demangle_read_expression(ddata))
+		return (0);
+	if (!cpp_demangle_push_str(ddata, name1, len1))
+		return (0);
+	if (!cpp_demangle_read_expression(ddata))
+		return (0);
+	if (!cpp_demangle_push_str(ddata, name2, len2))
+		return (0);
+
+	return (cpp_demangle_read_expression(ddata));
+}
+
+static int
+cpp_demangle_read_function(struct cpp_demangle_data *ddata, int *ext_c,
+    struct vector_type_qualifier *v)
+{
+	size_t class_type_size, class_type_len, limit;
+	const char *class_type;
+
+	if (ddata == NULL || *ddata->cur != 'F' || v == NULL)
+		return (0);
+
+	++ddata->cur;
+	if (*ddata->cur == 'Y') {
+		if (ext_c != NULL)
+			*ext_c = 1;
+		++ddata->cur;
+	}
+	if (!cpp_demangle_read_type(ddata, 0))
+		return (0);
+	if (*ddata->cur != 'E') {
+		if (!cpp_demangle_push_str(ddata, "(", 1))
+			return (0);
+		if (vector_read_cmd_find(&ddata->cmd, READ_PTRMEM)) {
+			if ((class_type_size = ddata->class_type.size) == 0)
+				return (0);
+			class_type =
+			    ddata->class_type.container[class_type_size - 1];
+			if (class_type == NULL)
+				return (0);
+			if ((class_type_len = strlen(class_type)) == 0)
+				return (0);
+			if (!cpp_demangle_push_str(ddata, class_type,
+			    class_type_len))
+				return (0);
+			if (!cpp_demangle_push_str(ddata, "::*", 3))
+				return (0);
+			++ddata->func_type;
+		} else {
+			if (!cpp_demangle_push_type_qualifier(ddata, v,
+			    (const char *) NULL))
+				return (0);
+			vector_type_qualifier_dest(v);
+			if (!vector_type_qualifier_init(v))
+				return (0);
+		}
+
+		if (!cpp_demangle_push_str(ddata, ")(", 2))
+			return (0);
+
+		limit = 0;
+		for (;;) {
+			if (!cpp_demangle_read_type(ddata, 0))
+				return (0);
+			if (*ddata->cur == 'E')
+				break;
+			if (limit++ > CPP_DEMANGLE_TRY_LIMIT)
+				return (0);
+		}
+
+		if (vector_read_cmd_find(&ddata->cmd, READ_PTRMEM) == 1) {
+			if (!cpp_demangle_push_type_qualifier(ddata, v,
+			    (const char *) NULL))
+				return (0);
+			vector_type_qualifier_dest(v);
+			if (!vector_type_qualifier_init(v))
+				return (0);
+		}
+
+		if (!cpp_demangle_push_str(ddata, ")", 1))
+			return (0);
+	}
+
+	++ddata->cur;
+
+	return (1);
+}
+
+/* read encoding, encoding are function name, data name, special-name */
+static int
+cpp_demangle_read_encoding(struct cpp_demangle_data *ddata)
+{
+
+	if (ddata == NULL || *ddata->cur == '\0')
+		return (0);
+
+	/* special name */
+	switch (SIMPLE_HASH(*ddata->cur, *(ddata->cur + 1))) {
+	case SIMPLE_HASH('G', 'V'):
+		/* sentry object for 1 time init */
+		if (!cpp_demangle_push_str(ddata, "guard variable for ", 20))
+			return (0);
+		ddata->cur += 2;
+		break;
+
+	case SIMPLE_HASH('T', 'c'):
+		/* virtual function covariant override thunk */
+		if (!cpp_demangle_push_str(ddata,
+		    "virtual function covariant override ", 36))
+			return (0);
+		ddata->cur += 2;
+		if (*ddata->cur == '\0')
+			return (0);
+		if (!cpp_demangle_read_offset(ddata))
+			return (0);
+		if (!cpp_demangle_read_offset(ddata))
+			return (0);
+		return (cpp_demangle_read_encoding(ddata));
+
+	case SIMPLE_HASH('T', 'D'):
+		/* typeinfo common proxy */
+		break;
+
+	case SIMPLE_HASH('T', 'h'):
+		/* virtual function non-virtual override thunk */
+		if (cpp_demangle_push_str(ddata,
+		    "virtual function non-virtual override ", 38) == 0)
+			return (0);
+		ddata->cur += 2;
+		if (*ddata->cur == '\0')
+			return (0);
+		if (!cpp_demangle_read_nv_offset(ddata))
+			return (0);
+		return (cpp_demangle_read_encoding(ddata));
+
+	case SIMPLE_HASH('T', 'I'):
+		/* typeinfo structure */
+		/* FALLTHROUGH */
+	case SIMPLE_HASH('T', 'S'):
+		/* RTTI name (NTBS) */
+		if (!cpp_demangle_push_str(ddata, "typeinfo for ", 14))
+			return (0);
+		ddata->cur += 2;
+		if (*ddata->cur == '\0')
+			return (0);
+		return (cpp_demangle_read_type(ddata, 1));
+
+	case SIMPLE_HASH('T', 'T'):
+		/* VTT table */
+		if (!cpp_demangle_push_str(ddata, "VTT for ", 8))
+			return (0);
+		ddata->cur += 2;
+		return (cpp_demangle_read_type(ddata, 1));
+
+	case SIMPLE_HASH('T', 'v'):
+		/* virtual function virtual override thunk */
+		if (!cpp_demangle_push_str(ddata,
+		    "virtual function virtual override ", 34))
+			return (0);
+		ddata->cur += 2;
+		if (*ddata->cur == '\0')
+			return (0);
+		if (!cpp_demangle_read_v_offset(ddata))
+			return (0);
+		return (cpp_demangle_read_encoding(ddata));
+
+	case SIMPLE_HASH('T', 'V'):
+		/* virtual table */
+		if (!cpp_demangle_push_str(ddata, "vtable for ", 12))
+			return (0);
+		ddata->cur += 2;
+		if (*ddata->cur == '\0')
+			return (0);
+		return (cpp_demangle_read_type(ddata, 1));
+	};
+
+	return (cpp_demangle_read_name(ddata));
+}
+
+static int
+cpp_demangle_read_local_name(struct cpp_demangle_data *ddata)
+{
+	size_t limit;
+
+	if (ddata == NULL)
+		return (0);
+	if (*(++ddata->cur) == '\0')
+		return (0);
+	if (!cpp_demangle_read_encoding(ddata))
+		return (0);
+
+	limit = 0;
+	for (;;) {
+		if (!cpp_demangle_read_type(ddata, 1))
+			return (0);
+		if (*ddata->cur == 'E')
+			break;
+		if (limit++ > CPP_DEMANGLE_TRY_LIMIT)
+			return (0);
+	}
+	if (*(++ddata->cur) == '\0')
+		return (0);
+	if (ddata->paren == true) {
+		if (!cpp_demangle_push_str(ddata, ")", 1))
+			return (0);
+		ddata->paren = false;
+	}
+	if (*ddata->cur == 's')
+		++ddata->cur;
+	else {
+		if (!cpp_demangle_push_str(ddata, "::", 2))
+			return (0);
+		if (!cpp_demangle_read_name(ddata))
+			return (0);
+	}
+	if (*ddata->cur == '_') {
+		++ddata->cur;
+		while (ELFTC_ISDIGIT(*ddata->cur) != 0)
+			++ddata->cur;
+	}
+
+	return (1);
+}
+
+static int
+cpp_demangle_read_name(struct cpp_demangle_data *ddata)
+{
+	struct vector_str *output, v;
+	size_t p_idx, subst_str_len;
+	int rtn;
+	char *subst_str;
+
+	if (ddata == NULL || *ddata->cur == '\0')
+		return (0);
+
+	output = ddata->push_head > 0 ? &ddata->output_tmp : &ddata->output;
+
+	subst_str = NULL;
+
+	switch (*ddata->cur) {
+	case 'S':
+		return (cpp_demangle_read_subst(ddata));
+	case 'N':
+		return (cpp_demangle_read_nested_name(ddata));
+	case 'Z':
+		return (cpp_demangle_read_local_name(ddata));
+	};
+
+	if (!vector_str_init(&v))
+		return (0);
+
+	p_idx = output->size;
+	rtn = 0;
+	if (!cpp_demangle_read_uqname(ddata))
+		goto clean;
+	if ((subst_str = vector_str_substr(output, p_idx, output->size - 1,
+	    &subst_str_len)) == NULL)
+		goto clean;
+	if (subst_str_len > 8 && strstr(subst_str, "operator") != NULL) {
+		rtn = 1;
+		goto clean;
+	}
+	if (!vector_str_push(&v, subst_str, subst_str_len))
+		goto clean;
+	if (!cpp_demangle_push_subst_v(ddata, &v))
+		goto clean;
+
+	if (*ddata->cur == 'I') {
+		p_idx = output->size;
+		if (!cpp_demangle_read_tmpl_args(ddata))
+			goto clean;
+		free(subst_str);
+		if ((subst_str = vector_str_substr(output, p_idx,
+		    output->size - 1, &subst_str_len)) == NULL)
+			goto clean;
+		if (!vector_str_push(&v, subst_str, subst_str_len))
+			goto clean;
+		if (!cpp_demangle_push_subst_v(ddata, &v))
+			goto clean;
+	}
+
+	rtn = 1;
+
+clean:
+	free(subst_str);
+	vector_str_dest(&v);
+
+	return (rtn);
+}
+
+static int
+cpp_demangle_read_nested_name(struct cpp_demangle_data *ddata)
+{
+	struct vector_str *output, v;
+	size_t limit, p_idx, subst_str_len;
+	int rtn;
+	char *subst_str;
+
+	if (ddata == NULL || *ddata->cur != 'N')
+		return (0);
+	if (*(++ddata->cur) == '\0')
+		return (0);
+
+	while (*ddata->cur == 'r' || *ddata->cur == 'V' ||
+	    *ddata->cur == 'K') {
+		switch (*ddata->cur) {
+		case 'r':
+			ddata->mem_rst = true;
+			break;
+		case 'V':
+			ddata->mem_vat = true;
+			break;
+		case 'K':
+			ddata->mem_cst = true;
+			break;
+		};
+		++ddata->cur;
+	}
+
+	output = ddata->push_head > 0 ? &ddata->output_tmp : &ddata->output;
+	if (!vector_str_init(&v))
+		return (0);
+
+	rtn = 0;
+	limit = 0;
+	for (;;) {
+		p_idx = output->size;
+		switch (*ddata->cur) {
+		case 'I':
+			if (!cpp_demangle_read_tmpl_args(ddata))
+				goto clean;
+			break;
+		case 'S':
+			if (!cpp_demangle_read_subst(ddata))
+				goto clean;
+			break;
+		case 'T':
+			if (!cpp_demangle_read_tmpl_param(ddata))
+				goto clean;
+			break;
+		default:
+			if (!cpp_demangle_read_uqname(ddata))
+				goto clean;
+		};
+
+		if ((subst_str = vector_str_substr(output, p_idx,
+		    output->size - 1, &subst_str_len)) == NULL)
+			goto clean;
+		if (!vector_str_push(&v, subst_str, subst_str_len)) {
+			free(subst_str);
+			goto clean;
+		}
+		free(subst_str);
+
+		if (!cpp_demangle_push_subst_v(ddata, &v))
+			goto clean;
+		if (*ddata->cur == 'E')
+			break;
+		else if (*ddata->cur != 'I' &&
+		    *ddata->cur != 'C' && *ddata->cur != 'D') {
+			if (!cpp_demangle_push_str(ddata, "::", 2))
+				goto clean;
+			if (!vector_str_push(&v, "::", 2))
+				goto clean;
+		}
+		if (limit++ > CPP_DEMANGLE_TRY_LIMIT)
+			goto clean;
+	}
+
+	++ddata->cur;
+	rtn = 1;
+
+clean:
+	vector_str_dest(&v);
+
+	return (rtn);
+}
+
+/*
+ * read number
+ * number ::= [n] <decimal>
+ */
+static int
+cpp_demangle_read_number(struct cpp_demangle_data *ddata, long *rtn)
+{
+	long len, negative_factor;
+
+	if (ddata == NULL || rtn == NULL)
+		return (0);
+
+	negative_factor = 1;
+	if (*ddata->cur == 'n') {
+		negative_factor = -1;
+
+		++ddata->cur;
+	}
+	if (ELFTC_ISDIGIT(*ddata->cur) == 0)
+		return (0);
+
+	errno = 0;
+	if ((len = strtol(ddata->cur, (char **) NULL, 10)) == 0 &&
+	    errno != 0)
+		return (0);
+
+	while (ELFTC_ISDIGIT(*ddata->cur) != 0)
+		++ddata->cur;
+
+	assert(len >= 0);
+	assert(negative_factor == 1 || negative_factor == -1);
+
+	*rtn = len * negative_factor;
+
+	return (1);
+}
+
+static int
+cpp_demangle_read_nv_offset(struct cpp_demangle_data *ddata)
+{
+
+	if (ddata == NULL)
+		return (0);
+
+	if (!cpp_demangle_push_str(ddata, "offset : ", 9))
+		return (0);
+
+	return (cpp_demangle_read_offset_number(ddata));
+}
+
+/* read offset, offset are nv-offset, v-offset */
+static int
+cpp_demangle_read_offset(struct cpp_demangle_data *ddata)
+{
+
+	if (ddata == NULL)
+		return (0);
+
+	if (*ddata->cur == 'h') {
+		++ddata->cur;
+		return (cpp_demangle_read_nv_offset(ddata));
+	} else if (*ddata->cur == 'v') {
+		++ddata->cur;
+		return (cpp_demangle_read_v_offset(ddata));
+	}
+
+	return (0);
+}
+
+static int
+cpp_demangle_read_offset_number(struct cpp_demangle_data *ddata)
+{
+	bool negative;
+	const char *start;
+
+	if (ddata == NULL || *ddata->cur == '\0')
+		return (0);
+
+	/* offset could be negative */
+	if (*ddata->cur == 'n') {
+		negative = true;
+		start = ddata->cur + 1;
+	} else {
+		negative = false;
+		start = ddata->cur;
+	}
+
+	while (*ddata->cur != '_')
+		++ddata->cur;
+
+	if (negative && !cpp_demangle_push_str(ddata, "-", 1))
+		return (0);
+
+	assert(start != NULL);
+
+	if (!cpp_demangle_push_str(ddata, start, ddata->cur - start))
+		return (0);
+	if (!cpp_demangle_push_str(ddata, " ", 1))
+		return (0);
+
+	++ddata->cur;
+
+	return (1);
+}
+
+static int
+cpp_demangle_read_pointer_to_member(struct cpp_demangle_data *ddata)
+{
+	size_t class_type_len, i, idx, p_idx;
+	int p_func_type, rtn;
+	char *class_type;
+
+	if (ddata == NULL || *ddata->cur != 'M' || *(++ddata->cur) == '\0')
+		return (0);
+
+	p_idx = ddata->output.size;
+	if (!cpp_demangle_read_type(ddata, 0))
+		return (0);
+
+	if ((class_type = vector_str_substr(&ddata->output, p_idx,
+	    ddata->output.size - 1, &class_type_len)) == NULL)
+		return (0);
+
+	rtn = 0;
+	idx = ddata->output.size;
+	for (i = p_idx; i < idx; ++i)
+		if (!vector_str_pop(&ddata->output))
+			goto clean1;
+
+	if (!vector_read_cmd_push(&ddata->cmd, READ_PTRMEM))
+		goto clean1;
+
+	if (!vector_str_push(&ddata->class_type, class_type, class_type_len))
+		goto clean2;
+
+	p_func_type = ddata->func_type;
+	if (!cpp_demangle_read_type(ddata, 0))
+		goto clean3;
+
+	if (p_func_type == ddata->func_type) {
+		if (!cpp_demangle_push_str(ddata, " ", 1))
+			goto clean3;
+		if (!cpp_demangle_push_str(ddata, class_type, class_type_len))
+			goto clean3;
+		if (!cpp_demangle_push_str(ddata, "::*", 3))
+			goto clean3;
+	}
+
+	rtn = 1;
+clean3:
+	if (!vector_str_pop(&ddata->class_type))
+		rtn = 0;
+clean2:
+	if (!vector_read_cmd_pop(&ddata->cmd))
+		rtn = 0;
+clean1:
+	free(class_type);
+
+	return (rtn);
+}
+
+/* read source-name, source-name is <len> <ID> */
+static int
+cpp_demangle_read_sname(struct cpp_demangle_data *ddata)
+{
+	long len;
+
+	if (ddata == NULL || cpp_demangle_read_number(ddata, &len) == 0 ||
+	    len <= 0 || cpp_demangle_push_str(ddata, ddata->cur, len) == 0)
+		return (0);
+
+	assert(ddata->output.size > 0);
+	if (vector_read_cmd_find(&ddata->cmd, READ_TMPL) == 0)
+		ddata->last_sname =
+		    ddata->output.container[ddata->output.size - 1];
+
+	ddata->cur += len;
+
+	return (1);
+}
+
+static int
+cpp_demangle_read_subst(struct cpp_demangle_data *ddata)
+{
+	long nth;
+
+	if (ddata == NULL || *ddata->cur == '\0')
+		return (0);
+
+	/* abbreviations of the form Sx */
+	switch (SIMPLE_HASH(*ddata->cur, *(ddata->cur + 1))) {
+	case SIMPLE_HASH('S', 'a'):
+		/* std::allocator */
+		if (cpp_demangle_push_str(ddata, "std::allocator", 14) == 0)
+			return (0);
+		ddata->cur += 2;
+		if (*ddata->cur == 'I')
+			return (cpp_demangle_read_subst_stdtmpl(ddata,
+			    "std::allocator", 14));
+		return (1);
+
+	case SIMPLE_HASH('S', 'b'):
+		/* std::basic_string */
+		if (!cpp_demangle_push_str(ddata, "std::basic_string", 17))
+			return (0);
+		ddata->cur += 2;
+		if (*ddata->cur == 'I')
+			return (cpp_demangle_read_subst_stdtmpl(ddata,
+			    "std::basic_string", 17));
+		return (1);
+
+	case SIMPLE_HASH('S', 'd'):
+		/* std::basic_iostream<char, std::char_traits<char> > */
+		if (!cpp_demangle_push_str(ddata, "std::iostream", 19))
+			return (0);
+		ddata->last_sname = "iostream";
+		ddata->cur += 2;
+		if (*ddata->cur == 'I')
+			return (cpp_demangle_read_subst_stdtmpl(ddata,
+			    "std::iostream", 19));
+		return (1);
+
+	case SIMPLE_HASH('S', 'i'):
+		/* std::basic_istream<char, std::char_traits<char> > */
+		if (!cpp_demangle_push_str(ddata, "std::istream", 18))
+			return (0);
+		ddata->last_sname = "istream";
+		ddata->cur += 2;
+		if (*ddata->cur == 'I')
+			return (cpp_demangle_read_subst_stdtmpl(ddata,
+			    "std::istream", 18));
+		return (1);
+
+	case SIMPLE_HASH('S', 'o'):
+		/* std::basic_ostream<char, std::char_traits<char> > */
+		if (!cpp_demangle_push_str(ddata, "std::ostream", 18))
+			return (0);
+		ddata->last_sname = "istream";
+		ddata->cur += 2;
+		if (*ddata->cur == 'I')
+			return (cpp_demangle_read_subst_stdtmpl(ddata,
+			    "std::ostream", 18));
+		return (1);
+
+	case SIMPLE_HASH('S', 's'):
+		/*
+		 * std::basic_string<char, std::char_traits<char>,
+		 * std::allocator<char> >
+		 *
+		 * a.k.a std::string
+		 */
+		if (!cpp_demangle_push_str(ddata, "std::string", 11))
+			return (0);
+		ddata->last_sname = "string";
+		ddata->cur += 2;
+		if (*ddata->cur == 'I')
+			return (cpp_demangle_read_subst_stdtmpl(ddata,
+			    "std::string", 11));
+		return (1);
+
+	case SIMPLE_HASH('S', 't'):
+		/* std:: */
+		return (cpp_demangle_read_subst_std(ddata));
+	};
+
+	if (*(++ddata->cur) == '\0')
+		return (0);
+
+	/* substitution */
+	if (*ddata->cur == '_')
+		return (cpp_demangle_get_subst(ddata, 0));
+	else {
+		errno = 0;
+		/* substitution number is base 36 */
+		if ((nth = strtol(ddata->cur, (char **) NULL, 36)) == 0 &&
+		    errno != 0)
+			return (0);
+
+		/* first was '_', so increase one */
+		++nth;
+
+		while (*ddata->cur != '_')
+			++ddata->cur;
+
+		assert(nth > 0);
+
+		return (cpp_demangle_get_subst(ddata, nth));
+	}
+
+	/* NOTREACHED */
+	return (0);
+}
+
+static int
+cpp_demangle_read_subst_std(struct cpp_demangle_data *ddata)
+{
+	struct vector_str *output, v;
+	size_t p_idx, subst_str_len;
+	int rtn;
+	char *subst_str;
+
+	if (ddata == NULL)
+		return (0);
+
+	if (!vector_str_init(&v))
+		return (0);
+
+	subst_str = NULL;
+	rtn = 0;
+	if (!cpp_demangle_push_str(ddata, "std::", 5))
+		goto clean;
+
+	if (!vector_str_push(&v, "std::", 5))
+		goto clean;
+
+	ddata->cur += 2;
+
+	output = ddata->push_head > 0 ? &ddata->output_tmp : &ddata->output;
+
+	p_idx = output->size;
+	if (!cpp_demangle_read_uqname(ddata))
+		goto clean;
+
+	if ((subst_str = vector_str_substr(output, p_idx, output->size - 1,
+	    &subst_str_len)) == NULL)
+		goto clean;
+
+	if (!vector_str_push(&v, subst_str, subst_str_len))
+		goto clean;
+
+	if (!cpp_demangle_push_subst_v(ddata, &v))
+		goto clean;
+
+	if (*ddata->cur == 'I') {
+		p_idx = output->size;
+		if (!cpp_demangle_read_tmpl_args(ddata))
+			goto clean;
+		free(subst_str);
+		if ((subst_str = vector_str_substr(output, p_idx,
+		    output->size - 1, &subst_str_len)) == NULL)
+			goto clean;
+		if (!vector_str_push(&v, subst_str, subst_str_len))
+			goto clean;
+		if (!cpp_demangle_push_subst_v(ddata, &v))
+			goto clean;
+	}
+
+	rtn = 1;
+clean:
+	free(subst_str);
+	vector_str_dest(&v);
+
+	return (1);
+}
+
+static int
+cpp_demangle_read_subst_stdtmpl(struct cpp_demangle_data *ddata,
+    const char *str, size_t len)
+{
+	struct vector_str *output;
+	size_t p_idx, substr_len;
+	int rtn;
+	char *subst_str, *substr;
+
+	if (ddata == NULL || str == NULL || len == 0)
+		return (0);
+
+	output = ddata->push_head > 0 ? &ddata->output_tmp : &ddata->output;
+
+	p_idx = output->size;
+	substr = NULL;
+	subst_str = NULL;
+
+	if (!cpp_demangle_read_tmpl_args(ddata))
+		return (0);
+	if ((substr = vector_str_substr(output, p_idx, output->size - 1,
+	    &substr_len)) == NULL)
+		return (0);
+
+	rtn = 0;
+	if ((subst_str = malloc(sizeof(char) * (substr_len + len + 1))) ==
+	    NULL)
+		goto clean;
+
+	memcpy(subst_str, str, len);
+	memcpy(subst_str + len, substr, substr_len);
+	subst_str[substr_len + len] = '\0';
+
+	if (!cpp_demangle_push_subst(ddata, subst_str, substr_len + len))
+		goto clean;
+
+	rtn = 1;
+clean:
+	free(subst_str);
+	free(substr);
+
+	return (rtn);
+}
+
+static int
+cpp_demangle_read_tmpl_arg(struct cpp_demangle_data *ddata)
+{
+
+	if (ddata == NULL || *ddata->cur == '\0')
+		return (0);
+
+	switch (*ddata->cur) {
+	case 'L':
+		return (cpp_demangle_read_expr_primary(ddata));
+	case 'X':
+		return (cpp_demangle_read_expression(ddata));
+	};
+
+	return (cpp_demangle_read_type(ddata, 0));
+}
+
+static int
+cpp_demangle_read_tmpl_args(struct cpp_demangle_data *ddata)
+{
+	struct vector_str *v;
+	size_t arg_len, idx, limit, size;
+	char *arg;
+
+	if (ddata == NULL || *ddata->cur == '\0')
+		return (0);
+
+	++ddata->cur;
+
+	if (!vector_read_cmd_push(&ddata->cmd, READ_TMPL))
+		return (0);
+
+	if (!cpp_demangle_push_str(ddata, "<", 1))
+		return (0);
+
+	limit = 0;
+	v = ddata->push_head > 0 ? &ddata->output_tmp : &ddata->output;
+	for (;;) {
+		idx = v->size;
+		if (!cpp_demangle_read_tmpl_arg(ddata))
+			return (0);
+		if ((arg = vector_str_substr(v, idx, v->size - 1, &arg_len)) ==
+		    NULL)
+			return (0);
+		if (!vector_str_find(&ddata->tmpl, arg, arg_len) &&
+		    !vector_str_push(&ddata->tmpl, arg, arg_len)) {
+			free(arg);
+			return (0);
+		}
+
+		free(arg);
+
+		if (*ddata->cur == 'E') {
+			++ddata->cur;
+			size = v->size;
+			assert(size > 0);
+			if (!strncmp(v->container[size - 1], ">", 1)) {
+				if (!cpp_demangle_push_str(ddata, " >", 2))
+					return (0);
+			} else if (!cpp_demangle_push_str(ddata, ">", 1))
+				return (0);
+			break;
+		} else if (*ddata->cur != 'I' &&
+		    !cpp_demangle_push_str(ddata, ", ", 2))
+			return (0);
+
+		if (limit++ > CPP_DEMANGLE_TRY_LIMIT)
+			return (0);
+	}
+
+	return (vector_read_cmd_pop(&ddata->cmd));
+}
+
+/*
+ * Read template parameter that forms in 'T[number]_'.
+ * This function much like to read_subst but only for types.
+ */
+static int
+cpp_demangle_read_tmpl_param(struct cpp_demangle_data *ddata)
+{
+	long nth;
+
+	if (ddata == NULL || *ddata->cur != 'T')
+		return (0);
+
+	++ddata->cur;
+
+	if (*ddata->cur == '_')
+		return (cpp_demangle_get_tmpl_param(ddata, 0));
+	else {
+
+		errno = 0;
+		if ((nth = strtol(ddata->cur, (char **) NULL, 36)) == 0 &&
+		    errno != 0)
+			return (0);
+
+		/* T_ is first */
+		++nth;
+
+		while (*ddata->cur != '_')
+			++ddata->cur;
+
+		assert(nth > 0);
+
+		return (cpp_demangle_get_tmpl_param(ddata, nth));
+	}
+
+	/* NOTREACHED */
+	return (0);
+}
+
+static int
+cpp_demangle_read_type(struct cpp_demangle_data *ddata, int delimit)
+{
+	struct vector_type_qualifier v;
+	struct vector_str *output;
+	size_t p_idx, type_str_len;
+	int extern_c, is_builtin;
+	long len;
+	char *type_str;
+
+	if (ddata == NULL)
+		return (0);
+
+	output = &ddata->output;
+	if (ddata->output.size > 0 && !strncmp(ddata->output.container[ddata->output.size - 1], ">", 1)) {
+		ddata->push_head++;
+		output = &ddata->output_tmp;
+	} else if (delimit == 1) {
+		if (ddata->paren == false) {
+			if (!cpp_demangle_push_str(ddata, "(", 1))
+				return (0);
+			if (ddata->output.size < 2)
+				return (0);
+			ddata->paren = true;
+			ddata->pfirst = true;
+			/* Need pop function name */
+			if (ddata->subst.size == 1 &&
+			    !vector_str_pop(&ddata->subst))
+				return (0);
+		}
+
+		if (ddata->pfirst)
+			ddata->pfirst = false;
+		else if (*ddata->cur != 'I' &&
+		    !cpp_demangle_push_str(ddata, ", ", 2))
+			return (0);
+	}
+
+	assert(output != NULL);
+	/*
+	 * [r, V, K] [P, R, C, G, U] builtin, function, class-enum, array
+	 * pointer-to-member, template-param, template-template-param, subst
+	 */
+
+	if (!vector_type_qualifier_init(&v))
+		return (0);
+
+	extern_c = 0;
+	is_builtin = 1;
+	p_idx = output->size;
+	type_str = NULL;
+again:
+	/* builtin type */
+	switch (*ddata->cur) {
+	case 'a':
+		/* signed char */
+		if (!cpp_demangle_push_str(ddata, "signed char", 11))
+			goto clean;
+		++ddata->cur;
+		goto rtn;
+
+	case 'A':
+		/* array type */
+		if (!cpp_demangle_read_array(ddata))
+			goto clean;
+		is_builtin = 0;
+		goto rtn;
+
+	case 'b':
+		/* bool */
+		if (!cpp_demangle_push_str(ddata, "bool", 4))
+			goto clean;
+		++ddata->cur;
+		goto rtn;
+
+	case 'C':
+		/* complex pair */
+		if (!vector_type_qualifier_push(&v, TYPE_CMX))
+			goto clean;
+		++ddata->cur;
+		goto again;
+
+	case 'c':
+		/* char */
+		if (!cpp_demangle_push_str(ddata, "char", 4))
+			goto clean;
+		++ddata->cur;
+		goto rtn;
+
+	case 'd':
+		/* double */
+		if (!cpp_demangle_push_str(ddata, "double", 6))
+			goto clean;
+		++ddata->cur;
+		goto rtn;
+
+	case 'e':
+		/* long double */
+		if (!cpp_demangle_push_str(ddata, "long double", 11))
+			goto clean;
+		++ddata->cur;
+		goto rtn;
+
+	case 'f':
+		/* float */
+		if (!cpp_demangle_push_str(ddata, "float", 5))
+			goto clean;
+		++ddata->cur;
+		goto rtn;
+
+	case 'F':
+		/* function */
+		if (!cpp_demangle_read_function(ddata, &extern_c, &v))
+			goto clean;
+		is_builtin = 0;
+		goto rtn;
+
+	case 'g':
+		/* __float128 */
+		if (!cpp_demangle_push_str(ddata, "__float128", 10))
+			goto clean;
+		++ddata->cur;
+		goto rtn;
+
+	case 'G':
+		/* imaginary */
+		if (!vector_type_qualifier_push(&v, TYPE_IMG))
+			goto clean;
+		++ddata->cur;
+		goto again;
+
+	case 'h':
+		/* unsigned char */
+		if (!cpp_demangle_push_str(ddata, "unsigned char", 13))
+			goto clean;
+		++ddata->cur;
+		goto rtn;
+
+	case 'i':
+		/* int */
+		if (!cpp_demangle_push_str(ddata, "int", 3))
+			goto clean;
+		++ddata->cur;
+		goto rtn;
+
+	case 'j':
+		/* unsigned int */
+		if (!cpp_demangle_push_str(ddata, "unsigned int", 12))
+			goto clean;
+		++ddata->cur;
+		goto rtn;
+
+	case 'K':
+		/* const */
+		if (!vector_type_qualifier_push(&v, TYPE_CST))
+			goto clean;
+		++ddata->cur;
+		goto again;
+
+	case 'l':
+		/* long */
+		if (!cpp_demangle_push_str(ddata, "long", 4))
+			goto clean;
+		++ddata->cur;
+		goto rtn;
+
+	case 'm':
+		/* unsigned long */
+		if (!cpp_demangle_push_str(ddata, "unsigned long", 13))
+			goto clean;
+
+		++ddata->cur;
+
+		goto rtn;
+	case 'M':
+		/* pointer to member */
+		if (!cpp_demangle_read_pointer_to_member(ddata))
+			goto clean;
+		is_builtin = 0;
+		goto rtn;
+
+	case 'n':
+		/* __int128 */
+		if (!cpp_demangle_push_str(ddata, "__int128", 8))
+			goto clean;
+		++ddata->cur;
+		goto rtn;
+
+	case 'o':
+		/* unsigned __int128 */
+		if (!cpp_demangle_push_str(ddata, "unsigned _;int128", 17))
+			goto clean;
+		++ddata->cur;
+		goto rtn;
+
+	case 'P':
+		/* pointer */
+		if (!vector_type_qualifier_push(&v, TYPE_PTR))
+			goto clean;
+		++ddata->cur;
+		goto again;
+
+	case 'r':
+		/* restrict */
+		if (!vector_type_qualifier_push(&v, TYPE_RST))
+			goto clean;
+		++ddata->cur;
+		goto again;
+
+	case 'R':
+		/* reference */
+		if (!vector_type_qualifier_push(&v, TYPE_REF))
+			goto clean;
+		++ddata->cur;
+		goto again;
+
+	case 's':
+		/* short, local string */
+		if (!cpp_demangle_push_str(ddata, "short", 5))
+			goto clean;
+		++ddata->cur;
+		goto rtn;
+
+	case 'S':
+		/* substitution */
+		if (!cpp_demangle_read_subst(ddata))
+			goto clean;
+		is_builtin = 0;
+		goto rtn;
+
+	case 't':
+		/* unsigned short */
+		if (!cpp_demangle_push_str(ddata, "unsigned short", 14))
+			goto clean;
+		++ddata->cur;
+		goto rtn;
+
+	case 'T':
+		/* template parameter */
+		if (!cpp_demangle_read_tmpl_param(ddata))
+			goto clean;
+		is_builtin = 0;
+		goto rtn;
+
+	case 'u':
+		/* vendor extended builtin */
+		++ddata->cur;
+		if (!cpp_demangle_read_sname(ddata))
+			goto clean;
+		is_builtin = 0;
+		goto rtn;
+
+	case 'U':
+		/* vendor extended type qualifier */
+		if (!cpp_demangle_read_number(ddata, &len))
+			goto clean;
+		if (len <= 0)
+			goto clean;
+		if (!vector_str_push(&v.ext_name, ddata->cur, len))
+			return (0);
+		ddata->cur += len;
+		goto again;
+
+	case 'v':
+		/* void */
+		if (!cpp_demangle_push_str(ddata, "void", 4))
+			goto clean;
+		++ddata->cur;
+		goto rtn;
+
+	case 'V':
+		/* volatile */
+		if (!vector_type_qualifier_push(&v, TYPE_VAT))
+			goto clean;
+		++ddata->cur;
+		goto again;
+
+	case 'w':
+		/* wchar_t */
+		if (!cpp_demangle_push_str(ddata, "wchar_t", 6))
+			goto clean;
+		++ddata->cur;
+		goto rtn;
+
+	case 'x':
+		/* long long */
+		if (!cpp_demangle_push_str(ddata, "long long", 9))
+			goto clean;
+		++ddata->cur;
+		goto rtn;
+
+	case 'y':
+		/* unsigned long long */
+		if (!cpp_demangle_push_str(ddata, "unsigned long long", 18))
+			goto clean;
+		++ddata->cur;
+		goto rtn;
+
+	case 'z':
+		/* ellipsis */
+		if (!cpp_demangle_push_str(ddata, "ellipsis", 8))
+			goto clean;
+		++ddata->cur;
+		goto rtn;
+	};
+
+	if (!cpp_demangle_read_name(ddata))
+		goto clean;
+
+	is_builtin = 0;
+rtn:
+	if ((type_str = vector_str_substr(output, p_idx, output->size - 1,
+	    &type_str_len)) == NULL)
+		goto clean;
+
+	if (is_builtin == 0) {
+		if (!vector_str_find(&ddata->subst, type_str, type_str_len) &&
+		    !vector_str_push(&ddata->subst, type_str, type_str_len))
+			goto clean;
+	}
+
+	if (!cpp_demangle_push_type_qualifier(ddata, &v, type_str))
+		goto clean;
+
+	free(type_str);
+	vector_type_qualifier_dest(&v);
+
+	if (ddata->push_head > 0) {
+		if (*ddata->cur == 'I' && cpp_demangle_read_tmpl_args(ddata)
+		    == 0)
+			return (0);
+
+		if (--ddata->push_head > 0)
+			return (1);
+
+		if (!vector_str_push(&ddata->output_tmp, " ", 1))
+			return (0);
+
+		if (!vector_str_push_vector_head(&ddata->output,
+		    &ddata->output_tmp))
+			return (0);
+
+		vector_str_dest(&ddata->output_tmp);
+		if (!vector_str_init(&ddata->output_tmp))
+			return (0);
+
+		if (!cpp_demangle_push_str(ddata, "(", 1))
+			return (0);
+
+		ddata->paren = true;
+		ddata->pfirst = true;
+	}
+
+	return (1);
+clean:
+	free(type_str);
+	vector_type_qualifier_dest(&v);
+
+	return (0);
+}
+
+/*
+ * read unqualified-name, unqualified name are operator-name, ctor-dtor-name,
+ * source-name
+ */
+static int
+cpp_demangle_read_uqname(struct cpp_demangle_data *ddata)
+{
+	size_t len;
+
+	if (ddata == NULL || *ddata->cur == '\0')
+		return (0);
+
+	/* operator name */
+	switch (SIMPLE_HASH(*ddata->cur, *(ddata->cur + 1))) {
+	case SIMPLE_HASH('a', 'a'):
+		/* operator && */
+		if (!cpp_demangle_push_str(ddata, "operator&&", 10))
+			return (0);
+		ddata->cur += 2;
+		return (1);
+
+	case SIMPLE_HASH('a', 'd'):
+		/* operator & (unary) */
+		if (!cpp_demangle_push_str(ddata, "operator&", 9))
+			return (0);
+		ddata->cur += 2;
+		return (1);
+
+	case SIMPLE_HASH('a', 'n'):
+		/* operator & */
+		if (!cpp_demangle_push_str(ddata, "operator&", 9))
+			return (0);
+		ddata->cur += 2;
+		return (1);
+
+	case SIMPLE_HASH('a', 'N'):
+		/* operator &= */
+		if (!cpp_demangle_push_str(ddata, "operator&=", 10))
+			return (0);
+		ddata->cur += 2;
+		return (1);
+
+	case SIMPLE_HASH('a', 'S'):
+		/* operator = */
+		if (!cpp_demangle_push_str(ddata, "operator=", 9))
+			return (0);
+		ddata->cur += 2;
+		return (1);
+
+	case SIMPLE_HASH('c', 'l'):
+		/* operator () */
+		if (!cpp_demangle_push_str(ddata, "operator()", 10))
+			return (0);
+		ddata->cur += 2;
+		return (1);
+
+	case SIMPLE_HASH('c', 'm'):
+		/* operator , */
+		if (!cpp_demangle_push_str(ddata, "operator,", 9))
+			return (0);
+		ddata->cur += 2;
+		return (1);
+
+	case SIMPLE_HASH('c', 'o'):
+		/* operator ~ */
+		if (!cpp_demangle_push_str(ddata, "operator~", 9))
+			return (0);
+		ddata->cur += 2;
+		return (1);
+
+	case SIMPLE_HASH('c', 'v'):
+		/* operator (cast) */
+		if (!cpp_demangle_push_str(ddata, "operator(cast)", 14))
+			return (0);
+		ddata->cur += 2;
+		return (cpp_demangle_read_type(ddata, 1));
+
+	case SIMPLE_HASH('d', 'a'):
+		/* operator delete [] */
+		if (!cpp_demangle_push_str(ddata, "operator delete []", 18))
+			return (0);
+		ddata->cur += 2;
+		return (1);
+
+	case SIMPLE_HASH('d', 'e'):
+		/* operator * (unary) */
+		if (!cpp_demangle_push_str(ddata, "operator*", 9))
+			return (0);
+		ddata->cur += 2;
+		return (1);
+
+	case SIMPLE_HASH('d', 'l'):
+		/* operator delete */
+		if (!cpp_demangle_push_str(ddata, "operator delete", 15))
+			return (0);
+		ddata->cur += 2;
+		return (1);
+
+	case SIMPLE_HASH('d', 'v'):
+		/* operator / */
+		if (!cpp_demangle_push_str(ddata, "operator/", 9))
+			return (0);
+		ddata->cur += 2;
+		return (1);
+
+	case SIMPLE_HASH('d', 'V'):
+		/* operator /= */
+		if (!cpp_demangle_push_str(ddata, "operator/=", 10))
+			return (0);
+		ddata->cur += 2;
+		return (1);
+
+	case SIMPLE_HASH('e', 'o'):
+		/* operator ^ */
+		if (!cpp_demangle_push_str(ddata, "operator^", 9))
+			return (0);
+		ddata->cur += 2;
+		return (1);
+
+	case SIMPLE_HASH('e', 'O'):
+		/* operator ^= */
+		if (!cpp_demangle_push_str(ddata, "operator^=", 10))
+			return (0);
+		ddata->cur += 2;
+		return (1);
+
+	case SIMPLE_HASH('e', 'q'):
+		/* operator == */
+		if (!cpp_demangle_push_str(ddata, "operator==", 10))
+			return (0);
+		ddata->cur += 2;
+		return (1);
+
+	case SIMPLE_HASH('g', 'e'):
+		/* operator >= */
+		if (!cpp_demangle_push_str(ddata, "operator>=", 10))
+			return (0);
+		ddata->cur += 2;
+		return (1);
+
+	case SIMPLE_HASH('g', 't'):
+		/* operator > */
+		if (!cpp_demangle_push_str(ddata, "operator>", 9))
+			return (0);
+		ddata->cur += 2;
+		return (1);
+
+	case SIMPLE_HASH('i', 'x'):
+		/* operator [] */
+		if (!cpp_demangle_push_str(ddata, "operator[]", 10))
+			return (0);
+		ddata->cur += 2;
+		return (1);
+
+	case SIMPLE_HASH('l', 'e'):
+		/* operator <= */
+		if (!cpp_demangle_push_str(ddata, "operator<=", 10))
+			return (0);
+		ddata->cur += 2;
+		return (1);
+
+	case SIMPLE_HASH('l', 's'):
+		/* operator << */
+		if (!cpp_demangle_push_str(ddata, "operator<<", 10))
+			return (0);
+		ddata->cur += 2;
+		return (1);
+
+	case SIMPLE_HASH('l', 'S'):
+		/* operator <<= */
+		if (!cpp_demangle_push_str(ddata, "operator<<=", 11))
+			return (0);
+		ddata->cur += 2;
+		return (1);
+
+	case SIMPLE_HASH('l', 't'):
+		/* operator < */
+		if (!cpp_demangle_push_str(ddata, "operator<", 9))
+			return (0);
+		ddata->cur += 2;
+		return (1);
+
+	case SIMPLE_HASH('m', 'i'):
+		/* operator - */
+		if (!cpp_demangle_push_str(ddata, "operator-", 9))
+			return (0);
+		ddata->cur += 2;
+		return (1);
+
+	case SIMPLE_HASH('m', 'I'):
+		/* operator -= */
+		if (!cpp_demangle_push_str(ddata, "operator-=", 10))
+			return (0);
+		ddata->cur += 2;
+		return (1);
+
+	case SIMPLE_HASH('m', 'l'):
+		/* operator * */
+		if (!cpp_demangle_push_str(ddata, "operator*", 9))
+			return (0);
+		ddata->cur += 2;
+		return (1);
+
+	case SIMPLE_HASH('m', 'L'):
+		/* operator *= */
+		if (!cpp_demangle_push_str(ddata, "operator*=", 10))
+			return (0);
+		ddata->cur += 2;
+		return (1);
+
+	case SIMPLE_HASH('m', 'm'):
+		/* operator -- */
+		if (!cpp_demangle_push_str(ddata, "operator--", 10))
+			return (0);
+		ddata->cur += 2;
+		return (1);
+
+	case SIMPLE_HASH('n', 'a'):
+		/* operator new[] */
+		if (!cpp_demangle_push_str(ddata, "operator new []", 15))
+			return (0);
+		ddata->cur += 2;
+		return (1);
+
+	case SIMPLE_HASH('n', 'e'):
+		/* operator != */
+		if (!cpp_demangle_push_str(ddata, "operator!=", 10))
+			return (0);
+		ddata->cur += 2;
+		return (1);
+
+	case SIMPLE_HASH('n', 'g'):
+		/* operator - (unary) */
+		if (!cpp_demangle_push_str(ddata, "operator-", 9))
+			return (0);
+		ddata->cur += 2;
+		return (1);
+
+	case SIMPLE_HASH('n', 't'):
+		/* operator ! */
+		if (!cpp_demangle_push_str(ddata, "operator!", 9))
+			return (0);
+		ddata->cur += 2;
+		return (1);
+
+	case SIMPLE_HASH('n', 'w'):
+		/* operator new */
+		if (!cpp_demangle_push_str(ddata, "operator new", 12))
+			return (0);
+		ddata->cur += 2;
+		return (1);
+
+	case SIMPLE_HASH('o', 'o'):
+		/* operator || */
+		if (!cpp_demangle_push_str(ddata, "operator||", 10))
+			return (0);
+		ddata->cur += 2;
+		return (1);
+
+	case SIMPLE_HASH('o', 'r'):
+		/* operator | */
+		if (!cpp_demangle_push_str(ddata, "operator|", 9))
+			return (0);
+		ddata->cur += 2;
+		return (1);
+
+	case SIMPLE_HASH('o', 'R'):
+		/* operator |= */
+		if (!cpp_demangle_push_str(ddata, "operator|=", 10))
+			return (0);
+		ddata->cur += 2;
+		return (1);
+
+	case SIMPLE_HASH('p', 'l'):
+		/* operator + */
+		if (!cpp_demangle_push_str(ddata, "operator+", 9))
+			return (0);
+		ddata->cur += 2;
+		return (1);
+
+	case SIMPLE_HASH('p', 'L'):
+		/* operator += */
+		if (!cpp_demangle_push_str(ddata, "operator+=", 10))
+			return (0);
+		ddata->cur += 2;
+		return (1);
+
+	case SIMPLE_HASH('p', 'm'):
+		/* operator ->* */
+		if (!cpp_demangle_push_str(ddata, "operator->*", 11))
+			return (0);
+		ddata->cur += 2;
+		return (1);
+
+	case SIMPLE_HASH('p', 'p'):
+		/* operator ++ */
+		if (!cpp_demangle_push_str(ddata, "operator++", 10))
+			return (0);
+		ddata->cur += 2;
+		return (1);
+
+	case SIMPLE_HASH('p', 's'):
+		/* operator + (unary) */
+		if (!cpp_demangle_push_str(ddata, "operator+", 9))
+			return (0);
+		ddata->cur += 2;
+		return (1);
+
+	case SIMPLE_HASH('p', 't'):
+		/* operator -> */
+		if (!cpp_demangle_push_str(ddata, "operator->", 10))
+			return (0);
+		ddata->cur += 2;
+		return (1);
+
+	case SIMPLE_HASH('q', 'u'):
+		/* operator ? */
+		if (!cpp_demangle_push_str(ddata, "operator?", 9))
+			return (0);
+		ddata->cur += 2;
+		return (1);
+
+	case SIMPLE_HASH('r', 'm'):
+		/* operator % */
+		if (!cpp_demangle_push_str(ddata, "operator%", 9))
+			return (0);
+		ddata->cur += 2;
+		return (1);
+
+	case SIMPLE_HASH('r', 'M'):
+		/* operator %= */
+		if (!cpp_demangle_push_str(ddata, "operator%=", 10))
+			return (0);
+		ddata->cur += 2;
+		return (1);
+
+	case SIMPLE_HASH('r', 's'):
+		/* operator >> */
+		if (!cpp_demangle_push_str(ddata, "operator>>", 10))
+			return (0);
+		ddata->cur += 2;
+		return (1);
+
+	case SIMPLE_HASH('r', 'S'):
+		/* operator >>= */
+		if (!cpp_demangle_push_str(ddata, "operator>>=", 11))
+			return (0);
+		ddata->cur += 2;
+		return (1);
+
+	case SIMPLE_HASH('r', 'z'):
+		/* operator sizeof */
+		if (!cpp_demangle_push_str(ddata, "operator sizeof ", 16))
+			return (0);
+		ddata->cur += 2;
+		return (1);
+
+	case SIMPLE_HASH('s', 'r'):
+		/* scope resolution operator */
+		if (!cpp_demangle_push_str(ddata, "scope resolution operator ",
+		    26))
+			return (0);
+		ddata->cur += 2;
+		return (1);
+
+	case SIMPLE_HASH('s', 'v'):
+		/* operator sizeof */
+		if (!cpp_demangle_push_str(ddata, "operator sizeof ", 16))
+			return (0);
+		ddata->cur += 2;
+		return (1);
+	};
+
+	/* vendor extened operator */
+	if (*ddata->cur == 'v' && ELFTC_ISDIGIT(*(ddata->cur + 1))) {
+		if (!cpp_demangle_push_str(ddata, "vendor extened operator ",
+		    24))
+			return (0);
+		if (!cpp_demangle_push_str(ddata, ddata->cur + 1, 1))
+			return (0);
+		ddata->cur += 2;
+		return (cpp_demangle_read_sname(ddata));
+	}
+
+	/* ctor-dtor-name */
+	switch (SIMPLE_HASH(*ddata->cur, *(ddata->cur + 1))) {
+	case SIMPLE_HASH('C', '1'):
+		/* FALLTHROUGH */
+	case SIMPLE_HASH('C', '2'):
+		/* FALLTHROUGH */
+	case SIMPLE_HASH('C', '3'):
+		if (ddata->last_sname == NULL)
+			return (0);
+		if ((len = strlen(ddata->last_sname)) == 0)
+			return (0);
+		if (!cpp_demangle_push_str(ddata, "::", 2))
+			return (0);
+		if (!cpp_demangle_push_str(ddata, ddata->last_sname, len))
+			return (0);
+		ddata->cur +=2;
+		return (1);
+
+	case SIMPLE_HASH('D', '0'):
+		/* FALLTHROUGH */
+	case SIMPLE_HASH('D', '1'):
+		/* FALLTHROUGH */
+	case SIMPLE_HASH('D', '2'):
+		if (ddata->last_sname == NULL)
+			return (0);
+		if ((len = strlen(ddata->last_sname)) == 0)
+			return (0);
+		if (!cpp_demangle_push_str(ddata, "::~", 3))
+			return (0);
+		if (!cpp_demangle_push_str(ddata, ddata->last_sname, len))
+			return (0);
+		ddata->cur +=2;
+		return (1);
+	};
+
+	/* source name */
+	if (ELFTC_ISDIGIT(*ddata->cur) != 0)
+		return (cpp_demangle_read_sname(ddata));
+
+	return (1);
+}
+
+static int
+cpp_demangle_read_v_offset(struct cpp_demangle_data *ddata)
+{
+
+	if (ddata == NULL)
+		return (0);
+
+	if (!cpp_demangle_push_str(ddata, "offset : ", 9))
+		return (0);
+
+	if (!cpp_demangle_read_offset_number(ddata))
+		return (0);
+
+	if (!cpp_demangle_push_str(ddata, "virtual offset : ", 17))
+		return (0);
+
+	return (!cpp_demangle_read_offset_number(ddata));
+}
+
+/*
+ * Decode floating point representation to string
+ * Return new allocated string or NULL
+ *
+ * Todo
+ * Replace these functions to macro.
+ */
+static char *
+decode_fp_to_double(const char *p, size_t len)
+{
+	double f;
+	size_t rtn_len, limit, i;
+	int byte;
+	char *rtn;
+
+	if (p == NULL || len == 0 || len % 2 != 0 || len / 2 > sizeof(double))
+		return (NULL);
+
+	memset(&f, 0, sizeof(double));
+
+	for (i = 0; i < len / 2; ++i) {
+		byte = hex_to_dec(p[len - i * 2 - 1]) +
+		    hex_to_dec(p[len - i * 2 - 2]) * 16;
+
+		if (byte < 0 || byte > 255)
+			return (NULL);
+
+#if ELFTC_BYTE_ORDER == ELFTC_BYTE_ORDER_LITTLE_ENDIAN
+		((unsigned char *)&f)[i] = (unsigned char)(byte);
+#else /* ELFTC_BYTE_ORDER != ELFTC_BYTE_ORDER_LITTLE_ENDIAN */
+		((unsigned char *)&f)[sizeof(double) - i - 1] =
+		    (unsigned char)(byte);
+#endif /* ELFTC_BYTE_ORDER == ELFTC_BYTE_ORDER_LITTLE_ENDIAN */
+	}
+
+	rtn_len = 64;
+	limit = 0;
+again:
+	if ((rtn = malloc(sizeof(char) * rtn_len)) == NULL)
+		return (NULL);
+
+	if (snprintf(rtn, rtn_len, "%fld", f) >= (int)rtn_len) {
+		free(rtn);
+		if (limit++ > FLOAT_SPRINTF_TRY_LIMIT)
+			return (NULL);
+		rtn_len *= BUFFER_GROWFACTOR;
+		goto again;
+	}
+
+	return rtn;
+}
+
+static char *
+decode_fp_to_float(const char *p, size_t len)
+{
+	size_t i, rtn_len, limit;
+	float f;
+	int byte;
+	char *rtn;
+
+	if (p == NULL || len == 0 || len % 2 != 0 || len / 2 > sizeof(float))
+		return (NULL);
+
+	memset(&f, 0, sizeof(float));
+
+	for (i = 0; i < len / 2; ++i) {
+		byte = hex_to_dec(p[len - i * 2 - 1]) +
+		    hex_to_dec(p[len - i * 2 - 2]) * 16;
+		if (byte < 0 || byte > 255)
+			return (NULL);
+#if ELFTC_BYTE_ORDER == ELFTC_BYTE_ORDER_LITTLE_ENDIAN
+		((unsigned char *)&f)[i] = (unsigned char)(byte);
+#else /* ELFTC_BYTE_ORDER != ELFTC_BYTE_ORDER_LITTLE_ENDIAN */
+		((unsigned char *)&f)[sizeof(float) - i - 1] =
+		    (unsigned char)(byte);
+#endif /* ELFTC_BYTE_ORDER == ELFTC_BYTE_ORDER_LITTLE_ENDIAN */
+	}
+
+	rtn_len = 64;
+	limit = 0;
+again:
+	if ((rtn = malloc(sizeof(char) * rtn_len)) == NULL)
+		return (NULL);
+
+	if (snprintf(rtn, rtn_len, "%ff", f) >= (int)rtn_len) {
+		free(rtn);
+		if (limit++ > FLOAT_SPRINTF_TRY_LIMIT)
+			return (NULL);
+		rtn_len *= BUFFER_GROWFACTOR;
+		goto again;
+	}
+
+	return rtn;
+}
+
+static char *
+decode_fp_to_float128(const char *p, size_t len)
+{
+	long double f;
+	size_t rtn_len, limit, i;
+	int byte;
+	unsigned char buf[FLOAT_QUADRUPLE_BYTES];
+	char *rtn;
+
+	switch(sizeof(long double)) {
+	case FLOAT_QUADRUPLE_BYTES:
+		return (decode_fp_to_long_double(p, len));
+	case FLOAT_EXTENED_BYTES:
+		if (p == NULL || len == 0 || len % 2 != 0 ||
+		    len / 2 > FLOAT_QUADRUPLE_BYTES)
+			return (NULL);
+
+		memset(buf, 0, FLOAT_QUADRUPLE_BYTES);
+
+		for (i = 0; i < len / 2; ++i) {
+			byte = hex_to_dec(p[len - i * 2 - 1]) +
+			    hex_to_dec(p[len - i * 2 - 2]) * 16;
+			if (byte < 0 || byte > 255)
+				return (NULL);
+#if ELFTC_BYTE_ORDER == ELFTC_BYTE_ORDER_LITTLE_ENDIAN
+			buf[i] = (unsigned char)(byte);
+#else /* ELFTC_BYTE_ORDER != ELFTC_BYTE_ORDER_LITTLE_ENDIAN */
+			buf[FLOAT_QUADRUPLE_BYTES - i -1] =
+			    (unsigned char)(byte);
+#endif /* ELFTC_BYTE_ORDER == ELFTC_BYTE_ORDER_LITTLE_ENDIAN */
+		}
+		memset(&f, 0, FLOAT_EXTENED_BYTES);
+
+#if ELFTC_BYTE_ORDER == ELFTC_BYTE_ORDER_LITTLE_ENDIAN
+		memcpy(&f, buf, FLOAT_EXTENED_BYTES);
+#else /* ELFTC_BYTE_ORDER != ELFTC_BYTE_ORDER_LITTLE_ENDIAN */
+		memcpy(&f, buf + 6, FLOAT_EXTENED_BYTES);
+#endif /* ELFTC_BYTE_ORDER == ELFTC_BYTE_ORDER_LITTLE_ENDIAN */
+
+		rtn_len = 256;
+		limit = 0;
+again:
+		if ((rtn = malloc(sizeof(char) * rtn_len)) == NULL)
+			return (NULL);
+
+		if (snprintf(rtn, rtn_len, "%Lfd", f) >= (int)rtn_len) {
+			free(rtn);
+			if (limit++ > FLOAT_SPRINTF_TRY_LIMIT)
+				return (NULL);
+			rtn_len *= BUFFER_GROWFACTOR;
+			goto again;
+		}
+
+		return (rtn);
+	default:
+		return (NULL);
+	}
+}
+
+static char *
+decode_fp_to_float80(const char *p, size_t len)
+{
+	long double f;
+	size_t rtn_len, limit, i;
+	int byte;
+	unsigned char buf[FLOAT_EXTENED_BYTES];
+	char *rtn;
+
+	switch(sizeof(long double)) {
+	case FLOAT_QUADRUPLE_BYTES:
+		if (p == NULL || len == 0 || len % 2 != 0 ||
+		    len / 2 > FLOAT_EXTENED_BYTES)
+			return (NULL);
+
+		memset(buf, 0, FLOAT_EXTENED_BYTES);
+
+		for (i = 0; i < len / 2; ++i) {
+			byte = hex_to_dec(p[len - i * 2 - 1]) +
+			    hex_to_dec(p[len - i * 2 - 2]) * 16;
+
+			if (byte < 0 || byte > 255)
+				return (NULL);
+
+#if ELFTC_BYTE_ORDER == ELFTC_BYTE_ORDER_LITTLE_ENDIAN
+			buf[i] = (unsigned char)(byte);
+#else /* ELFTC_BYTE_ORDER != ELFTC_BYTE_ORDER_LITTLE_ENDIAN */
+			buf[FLOAT_EXTENED_BYTES - i -1] =
+			    (unsigned char)(byte);
+#endif /* ELFTC_BYTE_ORDER == ELFTC_BYTE_ORDER_LITTLE_ENDIAN */
+		}
+
+		memset(&f, 0, FLOAT_QUADRUPLE_BYTES);
+
+#if ELFTC_BYTE_ORDER == ELFTC_BYTE_ORDER_LITTLE_ENDIAN
+		memcpy(&f, buf, FLOAT_EXTENED_BYTES);
+#else /* ELFTC_BYTE_ORDER != ELFTC_BYTE_ORDER_LITTLE_ENDIAN */
+		memcpy((unsigned char *)(&f) + 6, buf, FLOAT_EXTENED_BYTES);
+#endif /* ELFTC_BYTE_ORDER == ELFTC_BYTE_ORDER_LITTLE_ENDIAN */
+
+		rtn_len = 256;
+		limit = 0;
+again:
+		if ((rtn = malloc(sizeof(char) * rtn_len)) == NULL)
+			return (NULL);
+
+		if (snprintf(rtn, rtn_len, "%Lfd", f) >= (int)rtn_len) {
+			free(rtn);
+			if (limit++ > FLOAT_SPRINTF_TRY_LIMIT)
+				return (NULL);
+			rtn_len *= BUFFER_GROWFACTOR;
+			goto again;
+		}
+
+		return (rtn);
+	case FLOAT_EXTENED_BYTES:
+		return (decode_fp_to_long_double(p, len));
+	default:
+		return (NULL);
+	}
+}
+
+static char *
+decode_fp_to_long_double(const char *p, size_t len)
+{
+	long double f;
+	size_t rtn_len, limit, i;
+	int byte;
+	char *rtn;
+
+	if (p == NULL || len == 0 || len % 2 != 0 ||
+	    len / 2 > sizeof(long double))
+		return (NULL);
+
+	memset(&f, 0, sizeof(long double));
+
+	for (i = 0; i < len / 2; ++i) {
+		byte = hex_to_dec(p[len - i * 2 - 1]) +
+		    hex_to_dec(p[len - i * 2 - 2]) * 16;
+
+		if (byte < 0 || byte > 255)
+			return (NULL);
+
+#if ELFTC_BYTE_ORDER == ELFTC_BYTE_ORDER_LITTLE_ENDIAN
+		((unsigned char *)&f)[i] = (unsigned char)(byte);
+#else /* ELFTC_BYTE_ORDER != ELFTC_BYTE_ORDER_LITTLE_ENDIAN */
+		((unsigned char *)&f)[sizeof(long double) - i - 1] =
+		    (unsigned char)(byte);
+#endif /* ELFTC_BYTE_ORDER == ELFTC_BYTE_ORDER_LITTLE_ENDIAN */
+	}
+
+	rtn_len = 256;
+	limit = 0;
+again:
+	if ((rtn = malloc(sizeof(char) * rtn_len)) == NULL)
+		return (NULL);
+
+	if (snprintf(rtn, rtn_len, "%Lfd", f) >= (int)rtn_len) {
+		free(rtn);
+		if (limit++ > FLOAT_SPRINTF_TRY_LIMIT)
+			return (NULL);
+		rtn_len *= BUFFER_GROWFACTOR;
+		goto again;
+	}
+
+	return (rtn);
+}
+
+/* Simple hex to integer function used by decode_to_* function. */
+static int
+hex_to_dec(char c)
+{
+
+	switch (c) {
+	case '0':
+		return (0);
+	case '1':
+		return (1);
+	case '2':
+		return (2);
+	case '3':
+		return (3);
+	case '4':
+		return (4);
+	case '5':
+		return (5);
+	case '6':
+		return (6);
+	case '7':
+		return (7);
+	case '8':
+		return (8);
+	case '9':
+		return (9);
+	case 'a':
+		return (10);
+	case 'b':
+		return (11);
+	case 'c':
+		return (12);
+	case 'd':
+		return (13);
+	case 'e':
+		return (14);
+	case 'f':
+		return (15);
+	default:
+		return (-1);
+	};
+}
+
+static void
+vector_read_cmd_dest(struct vector_read_cmd *v)
+{
+
+	if (v == NULL)
+		return;
+
+	free(v->r_container);
+}
+
+/* return -1 at failed, 0 at not found, 1 at found. */
+static int
+vector_read_cmd_find(struct vector_read_cmd *v, enum read_cmd dst)
+{
+	size_t i;
+
+	if (v == NULL || dst == READ_FAIL)
+		return (-1);
+
+	for (i = 0; i < v->size; ++i)
+		if (v->r_container[i] == dst)
+			return (1);
+
+	return (0);
+}
+
+static int
+vector_read_cmd_init(struct vector_read_cmd *v)
+{
+
+	if (v == NULL)
+		return (0);
+
+	v->size = 0;
+	v->capacity = VECTOR_DEF_CAPACITY;
+
+	if ((v->r_container = malloc(sizeof(enum read_cmd) * v->capacity))
+	    == NULL)
+		return (0);
+
+	return (1);
+}
+
+static int
+vector_read_cmd_pop(struct vector_read_cmd *v)
+{
+
+	if (v == NULL || v->size == 0)
+		return (0);
+
+	--v->size;
+	v->r_container[v->size] = READ_FAIL;
+
+	return (1);
+}
+
+static int
+vector_read_cmd_push(struct vector_read_cmd *v, enum read_cmd cmd)
+{
+	enum read_cmd *tmp_r_ctn;
+	size_t tmp_cap;
+	size_t i;
+
+	if (v == NULL)
+		return (0);
+
+	if (v->size == v->capacity) {
+		tmp_cap = v->capacity * BUFFER_GROWFACTOR;
+		if ((tmp_r_ctn = malloc(sizeof(enum read_cmd) * tmp_cap))
+		    == NULL)
+			return (0);
+		for (i = 0; i < v->size; ++i)
+			tmp_r_ctn[i] = v->r_container[i];
+		free(v->r_container);
+		v->r_container = tmp_r_ctn;
+		v->capacity = tmp_cap;
+	}
+
+	v->r_container[v->size] = cmd;
+	++v->size;
+
+	return (1);
+}
+
+static void
+vector_type_qualifier_dest(struct vector_type_qualifier *v)
+{
+
+	if (v == NULL)
+		return;
+
+	free(v->q_container);
+	vector_str_dest(&v->ext_name);
+}
+
+/* size, capacity, ext_name */
+static int
+vector_type_qualifier_init(struct vector_type_qualifier *v)
+{
+
+	if (v == NULL)
+		return (0);
+
+	v->size = 0;
+	v->capacity = VECTOR_DEF_CAPACITY;
+
+	if ((v->q_container = malloc(sizeof(enum type_qualifier) * v->capacity))
+	    == NULL)
+		return (0);
+
+	assert(v->q_container != NULL);
+
+	if (vector_str_init(&v->ext_name) == false) {
+		free(v->q_container);
+		return (0);
+	}
+
+	return (1);
+}
+
+static int
+vector_type_qualifier_push(struct vector_type_qualifier *v,
+    enum type_qualifier t)
+{
+	enum type_qualifier *tmp_ctn;
+	size_t tmp_cap;
+	size_t i;
+
+	if (v == NULL)
+		return (0);
+
+	if (v->size == v->capacity) {
+		tmp_cap = v->capacity * BUFFER_GROWFACTOR;
+		if ((tmp_ctn = malloc(sizeof(enum type_qualifier) * tmp_cap))
+		    == NULL)
+			return (0);
+		for (i = 0; i < v->size; ++i)
+			tmp_ctn[i] = v->q_container[i];
+		free(v->q_container);
+		v->q_container = tmp_ctn;
+		v->capacity = tmp_cap;
+	}
+
+	v->q_container[v->size] = t;
+	++v->size;
+
+	return (1);
+}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/libcxxrt/memory.cc
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/contrib/libcxxrt/memory.cc	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,115 @@
+/**
+ * memory.cc - Contains stub definition of C++ new/delete operators.
+ *
+ * These definitions are intended to be used for testing and are weak symbols
+ * to allow them to be replaced by definitions from a STL implementation.
+ * These versions simply wrap malloc() and free(), they do not provide a
+ * C++-specific allocator.
+ */
+
+#include <stddef.h>
+#include <stdlib.h>
+#include "stdexcept.h"
+
+#if !__has_builtin(__sync_swap)
+#define __sync_swap __sync_lock_test_and_set
+#endif
+
+namespace std
+{
+	struct nothrow_t {};
+}
+
+
+/// The type of the function called when allocation fails.
+typedef void (*new_handler)();
+/**
+ * The function to call when allocation fails.  By default, there is no
+ * handler and a bad allocation exception is thrown if an allocation fails.
+ */
+static new_handler new_handl;
+
+namespace std
+{
+	/**
+	 * Sets a function to be called when there is a failure in new.
+	 */
+	__attribute__((weak))
+	new_handler set_new_handler(new_handler handler)
+	{
+		return __sync_swap(&new_handl, handler);
+	}
+}
+
+
+__attribute__((weak))
+void* operator new(size_t size)
+{
+	void * mem = malloc(size);
+	while (0 == mem)
+	{
+		if (0 != new_handl)
+		{
+			new_handl();
+		}
+		else
+		{
+			throw std::bad_alloc();
+		}
+		mem = malloc(size);
+	}
+
+	return mem;
+}
+
+__attribute__((weak))
+void* operator new(size_t size, const std::nothrow_t &) throw()
+{
+	void *mem = malloc(size);
+	while (0 == mem)
+	{
+		if (0 != new_handl)
+		{
+			try
+			{
+				new_handl();
+			}
+			catch (...)
+			{
+				// nothrow operator new should return NULL in case of
+				// std::bad_alloc exception in new handler
+				return NULL;
+			}
+		}
+		else
+		{
+			return NULL;
+		}
+		mem = malloc(size);
+	}
+
+	return mem;
+}
+
+
+__attribute__((weak))
+void operator delete(void * ptr)
+{
+	free(ptr);
+}
+
+
+__attribute__((weak))
+void * operator new[](size_t size)
+{
+	return ::operator new(size);
+}
+
+
+__attribute__((weak))
+void operator delete[](void * ptr) throw()
+{
+	::operator delete(ptr);
+}
+
+
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/libcxxrt/stdexcept.cc
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/contrib/libcxxrt/stdexcept.cc	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,60 @@
+/**
+ * stdexcept.cc - provides stub implementations of the exceptions required by the runtime.
+ */
+#include "stdexcept.h"
+
+namespace std {
+
+exception::exception() throw() {}
+exception::~exception() {}
+exception::exception(const exception&) throw() {}
+exception& exception::operator=(const exception&) throw()
+{
+	return *this;
+}
+const char* exception::what() const throw()
+{
+	return "std::exception";
+}
+
+bad_alloc::bad_alloc() throw() {}
+bad_alloc::~bad_alloc() {}
+bad_alloc::bad_alloc(const bad_alloc&) throw() {}
+bad_alloc& bad_alloc::operator=(const bad_alloc&) throw()
+{
+	return *this;
+}
+const char* bad_alloc::what() const throw()
+{
+	return "cxxrt::bad_alloc";
+}
+
+
+
+bad_cast::bad_cast() throw() {}
+bad_cast::~bad_cast() {}
+bad_cast::bad_cast(const bad_cast&) throw() {}
+bad_cast& bad_cast::operator=(const bad_cast&) throw()
+{
+	return *this;
+}
+const char* bad_cast::what() const throw()
+{
+	return "std::bad_cast";
+}
+
+bad_typeid::bad_typeid() throw() {}
+bad_typeid::~bad_typeid() {}
+bad_typeid::bad_typeid(const bad_typeid &__rhs) throw() {}
+bad_typeid& bad_typeid::operator=(const bad_typeid &__rhs) throw()
+{
+	return *this;
+}
+
+const char* bad_typeid::what() const throw()
+{
+	return "std::bad_typeid";
+}
+
+} // namespace std
+
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/libcxxrt/stdexcept.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/contrib/libcxxrt/stdexcept.h	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,61 @@
+/**
+ * stdexcept.h - provides a stub version of <stdexcept>, which defines enough
+ * of the exceptions for the runtime to use.  
+ */
+
+namespace std
+{
+
+	class exception
+	{
+	public:
+		exception() throw();
+		exception(const exception&) throw();
+		exception& operator=(const exception&) throw();
+		virtual ~exception();
+		virtual const char* what() const throw();
+	};
+
+
+	/**
+	 * Bad allocation exception.  Thrown by ::operator new() if it fails.
+	 */
+	class bad_alloc: public exception
+	{
+	public:
+		bad_alloc() throw();
+		bad_alloc(const bad_alloc&) throw();
+		bad_alloc& operator=(const bad_alloc&) throw();
+		~bad_alloc();
+		virtual const char* what() const throw();
+	};
+
+	/**
+	 * Bad cast exception.  Thrown by the __cxa_bad_cast() helper function.
+	 */
+	class bad_cast: public exception {
+	public:
+		bad_cast() throw();
+		bad_cast(const bad_cast&) throw();
+		bad_cast& operator=(const bad_cast&) throw();
+		virtual ~bad_cast();
+		virtual const char* what() const throw();
+	};
+
+	/**
+	 * Bad typeidexception.  Thrown by the __cxa_bad_typeid() helper function.
+	 */
+	class bad_typeid: public exception
+	{
+	public:
+		bad_typeid() throw();
+		bad_typeid(const bad_typeid &__rhs) throw();
+		virtual ~bad_typeid();
+		bad_typeid& operator=(const bad_typeid &__rhs) throw();
+		virtual const char* what() const throw();
+	};
+
+
+
+} // namespace std
+
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/libcxxrt/terminate.cc
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/contrib/libcxxrt/terminate.cc	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,14 @@
+#include <stdlib.h>
+
+namespace std
+{
+	/**
+	 * Stub implementation of std::terminate.  Used when the STL implementation
+	 * doesn't provide one.
+	 */
+	__attribute__((weak))
+	void terminate()
+	{
+		abort();
+	}
+}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/libcxxrt/typeinfo
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/contrib/libcxxrt/typeinfo	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,26 @@
+namespace std
+{
+	/**
+	  * Standard type info class.  The layout of this class is specified by the
+	  * ABI.
+	  */
+	class type_info
+	{
+		public:
+		/**
+		 * Virtual destructor.  This class must have one virtual function to
+		 * ensure that it has a vtable.
+		 */
+		virtual ~type_info();
+		bool operator==(const type_info &) const;
+		bool operator!=(const type_info &) const;
+		bool before(const type_info &) const;
+		const char* name() const;
+		type_info();
+		private:
+		type_info(const type_info& rhs);
+		type_info& operator= (const type_info& rhs);
+		const char *__type_name;
+	};
+}
+
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/libcxxrt/typeinfo.cc
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/contrib/libcxxrt/typeinfo.cc	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,83 @@
+#include "typeinfo.h"
+#include <string.h>
+#include <stdlib.h>
+#include <stdio.h>
+
+using std::type_info;
+
+type_info::~type_info() {}
+
+bool type_info::operator==(const type_info &other) const
+{
+	return __type_name == other.__type_name;
+}
+bool type_info::operator!=(const type_info &other) const
+{
+	return __type_name != other.__type_name;
+}
+bool type_info::before(const type_info &other) const
+{
+	return __type_name < other.__type_name;
+}
+const char* type_info::name() const
+{
+	return __type_name;
+}
+type_info::type_info (const type_info& rhs)
+{
+	__type_name = rhs.__type_name;
+}
+type_info& type_info::operator= (const type_info& rhs) 
+{
+	return *new type_info(rhs);
+}
+
+ABI_NAMESPACE::__fundamental_type_info::~__fundamental_type_info() {}
+ABI_NAMESPACE::__array_type_info::~__array_type_info() {}
+ABI_NAMESPACE::__function_type_info::~__function_type_info() {}
+ABI_NAMESPACE::__enum_type_info::~__enum_type_info() {}
+ABI_NAMESPACE::__class_type_info::~__class_type_info() {}
+ABI_NAMESPACE::__si_class_type_info::~__si_class_type_info() {}
+ABI_NAMESPACE::__vmi_class_type_info::~__vmi_class_type_info() {}
+ABI_NAMESPACE::__pbase_type_info::~__pbase_type_info() {}
+ABI_NAMESPACE::__pointer_type_info::~__pointer_type_info() {}
+ABI_NAMESPACE::__pointer_to_member_type_info::~__pointer_to_member_type_info() {}
+
+// From libelftc
+extern "C" char    *__cxa_demangle_gnu3(const char *);
+
+extern "C" char* __cxa_demangle(const char* mangled_name,
+                                char* buf,
+                                size_t* n,
+                                int* status)
+{
+	// TODO: We should probably just be linking against libelf-tc, rather than
+	// copying their code.  This requires them to do an actual release,
+	// however, and for our changes to be pushed upstream.  We also need to
+	// call a different demangling function here depending on the ABI (e.g.
+	// ARM).
+	char *demangled = __cxa_demangle_gnu3(mangled_name);
+	if (NULL != demangled)
+	{
+		size_t len = strlen(demangled);
+		buf = (char*)realloc(buf, len+1);
+		if (0 != buf)
+		{
+			memcpy(buf, demangled, len);
+			buf[len] = 0;
+			*n = len;
+			*status = 0;
+		}
+		else
+		{
+			*status = -1;
+		}
+		free(demangled);
+	}
+	else
+	{
+		*status = -2;
+		return NULL;
+	}
+	return buf;
+}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/libcxxrt/typeinfo.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/contrib/libcxxrt/typeinfo.h	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,200 @@
+#include <stddef.h>
+#include "abi_namespace.h"
+#include "typeinfo"
+
+namespace ABI_NAMESPACE
+{
+	/**
+	 * Primitive type info, for intrinsic types.
+	 */
+	struct __fundamental_type_info : public std::type_info
+	{
+		virtual ~__fundamental_type_info();
+	};
+	/**
+	 * Type info for arrays.  
+	 */
+	struct __array_type_info : public std::type_info
+	{
+		virtual ~__array_type_info();
+	};
+	/**
+	 * Type info for functions.
+	 */
+	struct __function_type_info : public std::type_info
+	{
+		virtual ~__function_type_info();
+	};
+	/**
+	 * Type info for enums.
+	 */
+	struct __enum_type_info : public std::type_info
+	{
+		virtual ~__enum_type_info();
+	};
+
+	/**
+	 * Base class for class type info.  Used only for tentative definitions.
+	 */
+	struct __class_type_info : public std::type_info
+	{
+		virtual ~__class_type_info();
+		/**
+		 * Function implementing dynamic casts.
+		 */
+		virtual void *cast_to(void *obj,
+		                      const struct __class_type_info *other) const;
+		/**
+		 * Function returning whether a cast from this type to another type is
+		 * possible.
+		 */
+		virtual bool can_cast_to(const struct __class_type_info *other) const;
+	};
+
+	/**
+	 * Single-inheritance class type info.  This is used for classes containing
+	 * a single non-virtual base class at offset 0.
+	 */
+	struct __si_class_type_info : public __class_type_info
+	{
+		virtual ~__si_class_type_info();
+		const __class_type_info *__base_type;
+		virtual void *cast_to(void *obj, const struct __class_type_info *other) const;
+        virtual bool can_cast_to(const struct __class_type_info *other) const;
+	};
+
+	/**
+	 * Type info for base classes.  Classes with multiple bases store an array
+	 * of these, one for each superclass.
+	 */
+	struct __base_class_type_info
+	{
+		const __class_type_info *__base_type;
+		private:
+			/**
+			 * The high __offset_shift bits of this store the (signed) offset
+			 * of the base class.  The low bits store flags from
+			 * __offset_flags_masks.
+			 */
+			long __offset_flags;
+			/**
+			 * Flags used in the low bits of __offset_flags.
+			 */
+			enum __offset_flags_masks
+			{
+				/** This base class is virtual. */
+				__virtual_mask = 0x1,
+				/** This base class is public. */
+				__public_mask = 0x2,
+				/** The number of bits reserved for flags. */
+				__offset_shift = 8
+			};
+		public:
+			/**
+			 * Returns the offset of the base class.
+			 */
+			long offset() const
+			{
+				return __offset_flags >> __offset_shift;
+			}
+			/**
+			 * Returns the flags.
+			 */
+			long flags() const
+			{
+				return __offset_flags & ((1 << __offset_shift) - 1);
+			}
+			/**
+			 * Returns whether this is a public base class.
+			 */
+			bool isPublic() const { return flags() & __public_mask; }
+			/**
+			 * Returns whether this is a virtual base class.
+			 */
+			bool isVirtual() const { return flags() & __virtual_mask; }
+	};
+
+	/**
+	 * Type info for classes with virtual bases or multiple superclasses.
+	 */
+	struct __vmi_class_type_info : public __class_type_info
+	{
+		virtual ~__vmi_class_type_info();
+		/** Flags describing this class.  Contains values from __flags_masks. */
+		unsigned int __flags;
+		/** The number of base classes. */
+		unsigned int __base_count;
+		/** 
+		 * Array of base classes - this actually has __base_count elements, not
+		 * 1.
+		 */
+		__base_class_type_info __base_info[1];
+
+		/**
+		 * Flags used in the __flags field.
+		 */
+		enum __flags_masks
+		{
+			/** The class has non-diamond repeated inheritance. */
+			__non_diamond_repeat_mask = 0x1,
+			/** The class is diamond shaped. */
+			__diamond_shaped_mask = 0x2
+		};
+		virtual void *cast_to(void *obj, const struct __class_type_info *other) const;
+        virtual bool can_cast_to(const struct __class_type_info *other) const;
+	};
+
+	/**
+	 * Base class used for both pointer and pointer-to-member type info.
+	 */
+	struct __pbase_type_info : public std::type_info
+	{
+		virtual ~__pbase_type_info();
+		/**
+		 * Flags.  Values from __masks.
+		 */
+		unsigned int __flags;
+		/**
+		 * The type info for the pointee.
+		 */
+		const std::type_info *__pointee;
+
+		/**
+		 * Masks used for qualifiers on the pointer.
+		 */
+		enum __masks
+		{
+			/** Pointer has const qualifier. */
+			__const_mask = 0x1,
+			/** Pointer has volatile qualifier. */
+			__volatile_mask = 0x2,
+			/** Pointer has restrict qualifier. */
+			__restrict_mask = 0x4,
+			/** Pointer points to an incomplete type. */
+			__incomplete_mask = 0x8,
+			/** Pointer is a pointer to a member of an incomplete class. */
+			__incomplete_class_mask = 0x10
+		};
+	};
+
+	/**
+	 * Pointer type info.
+	 */
+	struct __pointer_type_info : public __pbase_type_info
+	{
+		virtual ~__pointer_type_info();
+	};
+
+	/**
+	 * Pointer to member type info.
+	 */
+	struct __pointer_to_member_type_info : public __pbase_type_info
+	{
+		virtual ~__pointer_to_member_type_info();
+		/**
+		 * Pointer to the class containing this member.
+		 */
+		const __class_type_info *__context;
+	};
+
+}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/libcxxrt/unwind-arm.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/contrib/libcxxrt/unwind-arm.h	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,201 @@
+/**
+ * ARM-specific unwind definitions.  These are taken from the ARM EHABI
+ * specification.
+ */
+ typedef enum
+{
+	_URC_OK = 0,                /* operation completed successfully */
+	_URC_FOREIGN_EXCEPTION_CAUGHT = 1,
+    _URC_END_OF_STACK = 5,
+	_URC_HANDLER_FOUND = 6,
+	_URC_INSTALL_CONTEXT = 7,
+	_URC_CONTINUE_UNWIND = 8,
+	_URC_FAILURE = 9,            /* unspecified failure of some kind */
+	_URC_FATAL_PHASE1_ERROR = _URC_FAILURE
+} _Unwind_Reason_Code;
+
+typedef uint32_t _Unwind_State;
+#ifdef __clang__
+static const _Unwind_State _US_VIRTUAL_UNWIND_FRAME  = 0;
+static const _Unwind_State _US_UNWIND_FRAME_STARTING = 1;
+static const _Unwind_State _US_UNWIND_FRAME_RESUME   = 2;
+#else // GCC fails at knowing what a constant expression is
+#	define _US_VIRTUAL_UNWIND_FRAME  0
+#	define _US_UNWIND_FRAME_STARTING 1
+#	define _US_UNWIND_FRAME_RESUME 2
+#endif
+
+typedef struct _Unwind_Context _Unwind_Context;
+
+typedef uint32_t _Unwind_EHT_Header;
+
+struct _Unwind_Exception
+{
+	uint64_t exception_class;
+	void (*exception_cleanup)(_Unwind_Reason_Code, struct _Unwind_Exception *);
+	/* Unwinder cache, private fields for the unwinder's use */
+	struct
+	{
+		uint32_t reserved1;
+		uint32_t reserved2;
+		uint32_t reserved3;
+		uint32_t reserved4;
+		uint32_t reserved5;
+	/* init reserved1 to 0, then don't touch */
+	} unwinder_cache;
+	/* Propagation barrier cache (valid after phase 1): */
+	struct
+	{
+		uint32_t sp;
+		uint32_t bitpattern[5];
+	} barrier_cache;
+	/* Cleanup cache (preserved over cleanup): */
+	struct
+	{
+		uint32_t bitpattern[4];
+	} cleanup_cache;
+	/* Pr cache (for pr's benefit): */
+	struct
+	{
+		/** function start address */
+		uint32_t fnstart;
+		/** pointer to EHT entry header word */
+		_Unwind_EHT_Header *ehtp;
+		/** additional data */
+		uint32_t additional;
+		uint32_t reserved1;
+	} pr_cache;
+	/** Force alignment of next item to 8-byte boundary */
+	long long int :0;
+};
+
+/* Unwinding functions */
+_Unwind_Reason_Code _Unwind_RaiseException(struct _Unwind_Exception *ucbp);
+void _Unwind_Resume(struct _Unwind_Exception *ucbp);
+void _Unwind_Complete(struct _Unwind_Exception *ucbp);
+void _Unwind_DeleteException(struct _Unwind_Exception *ucbp);
+void *_Unwind_GetLanguageSpecificData(struct _Unwind_Context*);
+
+typedef enum
+{
+	_UVRSR_OK = 0,
+	_UVRSR_NOT_IMPLEMENTED = 1,
+	_UVRSR_FAILED = 2
+} _Unwind_VRS_Result;
+typedef enum
+{
+	_UVRSC_CORE = 0,
+	_UVRSC_VFP = 1,
+	_UVRSC_WMMXD = 3,
+	_UVRSC_WMMXC = 4
+} _Unwind_VRS_RegClass;
+typedef enum
+{
+	_UVRSD_UINT32 = 0,
+	_UVRSD_VFPX = 1,
+	_UVRSD_UINT64 = 3,
+	_UVRSD_FLOAT = 4,
+	_UVRSD_DOUBLE = 5
+} _Unwind_VRS_DataRepresentation;
+
+_Unwind_VRS_Result _Unwind_VRS_Get(_Unwind_Context *context,
+                                   _Unwind_VRS_RegClass regclass,
+                                   uint32_t regno,
+                                   _Unwind_VRS_DataRepresentation representation,
+                                   void *valuep);
+_Unwind_VRS_Result _Unwind_VRS_Set(_Unwind_Context *context,
+                                   _Unwind_VRS_RegClass regclass,
+                                   uint32_t regno,
+                                   _Unwind_VRS_DataRepresentation representation,
+                                   void *valuep);
+
+/* Return the base-address for data references.  */
+extern unsigned long _Unwind_GetDataRelBase(struct _Unwind_Context *);
+
+/* Return the base-address for text references.  */
+extern unsigned long _Unwind_GetTextRelBase(struct _Unwind_Context *);
+extern unsigned long _Unwind_GetRegionStart(struct _Unwind_Context *);
+
+typedef _Unwind_Reason_Code (*_Unwind_Trace_Fn) (struct _Unwind_Context *,
+						 void *);
+extern _Unwind_Reason_Code _Unwind_Backtrace (_Unwind_Trace_Fn, void *);
+extern _Unwind_Reason_Code
+	  _Unwind_Resume_or_Rethrow (struct _Unwind_Exception *);
+
+/**
+ * The next set of functions are compatibility extensions, implementing Itanium
+ * ABI functions on top of ARM ones.
+ */
+
+#define _UA_SEARCH_PHASE	1
+#define _UA_CLEANUP_PHASE	2
+#define _UA_HANDLER_FRAME	4
+#define _UA_FORCE_UNWIND	8
+
+static inline unsigned long _Unwind_GetGR(struct _Unwind_Context *context, int reg)
+{
+	unsigned long val;
+	_Unwind_VRS_Get(context, _UVRSC_CORE, reg, _UVRSD_UINT32, &val);
+	return val;
+}
+static inline  void _Unwind_SetGR(struct _Unwind_Context *context, int reg, unsigned long val)
+{
+	_Unwind_VRS_Set(context, _UVRSC_CORE, reg, _UVRSD_UINT32, &val);
+}
+static inline unsigned long _Unwind_GetIP(_Unwind_Context *context)
+{
+	// Low bit store the thumb state - discard it
+	return _Unwind_GetGR(context, 15) & ~1;
+}
+static inline void _Unwind_SetIP(_Unwind_Context *context, unsigned long val)
+{
+	// The lowest bit of the instruction pointer indicates whether we're in
+	// thumb or ARM mode.  This is assumed to be fixed throughout a function,
+	// so must be propagated when setting the program counter.
+	unsigned long thumbState = _Unwind_GetGR(context, 15) & 1;
+   _Unwind_SetGR(context, 15, (val | thumbState));
+}
+
+/** GNU API function that unwinds the frame */
+_Unwind_Reason_Code __gnu_unwind_frame(struct _Unwind_Exception*, struct _Unwind_Context*);
+
+
+#define DECLARE_PERSONALITY_FUNCTION(name) \
+_Unwind_Reason_Code name(_Unwind_State state,\
+                         struct _Unwind_Exception *exceptionObject,\
+                         struct _Unwind_Context *context);
+
+#define BEGIN_PERSONALITY_FUNCTION(name) \
+_Unwind_Reason_Code name(_Unwind_State state,\
+                         struct _Unwind_Exception *exceptionObject,\
+                         struct _Unwind_Context *context)\
+{\
+	int version = 1;\
+	uint64_t exceptionClass = exceptionObject->exception_class;\
+	int actions;\
+	switch (state)\
+	{\
+		default: return _URC_FAILURE;\
+		case _US_VIRTUAL_UNWIND_FRAME:\
+		{\
+			actions = _UA_SEARCH_PHASE;\
+			break;\
+		}\
+		case _US_UNWIND_FRAME_STARTING:\
+		{\
+			actions = _UA_CLEANUP_PHASE;\
+			if (exceptionObject->barrier_cache.sp == _Unwind_GetGR(context, 13))\
+			{\
+				actions |= _UA_HANDLER_FRAME;\
+			}\
+			break;\
+		}\
+		case _US_UNWIND_FRAME_RESUME:\
+		{\
+			return continueUnwinding(exceptionObject, context);\
+			break;\
+		}\
+	}\
+	_Unwind_SetGR (context, 12, (unsigned long)exceptionObject);\
+
+#define CALL_PERSONALITY_FUNCTION(name) name(state,exceptionObject,context)
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/libcxxrt/unwind-itanium.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/contrib/libcxxrt/unwind-itanium.h	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,170 @@
+/* libunwind - a platform-independent unwind library
+   Copyright (C) 2003 Hewlett-Packard Co
+	Contributed by David Mosberger-Tang <davidm at hpl.hp.com>
+
+This file is part of libunwind.
+
+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 _UNWIND_H
+#define _UNWIND_H
+
+/* For uint64_t */
+#include <stdint.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Minimal interface as per C++ ABI draft standard:
+
+	http://www.codesourcery.com/cxx-abi/abi-eh.html */
+
+typedef enum
+  {
+    _URC_NO_REASON = 0,
+    _URC_FOREIGN_EXCEPTION_CAUGHT = 1,
+    _URC_FATAL_PHASE2_ERROR = 2,
+    _URC_FATAL_PHASE1_ERROR = 3,
+    _URC_NORMAL_STOP = 4,
+    _URC_END_OF_STACK = 5,
+    _URC_HANDLER_FOUND = 6,
+    _URC_INSTALL_CONTEXT = 7,
+    _URC_CONTINUE_UNWIND = 8
+  }
+_Unwind_Reason_Code;
+
+typedef int _Unwind_Action;
+
+#define _UA_SEARCH_PHASE	1
+#define _UA_CLEANUP_PHASE	2
+#define _UA_HANDLER_FRAME	4
+#define _UA_FORCE_UNWIND	8
+
+struct _Unwind_Context;		/* opaque data-structure */
+struct _Unwind_Exception;	/* forward-declaration */
+
+typedef void (*_Unwind_Exception_Cleanup_Fn) (_Unwind_Reason_Code,
+					      struct _Unwind_Exception *);
+
+typedef _Unwind_Reason_Code (*_Unwind_Stop_Fn) (int, _Unwind_Action,
+						uint64_t,
+						struct _Unwind_Exception *,
+						struct _Unwind_Context *,
+						void *);
+
+/* The C++ ABI requires exception_class, private_1, and private_2 to
+   be of type uint64 and the entire structure to be
+   double-word-aligned. Please note that exception_class stays 64-bit 
+   even on 32-bit machines for gcc compatibility.  */
+struct _Unwind_Exception
+  {
+    uint64_t exception_class;
+    _Unwind_Exception_Cleanup_Fn exception_cleanup;
+    unsigned long private_1;
+    unsigned long private_2;
+  } __attribute__((__aligned__));
+
+extern _Unwind_Reason_Code _Unwind_RaiseException (struct _Unwind_Exception *);
+extern _Unwind_Reason_Code _Unwind_ForcedUnwind (struct _Unwind_Exception *,
+						 _Unwind_Stop_Fn, void *);
+extern void _Unwind_Resume (struct _Unwind_Exception *);
+extern void _Unwind_DeleteException (struct _Unwind_Exception *);
+extern unsigned long _Unwind_GetGR (struct _Unwind_Context *, int);
+extern void _Unwind_SetGR (struct _Unwind_Context *, int, unsigned long);
+extern unsigned long _Unwind_GetIP (struct _Unwind_Context *);
+extern unsigned long _Unwind_GetIPInfo (struct _Unwind_Context *, int *);
+extern void _Unwind_SetIP (struct _Unwind_Context *, unsigned long);
+extern unsigned long _Unwind_GetLanguageSpecificData (struct _Unwind_Context*);
+extern unsigned long _Unwind_GetRegionStart (struct _Unwind_Context *);
+
+#ifdef _GNU_SOURCE
+
+/* Callback for _Unwind_Backtrace().  The backtrace stops immediately
+   if the callback returns any value other than _URC_NO_REASON. */
+typedef _Unwind_Reason_Code (*_Unwind_Trace_Fn) (struct _Unwind_Context *,
+						 void *);
+
+/* See http://gcc.gnu.org/ml/gcc-patches/2001-09/msg00082.html for why
+   _UA_END_OF_STACK exists.  */
+# define _UA_END_OF_STACK	16
+
+/* If the unwind was initiated due to a forced unwind, resume that
+   operation, else re-raise the exception.  This is used by
+   __cxa_rethrow().  */
+extern _Unwind_Reason_Code
+	  _Unwind_Resume_or_Rethrow (struct _Unwind_Exception *);
+
+/* See http://gcc.gnu.org/ml/gcc-patches/2003-09/msg00154.html for why
+   _Unwind_GetBSP() exists.  */
+extern unsigned long _Unwind_GetBSP (struct _Unwind_Context *);
+
+/* Return the "canonical frame address" for the given context.
+   This is used by NPTL... */
+extern unsigned long _Unwind_GetCFA (struct _Unwind_Context *);
+
+/* Return the base-address for data references.  */
+extern unsigned long _Unwind_GetDataRelBase (struct _Unwind_Context *);
+
+/* Return the base-address for text references.  */
+extern unsigned long _Unwind_GetTextRelBase (struct _Unwind_Context *);
+
+/* Call _Unwind_Trace_Fn once for each stack-frame, without doing any
+   cleanup.  The first frame for which the callback is invoked is the
+   one for the caller of _Unwind_Backtrace().  _Unwind_Backtrace()
+   returns _URC_END_OF_STACK when the backtrace stopped due to
+   reaching the end of the call-chain or _URC_FATAL_PHASE1_ERROR if it
+   stops for any other reason.  */
+extern _Unwind_Reason_Code _Unwind_Backtrace (_Unwind_Trace_Fn, void *);
+
+/* Find the start-address of the procedure containing the specified IP
+   or NULL if it cannot be found (e.g., because the function has no
+   unwind info).  Note: there is not necessarily a one-to-one
+   correspondence between source-level functions and procedures: some
+   functions don't have unwind-info and others are split into multiple
+   procedures.  */
+extern void *_Unwind_FindEnclosingFunction (void *);
+
+/* See also Linux Standard Base Spec:
+    http://www.linuxbase.org/spec/refspecs/LSB_1.3.0/gLSB/gLSB/libgcc-s.html */
+
+#endif /* _GNU_SOURCE */
+
+#define DECLARE_PERSONALITY_FUNCTION(name) \
+_Unwind_Reason_Code name(int version,\
+                         _Unwind_Action actions,\
+                         uint64_t exceptionClass,\
+                         struct _Unwind_Exception *exceptionObject,\
+                         struct _Unwind_Context *context);
+#define BEGIN_PERSONALITY_FUNCTION(name) \
+_Unwind_Reason_Code name(int version,\
+                         _Unwind_Action actions,\
+                         uint64_t exceptionClass,\
+                         struct _Unwind_Exception *exceptionObject,\
+                         struct _Unwind_Context *context)\
+{
+
+#define CALL_PERSONALITY_FUNCTION(name) name(version, actions, exceptionClass, exceptionObject, context)
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _UNWIND_H */
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/contrib/libcxxrt/unwind.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/contrib/libcxxrt/unwind.h	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,18 @@
+#ifndef UNWIND_H_INCLUDED
+#define UNWIND_H_INCLUDED
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifdef __arm__
+#include "unwind-arm.h"
+#else
+#include "unwind-itanium.h"
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/etc/devd/apple.conf
--- a/head/etc/devd/apple.conf	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/etc/devd/apple.conf	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-# $FreeBSD: head/etc/devd/apple.conf 226449 2011-10-16 21:01:42Z nwhitehorn $
+# $FreeBSD: head/etc/devd/apple.conf 228277 2011-12-05 14:13:21Z jhibbits $
 #
 # PowerPC Apple specific devd events
 
@@ -11,6 +11,16 @@
 };
 
 
+# PowerBook and iBook lid close.
+notify 0 {
+	match "system"		"PMU";
+	match "subsystem"	"lid";
+	match "type"		"close";
+	match "notify"		"0x0";
+	action			"shutdown -p now";
+};
+
+
 # The next blocks enable volume hotkeys that can be found on Apple laptops
 notify 0 {
 	match "system"		"PMU";
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/etc/mtree/BSD.include.dist
--- a/head/etc/mtree/BSD.include.dist	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/etc/mtree/BSD.include.dist	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-# $FreeBSD: head/etc/mtree/BSD.include.dist 225790 2011-09-27 12:14:43Z kib $
+# $FreeBSD: head/etc/mtree/BSD.include.dist 227983 2011-11-25 20:59:04Z theraven $
 #
 # Please see the file src/etc/mtree/README before making changes to this file.
 #
@@ -76,6 +76,10 @@
             tr1
             ..
         ..
+        v1
+            ext
+            ..
+        ..
     ..
     cam
         ata
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/etc/rc.d/kld
--- a/head/etc/rc.d/kld	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/etc/rc.d/kld	Tue Dec 06 20:26:16 2011 +0200
@@ -24,10 +24,10 @@
 # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 # SUCH DAMAGE.
 #
-# $FreeBSD: head/etc/rc.d/kld 224273 2011-07-22 21:08:19Z dougb $
+# $FreeBSD: head/etc/rc.d/kld 228191 2011-12-01 22:50:10Z obrien $
 #
 # PROVIDE: kld
-# REQUIRE: FILESYSTEMS
+# REQUIRE: kldxref
 # KEYWORD: nojail
 
 . /etc/rc.subr
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/Makefile
--- a/head/gnu/lib/Makefile	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/gnu/lib/Makefile	Tue Dec 06 20:26:16 2011 +0200
@@ -1,9 +1,8 @@
-# $FreeBSD: head/gnu/lib/Makefile 220755 2011-04-17 21:03:23Z dim $
+# $FreeBSD: head/gnu/lib/Makefile 227951 2011-11-24 20:31:06Z fjoe $
 
 .include <bsd.own.mk>
 
-SUBDIR= csu libgcc libgcov libdialog libgomp libodialog libregex libreadline \
-	libssp
+SUBDIR= csu libgcc libgcov libdialog libgomp libregex libreadline libssp
 
 # libsupc++ uses libstdc++ headers, although 'make includes' should
 # have taken care of that already.
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/CHANGES
--- a/head/gnu/lib/libodialog/CHANGES	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,9 +0,0 @@
-- Added two variables to call to dialog_menu() to save the position 
-  in the menu when choosing a menu-option.
-
-- Added dialog_fselect(), implements a fileselector dialog
-- Added ui-interface objects: Stringobject, Listobject and Buttonobject.
-  The fileselector dialog was built using these objects.
-- changed dialog_menu to use PGUP and PGDN
-- Added dialog_mesgbox, which display text given in a char buffer.
-- 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/COPYING
--- a/head/gnu/lib/libodialog/COPYING	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,339 +0,0 @@
-		    GNU GENERAL PUBLIC LICENSE
-		       Version 2, June 1991
-
- Copyright (C) 1989, 1991 Free Software Foundation, Inc.
-                          675 Mass Ave, Cambridge, MA 02139, USA
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
-			    Preamble
-
-  The licenses for most software are designed to take away your
-freedom to share and change it.  By contrast, the GNU General Public
-License is intended to guarantee your freedom to share and change free
-software--to make sure the software is free for all its users.  This
-General Public License applies to most of the Free Software
-Foundation's software and to any other program whose authors commit to
-using it.  (Some other Free Software Foundation software is covered by
-the GNU Library General Public License instead.)  You can apply it to
-your programs, too.
-
-  When we speak of free software, we are referring to freedom, 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 or use pieces of it
-in new free programs; and that you know you can do these things.
-
-  To protect your rights, we need to make restrictions that forbid
-anyone to deny you these rights or to ask you to surrender the rights.
-These restrictions translate to certain responsibilities for you if you
-distribute copies of the software, or if you modify it.
-
-  For example, if you distribute copies of such a program, whether
-gratis or for a fee, you must give the recipients all the rights that
-you have.  You must make sure that they, too, receive or can get the
-source code.  And you must show them these terms so they know their
-rights.
-
-  We protect your rights with two steps: (1) copyright the software, and
-(2) offer you this license which gives you legal permission to copy,
-distribute and/or modify the software.
-
-  Also, for each author's protection and ours, we want to make certain
-that everyone understands that there is no warranty for this free
-software.  If the software is modified by someone else and passed on, we
-want its recipients to know that what they have is not the original, so
-that any problems introduced by others will not reflect on the original
-authors' reputations.
-
-  Finally, any free program is threatened constantly by software
-patents.  We wish to avoid the danger that redistributors of a free
-program will individually obtain patent licenses, in effect making the
-program proprietary.  To prevent this, we have made it clear that any
-patent must be licensed for everyone's free use or not licensed at all.
-
-  The precise terms and conditions for copying, distribution and
-modification follow.
-
-		    GNU GENERAL PUBLIC LICENSE
-   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
-
-  0. This License applies to any program or other work which contains
-a notice placed by the copyright holder saying it may be distributed
-under the terms of this General Public License.  The "Program", below,
-refers to any such program or work, and a "work based on the Program"
-means either the Program or any derivative work under copyright law:
-that is to say, a work containing the Program or a portion of it,
-either verbatim or with modifications and/or translated into another
-language.  (Hereinafter, translation is included without limitation in
-the term "modification".)  Each licensee is addressed as "you".
-
-Activities other than copying, distribution and modification are not
-covered by this License; they are outside its scope.  The act of
-running the Program is not restricted, and the output from the Program
-is covered only if its contents constitute a work based on the
-Program (independent of having been made by running the Program).
-Whether that is true depends on what the Program does.
-
-  1. You may copy and distribute verbatim copies of the Program's
-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 give any other recipients of the Program a copy of this License
-along with the Program.
-
-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 Program or any portion
-of it, thus forming a work based on the Program, 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) You must cause the modified files to carry prominent notices
-    stating that you changed the files and the date of any change.
-
-    b) You must cause any work that you distribute or publish, that in
-    whole or in part contains or is derived from the Program or any
-    part thereof, to be licensed as a whole at no charge to all third
-    parties under the terms of this License.
-
-    c) If the modified program normally reads commands interactively
-    when run, you must cause it, when started running for such
-    interactive use in the most ordinary way, to print or display an
-    announcement including an appropriate copyright notice and a
-    notice that there is no warranty (or else, saying that you provide
-    a warranty) and that users may redistribute the program under
-    these conditions, and telling the user how to view a copy of this
-    License.  (Exception: if the Program itself is interactive but
-    does not normally print such an announcement, your work based on
-    the Program is not required to print an announcement.)
-
-These requirements apply to the modified work as a whole.  If
-identifiable sections of that work are not derived from the Program,
-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 Program, 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 Program.
-
-In addition, mere aggregation of another work not based on the Program
-with the Program (or with a work based on the Program) on a volume of
-a storage or distribution medium does not bring the other work under
-the scope of this License.
-
-  3. You may copy and distribute the Program (or a work based on it,
-under Section 2) in object code or executable form under the terms of
-Sections 1 and 2 above provided that you also do one of the following:
-
-    a) 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; or,
-
-    b) Accompany it with a written offer, valid for at least three
-    years, to give any third party, for a charge no more than your
-    cost of physically performing source distribution, a complete
-    machine-readable copy of the corresponding source code, to be
-    distributed under the terms of Sections 1 and 2 above on a medium
-    customarily used for software interchange; or,
-
-    c) Accompany it with the information you received as to the offer
-    to distribute corresponding source code.  (This alternative is
-    allowed only for noncommercial distribution and only if you
-    received the program in object code or executable form with such
-    an offer, in accord with Subsection b above.)
-
-The source code for a work means the preferred form of the work for
-making modifications to it.  For an executable work, 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 executable.  However, as a
-special exception, the source code 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.
-
-If distribution of executable or 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 counts as
-distribution of the source code, even though third parties are not
-compelled to copy the source along with the object code.
-
-  4. You may not copy, modify, sublicense, or distribute the Program
-except as expressly provided under this License.  Any attempt
-otherwise to copy, modify, sublicense or distribute the Program 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.
-
-  5. 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 Program or its derivative works.  These actions are
-prohibited by law if you do not accept this License.  Therefore, by
-modifying or distributing the Program (or any work based on the
-Program), you indicate your acceptance of this License to do so, and
-all its terms and conditions for copying, distributing or modifying
-the Program or works based on it.
-
-  6. Each time you redistribute the Program (or any work based on the
-Program), the recipient automatically receives a license from the
-original licensor to copy, distribute or modify the Program 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 to
-this License.
-
-  7. 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 Program at all.  For example, if a patent
-license would not permit royalty-free redistribution of the Program 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 Program.
-
-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.
-
-  8. If the distribution and/or use of the Program is restricted in
-certain countries either by patents or by copyrighted interfaces, the
-original copyright holder who places the Program 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.
-
-  9. The Free Software Foundation may publish revised and/or new versions
-of the 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 Program
-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 Program does not specify a version number of
-this License, you may choose any version ever published by the Free Software
-Foundation.
-
-  10. If you wish to incorporate parts of the Program into other free
-programs whose distribution conditions are different, 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
-
-  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
-FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
-OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
-PROVIDE THE PROGRAM "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 PROGRAM IS WITH YOU.  SHOULD THE
-PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
-REPAIR OR CORRECTION.
-
-  12. 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 PROGRAM 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 PROGRAM (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 PROGRAM TO OPERATE WITH ANY OTHER
-PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
-POSSIBILITY OF SUCH DAMAGES.
-
-		     END OF TERMS AND CONDITIONS
-
-	Appendix: How to Apply These Terms to Your New Programs
-
-  If you develop a new program, and you want it to be of the greatest
-possible use to the public, the best way to achieve this is to make it
-free software which everyone can redistribute and change under these terms.
-
-  To do so, attach the following notices to the program.  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.
-
-    <one line to give the program's name and a brief idea of what it does.>
-    Copyright (C) 19yy  <name of author>
-
-    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., 675 Mass Ave, Cambridge, MA 02139, USA.
-
-Also add information on how to contact you by electronic and paper mail.
-
-If the program is interactive, make it output a short notice like this
-when it starts in an interactive mode:
-
-    Gnomovision version 69, Copyright (C) 19yy name of author
-    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
-    This is free software, and you are welcome to redistribute it
-    under certain conditions; type `show c' for details.
-
-The hypothetical commands `show w' and `show c' should show the appropriate
-parts of the General Public License.  Of course, the commands you use may
-be called something other than `show w' and `show c'; they could even be
-mouse-clicks or menu items--whatever suits your program.
-
-You should also get your employer (if you work as a programmer) or your
-school, if any, to sign a "copyright disclaimer" for the program, if
-necessary.  Here is a sample; alter the names:
-
-  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
-  `Gnomovision' (which makes passes at compilers) written by James Hacker.
-
-  <signature of Ty Coon>, 1 April 1989
-  Ty Coon, President of Vice
-
-This General Public License does not permit incorporating your program into
-proprietary programs.  If your program is a subroutine library, you may
-consider it more useful to permit linking proprietary applications with the
-library.  If this is what you want to do, use the GNU Library General
-Public License instead of this License.
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/Makefile
--- a/head/gnu/lib/libodialog/Makefile	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,24 +0,0 @@
-# Makefile for libdialog
-# $FreeBSD$
-
-.include <bsd.own.mk>
-
-LIB=    odialog
-#MAN=	NOMAN
-
-SHLIB_MAJOR= 7
-SRCS=   kernel.c rc.c checklist.c inputbox.c menubox.c msgbox.c \
-	lineedit.c radiolist.c textbox.c yesno.c prgbox.c raw_popen.c \
-	fselect.c ui_objects.c dir.c notify.c help.c gauge.c tree.c
-
-CFLAGS+= -I${.CURDIR} -Wall -Wstrict-prototypes -DLOCALE
-
-DPADD=	${LIBNCURSES}
-LDADD=	-lncurses
-
-.if ${MK_HTML} != "no"
-FILES=	${EXAMPLES:C;^;${.CURDIR}/TESTS/;}
-FILESDIR= ${SHAREDIR}/examples/libdialog
-.endif
-
-.include <bsd.lib.mk>
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/README
--- a/head/gnu/lib/libodialog/README	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,8 +0,0 @@
-This library was split out from the `dialog' program for use
-in C programs.  For a list of interface functions, see dialog.h.
-For usage examples, see the `dialog' program sources in
-/usr/src/gnu/usr.bin/dialog.
-
-You can additionally use any ncurses functions after init_dialog().
-
-							Ache.
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/TESTS/Makefile
--- a/head/gnu/lib/libodialog/TESTS/Makefile	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,20 +0,0 @@
-# Really quick and evil Makefile for building all the tests.  I wish that
-# bmake was friendlier to the concept of multiple progs/libs in the same
-# directory.
-#
-# $FreeBSD$
-
-PROGS=	msg yesno prgbox gauge dselect fselect text menu1 menu2 menu3 \
-	input1 input2 check1 check2 check3 radio1 radio2 radio3 \
-	ftree1 ftree2 tree
-
-WARNS?=	2
-CFLAGS+= -Wall -Wstrict-prototypes
-LDFLAGS+= -ldialog
-
-all: ${PROGS}
-
-clean:
-	rm -f ${PROGS}
-	
-.include <bsd.prog.mk>
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/TESTS/check1.c
--- a/head/gnu/lib/libodialog/TESTS/check1.c	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,83 +0,0 @@
-/*
- * small test-driver for new dialog functionality
- *
- * Copyright (c) 1995, Jordan Hubbard
- *
- * All rights reserved.
- *
- * This source code may be used, modified, copied, distributed, and
- * sold, in both source and binary form provided that the above
- * copyright and these terms are retained, verbatim, as the first
- * lines of this file.  Under no circumstances is the author
- * responsible for the proper functioning of the software nor does
- * the author assume any responsibility for damages incurred with
- * its use.
- */
-
-#include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-#include <sys/wait.h>
-#include <dialog.h>
-
-/* Hook functions */
-
-static int
-getBool(dialogMenuItem *self)
-{
-    if (self->data && *((int *)self->data))
-	return TRUE;
-    return FALSE;
-}
-
-static int
-setBool(dialogMenuItem *self)
-{
-    if (self->data) {
-	*((int *)self->data) = !*((int *)self->data);
-	return DITEM_SUCCESS;
-    }
-    return DITEM_FAILURE;
-}
-
-static int german_book, italian_book, slang_book;
-
-static int
-clearBooks(dialogMenuItem *self)
-{
-    german_book = italian_book = slang_book = FALSE;
-    return DITEM_SUCCESS | DITEM_REDRAW;
-}
-
-/* menu2 - A more advanced way of using checked and fire hooks to manipulate the backing-variables directly */
-/* prompt	title					checked		fire		sel   data */
-static dialogMenuItem menu2[] = {
-    { "German",	"Buy book on learning German",		getBool,	setBool,	NULL, &german_book},
-    { "Italian",	"Buy book on learning Italian",		getBool,	setBool,	NULL, &italian_book },
-    { "Slang",	"Buy book on commonly used insults",	getBool,	setBool,	NULL, &slang_book },
-    { "Clear",	"Clear book list",			NULL,		clearBooks,	NULL, NULL,	' ', ' ', ' ' },
-};
-
-/* End of hook functions */
-
-/* Kick it off, James! */
-int
-main(int argc, char **argv)
-{
-    int retval;
-    
-    init_dialog();
-    
-    retval = dialog_checklist("this is a dialog_checklist() in action, test #1",
-			      "this checklist menu shows off some of the straight-forward features\n"
-			      "of the new menu system's check & fire dispatch hooks", -1, -1, 4, -4, menu2, NULL);
-    dialog_clear();
-    fprintf(stderr, "returned value for dialog_checklist was %d (%d %d %d)\n", retval, german_book, italian_book, slang_book);
-    
-    end_dialog();
-    return 0;
-}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/TESTS/check2.c
--- a/head/gnu/lib/libodialog/TESTS/check2.c	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,105 +0,0 @@
-/*
- * small test-driver for new dialog functionality
- *
- * Copyright (c) 1995, Jordan Hubbard
- *
- * All rights reserved.
- *
- * This source code may be used, modified, copied, distributed, and
- * sold, in both source and binary form provided that the above
- * copyright and these terms are retained, verbatim, as the first
- * lines of this file.  Under no circumstances is the author
- * responsible for the proper functioning of the software nor does
- * the author assume any responsibility for damages incurred with
- * its use.
- */
-
-#include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-#include <sys/wait.h>
-#include <dialog.h>
-
-/* Hook functions */
-
-static int
-getBool(dialogMenuItem *self)
-{
-    if (self->data && *((int *)self->data))
-	return TRUE;
-    return FALSE;
-}
-
-static int
-setBool(dialogMenuItem *self)
-{
-    if (self->data) {
-	*((int *)self->data) = !*((int *)self->data);
-	return DITEM_SUCCESS;
-    }
-    return DITEM_FAILURE;
-}
-
-static int german_book, italian_book, slang_book;
-
-static int
-clearBooks(dialogMenuItem *self)
-{
-    german_book = italian_book = slang_book = FALSE;
-    return DITEM_SUCCESS | DITEM_REDRAW;
-}
-
-static int
-buyBooks(dialogMenuItem *self)
-{
-    char foo[256];
-    
-    if (german_book || italian_book || slang_book) {
-	strcpy(foo, "Ok, you're buying books on");
-	if (german_book)
-	    strcat(foo, " german");
-	if (italian_book)
-	    strcat(foo, " italian");
-	if (slang_book)
-	    strcat(foo, " slang");
-    }
-    else
-	strcpy(foo, "You're not buying any books?");
-    dialog_mesgbox("This is a direct callback for the `Buy' button", foo, -1, -1);
-    return DITEM_SUCCESS;
-}
-
-/* menu3 - Look mom!  We can finally use our own OK and Cancel buttons! */
-/* prompt	title					checked		fire		sel   data */
-static dialogMenuItem menu3[] = {
-    { "Buy!",	NULL,					NULL,		buyBooks	}, /* New "OK" button */
-    { "No Way!",	NULL,					NULL,		NULL		}, /* New "Cancel" button */
-    { "German",	"Buy books on learning German",		getBool,	setBool,	NULL, &german_book },
-    { "Italian",	"Buy books on learning Italian",	getBool,	setBool,	NULL, &italian_book },
-    { "Slang",	"Buy books on commonly used insults",	getBool,	setBool,	NULL, &slang_book },
-    { "Clear",	"Clear book list",			NULL,		clearBooks,	NULL, NULL, ' ', ' ', ' ' },
-};
-
-/* End of hook functions */
-
-/* Kick it off, James! */
-int
-main(int argc, char **argv)
-{
-    int retval;
-    
-    init_dialog();
-    
-    retval = dialog_checklist("this is dialog_checklist() in action, test #2",
-			      "Same as before, but now we relabel the buttons and override the OK action.",
-			      -1, -1, 4, -4, menu3 + 2, (char *)TRUE);
-    dialog_clear();
-    fprintf(stderr, "returned value for dialog_checklist was %d\n", retval);
-    
-    end_dialog();
-    return 0;
-}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/TESTS/check3.c
--- a/head/gnu/lib/libodialog/TESTS/check3.c	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,92 +0,0 @@
-/*
- * small test-driver for new dialog functionality
- *
- * Copyright (c) 1995, Jordan Hubbard
- *
- * All rights reserved.
- *
- * This source code may be used, modified, copied, distributed, and
- * sold, in both source and binary form provided that the above
- * copyright and these terms are retained, verbatim, as the first
- * lines of this file.  Under no circumstances is the author
- * responsible for the proper functioning of the software nor does
- * the author assume any responsibility for damages incurred with
- * its use.
- *
- */
-
-#include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
-
-#include <sys/wait.h>
-#include <dialog.h>
-
-/* Hook functions */
-
-static int
-getBool(dialogMenuItem *self)
-{
-    if (self->data && *((int *)self->data))
-	return TRUE;
-    return FALSE;
-}
-
-static int
-setBool(dialogMenuItem *self)
-{
-    if (self->data) {
-	*((int *)self->data) = !*((int *)self->data);
-	return DITEM_SUCCESS;
-    }
-    return DITEM_FAILURE;
-}
-
-static int german_book, italian_book, slang_book;
-static int spending;
-
-static int
-check(dialogMenuItem *self)
-{
-    return ((int)(intptr_t)self->data == spending);
-}
-
-static int
-spend(dialogMenuItem *self)
-{
-    spending = (int)(intptr_t)self->data;
-    return DITEM_SUCCESS | DITEM_REDRAW;
-}
-
-/* menu4 - Show off a simulated compound menu (group at top is checklist, group at bottom radio) */
-/* prompt	title					checked		fire	 sel,  data	     lbra mark rbra */
-static dialogMenuItem menu4[] = {
-    { "German",	"Buy books on learning German",		getBool,	setBool, NULL, &german_book },
-    { "Italian","Buy books on learning Italian",	getBool,	setBool, NULL, &italian_book },
-    { "Slang",	"Buy books on commonly used insults",	getBool,	setBool, NULL, &slang_book },
-    { "-----",	"----------------------------------",	NULL,		NULL,	 NULL, NULL,	     ' ', ' ', ' ' },
-    { "1000",	"Spend $1,000",				check,		spend,	 NULL, (void *)1000, '(', '*', ')' },
-    { "500",	"Spend $500",				check,		spend,	 NULL, (void *)500,  '(', '*', ')' },
-    { "100",	"Spend $100",				check,		spend,	 NULL, (void *)100,  '(', '*', ')' },
-};
-
-/* End of hook functions */
-
-/* Kick it off, James! */
-int
-main(int argc, char **argv)
-{
-    int retval;
-    
-    init_dialog();
-    
-    
-    retval = dialog_checklist("this is dialog_checklist() in action, test #3",
-			      "Now we show off some of the button 'styles' one can create.",
-			      -1, -1, 7, -7, menu4, NULL);
-    dialog_clear();
-    fprintf(stderr, "spent $%d on %s%s%s books\n", spending, german_book ? " german" : "",
-	    italian_book ? " italian" : "", slang_book ? " slang" : "");
-    
-    end_dialog();
-    return 0;
-}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/TESTS/dselect.c
--- a/head/gnu/lib/libodialog/TESTS/dselect.c	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,41 +0,0 @@
-/*
- * small test-driver for new dialog functionality
- *
- * Copyright (c) 1995, Jordan Hubbard
- *
- * All rights reserved.
- *
- * This source code may be used, modified, copied, distributed, and
- * sold, in both source and binary form provided that the above
- * copyright and these terms are retained, verbatim, as the first
- * lines of this file.  Under no circumstances is the author
- * responsible for the proper functioning of the software nor does
- * the author assume any responsibility for damages incurred with
- * its use.
- */
-
-#include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-#include <sys/wait.h>
-#include <dialog.h>
-
-/* Kick it off, James! */
-int
-main(int argc, char **argv)
-{
-  int retval;
-
-  init_dialog();
-
-  retval = dialog_dselect(".", "*");
-  dialog_clear();
-  fprintf(stderr, "returned value for dialog_dselect was %d\n", retval);
-
-  end_dialog();
-  return 0;
-}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/TESTS/fselect.c
--- a/head/gnu/lib/libodialog/TESTS/fselect.c	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,44 +0,0 @@
-/*
- * small test-driver for new dialog functionality
- *
- * Copyright (c) 1995, Jordan Hubbard
- *
- * All rights reserved.
- *
- * This source code may be used, modified, copied, distributed, and
- * sold, in both source and binary form provided that the above
- * copyright and these terms are retained, verbatim, as the first
- * lines of this file.  Under no circumstances is the author
- * responsible for the proper functioning of the software nor does
- * the author assume any responsibility for damages incurred with
- * its use.
- */
-
-#include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-#include <sys/wait.h>
-#include <dialog.h>
-
-/* Kick it off, James! */
-int
-main(int argc, char **argv)
-{
-  char *retval;
-
-  init_dialog();
-
-  retval = dialog_fselect(".", "*.[ch]");
-  dialog_clear();
-  if (retval)
-    fprintf(stderr, "returned value for dialog_fselect was %s\n", retval);
-  else
-    fprintf(stderr, "returned value for dialog_fselect was NULL\n");
-
-  end_dialog();
-  return 0;
-}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/TESTS/ftree1.c
--- a/head/gnu/lib/libodialog/TESTS/ftree1.c	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,45 +0,0 @@
-/*
- * ftree1.c
- *
- * small test-driver for new dialog functionality
- *
- * Copyright (c) 1998, Anatoly A. Orehovsky
- *
- * file ./ftree1.test with xterm widget tree from 
- * direct editres(1) dump needed !!!
- */
-
-#include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <dialog.h>
-
-int
-main(int argc, char **argv)
-{
-	int retval;
-	unsigned char *tresult;
-
-	init_dialog();
-	retval = dialog_ftree("ftree1.test", '\t',
-		"ftree dialog box example",
-		"xterm widget tree from direct editres(1) dump", 
-		-1, -1, 15,
-                            &tresult);
-
-	dialog_update();
-	
-	dialog_clear();
-	
-	end_dialog();
-
-	if (!retval)
-	{
- 		puts(tresult);
-  		free(tresult);
-  	}
-  	
-	exit(retval);
-}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/TESTS/ftree1.test
--- a/head/gnu/lib/libodialog/TESTS/ftree1.test	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,73 +0,0 @@
-XTerm  login
-	VendorShellExt  shellext
-	VT100  vt100
-	SimpleMenu  fontMenu
-		SmeBSB  menuLabel
-		SmeBSB  fontdefault
-		SmeBSB  font1
-		SmeBSB  font2
-		SmeBSB  font3
-		SmeBSB  font4
-		SmeBSB  font5
-		SmeBSB  font6
-		SmeBSB  fontescape
-		SmeBSB  fontsel
-	SimpleMenu  mainMenu
-		SmeBSB  menuLabel
-		SmeBSB  securekbd
-		SmeBSB  allowsends
-		SmeBSB  redraw
-		SmeLine  line1
-		SmeBSB  8-bit control
-		SmeBSB  sun function-keys
-		SmeLine  line2
-		SmeBSB  suspend
-		SmeBSB  continue
-		SmeBSB  interrupt
-		SmeBSB  hangup
-		SmeBSB  terminate
-		SmeBSB  kill
-		SmeLine  line3
-		SmeBSB  quit
-	SimpleMenu  vtMenu
-		SmeBSB  menuLabel
-		SmeBSB  scrollbar
-		SmeBSB  jumpscroll
-		SmeBSB  reversevideo
-		SmeBSB  autowrap
-		SmeBSB  reversewrap
-		SmeBSB  autolinefeed
-		SmeBSB  appcursor
-		SmeBSB  appkeypad
-		SmeBSB  scrollkey
-		SmeBSB  scrollttyoutput
-		SmeBSB  allow132
-		SmeBSB  cursesemul
-		SmeBSB  visualbell
-		SmeBSB  marginbell
-		SmeBSB  altscreen
-		SmeLine  line1
-		SmeBSB  softreset
-		SmeBSB  hardreset
-		SmeBSB  clearsavedlines
-		SmeLine  line2
-		SmeBSB  tekshow
-		SmeBSB  tekmode
-		SmeBSB  vthide
-	TopLevelShell  tektronix
-		VendorShellExt  shellext
-		Tek4014  tek4014
-	SimpleMenu  tekMenu
-		SmeBSB  menuLabel
-		SmeBSB  tektextlarge
-		SmeBSB  tektext2
-		SmeBSB  tektext3
-		SmeBSB  tektextsmall
-		SmeLine  line1
-		SmeBSB  tekpage
-		SmeBSB  tekreset
-		SmeBSB  tekcopy
-		SmeLine  line2
-		SmeBSB  vtshow
-		SmeBSB  vtmode
-		SmeBSB  tekhide
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/TESTS/ftree2.c
--- a/head/gnu/lib/libodialog/TESTS/ftree2.c	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,47 +0,0 @@
-/*
- * ftree2.c
- *
- * small test-driver for new dialog functionality
- *
- * Copyright (c) 1998, Anatoly A. Orehovsky
- *
- * file ./ftree2.test with xterm widget tree from 
- * preprocess editres(1) dump needed !!!
- */
-
-#include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <dialog.h>
-
-int
-main(int argc, char **argv)
-{
-	int retval;
-	unsigned char *tresult;
-
-	init_dialog();
-	use_helpfile("ftree2.test");
-	use_helpline("Press Arrows, Tab, Enter or F1");
-	retval = dialog_ftree("ftree2.test", '\t',
-		"ftree dialog box example",
-		"xterm widget tree from preprocess editres(1) dump", 
-		-1, -1, 15,
-                            &tresult);
-
-	dialog_update();
-	
-	dialog_clear();
-	
-	end_dialog();
-
-	if (!retval)
-	{
- 		puts(tresult);
-  		free(tresult);
-  	}
-  	
-	exit(retval);
-}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/TESTS/ftree2.test
--- a/head/gnu/lib/libodialog/TESTS/ftree2.test	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,73 +0,0 @@
-XTerm  login
-XTerm  login	VendorShellExt  shellext
-XTerm  login	VT100  vt100
-XTerm  login	SimpleMenu  fontMenu
-XTerm  login	SimpleMenu  fontMenu	SmeBSB  menuLabel
-XTerm  login	SimpleMenu  fontMenu	SmeBSB  fontdefault
-XTerm  login	SimpleMenu  fontMenu	SmeBSB  font1
-XTerm  login	SimpleMenu  fontMenu	SmeBSB  font2
-XTerm  login	SimpleMenu  fontMenu	SmeBSB  font3
-XTerm  login	SimpleMenu  fontMenu	SmeBSB  font4
-XTerm  login	SimpleMenu  fontMenu	SmeBSB  font5
-XTerm  login	SimpleMenu  fontMenu	SmeBSB  font6
-XTerm  login	SimpleMenu  fontMenu	SmeBSB  fontescape
-XTerm  login	SimpleMenu  fontMenu	SmeBSB  fontsel
-XTerm  login	SimpleMenu  mainMenu
-XTerm  login	SimpleMenu  mainMenu	SmeBSB  menuLabel
-XTerm  login	SimpleMenu  mainMenu	SmeBSB  securekbd
-XTerm  login	SimpleMenu  mainMenu	SmeBSB  allowsends
-XTerm  login	SimpleMenu  mainMenu	SmeBSB  redraw
-XTerm  login	SimpleMenu  mainMenu	SmeLine  line1
-XTerm  login	SimpleMenu  mainMenu	SmeBSB  8-bit control
-XTerm  login	SimpleMenu  mainMenu	SmeBSB  sun function-keys
-XTerm  login	SimpleMenu  mainMenu	SmeLine  line2
-XTerm  login	SimpleMenu  mainMenu	SmeBSB  suspend
-XTerm  login	SimpleMenu  mainMenu	SmeBSB  continue
-XTerm  login	SimpleMenu  mainMenu	SmeBSB  interrupt
-XTerm  login	SimpleMenu  mainMenu	SmeBSB  hangup
-XTerm  login	SimpleMenu  mainMenu	SmeBSB  terminate
-XTerm  login	SimpleMenu  mainMenu	SmeBSB  kill
-XTerm  login	SimpleMenu  mainMenu	SmeLine  line3
-XTerm  login	SimpleMenu  mainMenu	SmeBSB  quit
-XTerm  login	SimpleMenu  vtMenu
-XTerm  login	SimpleMenu  vtMenu	SmeBSB  menuLabel
-XTerm  login	SimpleMenu  vtMenu	SmeBSB  scrollbar
-XTerm  login	SimpleMenu  vtMenu	SmeBSB  jumpscroll
-XTerm  login	SimpleMenu  vtMenu	SmeBSB  reversevideo
-XTerm  login	SimpleMenu  vtMenu	SmeBSB  autowrap
-XTerm  login	SimpleMenu  vtMenu	SmeBSB  reversewrap
-XTerm  login	SimpleMenu  vtMenu	SmeBSB  autolinefeed
-XTerm  login	SimpleMenu  vtMenu	SmeBSB  appcursor
-XTerm  login	SimpleMenu  vtMenu	SmeBSB  appkeypad
-XTerm  login	SimpleMenu  vtMenu	SmeBSB  scrollkey
-XTerm  login	SimpleMenu  vtMenu	SmeBSB  scrollttyoutput
-XTerm  login	SimpleMenu  vtMenu	SmeBSB  allow132
-XTerm  login	SimpleMenu  vtMenu	SmeBSB  cursesemul
-XTerm  login	SimpleMenu  vtMenu	SmeBSB  visualbell
-XTerm  login	SimpleMenu  vtMenu	SmeBSB  marginbell
-XTerm  login	SimpleMenu  vtMenu	SmeBSB  altscreen
-XTerm  login	SimpleMenu  vtMenu	SmeLine  line1
-XTerm  login	SimpleMenu  vtMenu	SmeBSB  softreset
-XTerm  login	SimpleMenu  vtMenu	SmeBSB  hardreset
-XTerm  login	SimpleMenu  vtMenu	SmeBSB  clearsavedlines
-XTerm  login	SimpleMenu  vtMenu	SmeLine  line2
-XTerm  login	SimpleMenu  vtMenu	SmeBSB  tekshow
-XTerm  login	SimpleMenu  vtMenu	SmeBSB  tekmode
-XTerm  login	SimpleMenu  vtMenu	SmeBSB  vthide
-XTerm  login	TopLevelShell  tektronix
-XTerm  login	TopLevelShell  tektronix	VendorShellExt  shellext
-XTerm  login	TopLevelShell  tektronix	Tek4014  tek4014
-XTerm  login	SimpleMenu  tekMenu
-XTerm  login	SimpleMenu  tekMenu	SmeBSB  menuLabel
-XTerm  login	SimpleMenu  tekMenu	SmeBSB  tektextlarge
-XTerm  login	SimpleMenu  tekMenu	SmeBSB  tektext2
-XTerm  login	SimpleMenu  tekMenu	SmeBSB  tektext3
-XTerm  login	SimpleMenu  tekMenu	SmeBSB  tektextsmall
-XTerm  login	SimpleMenu  tekMenu	SmeLine  line1
-XTerm  login	SimpleMenu  tekMenu	SmeBSB  tekpage
-XTerm  login	SimpleMenu  tekMenu	SmeBSB  tekreset
-XTerm  login	SimpleMenu  tekMenu	SmeBSB  tekcopy
-XTerm  login	SimpleMenu  tekMenu	SmeLine  line2
-XTerm  login	SimpleMenu  tekMenu	SmeBSB  vtshow
-XTerm  login	SimpleMenu  tekMenu	SmeBSB  vtmode
-XTerm  login	SimpleMenu  tekMenu	SmeBSB  tekhide
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/TESTS/gauge.c
--- a/head/gnu/lib/libodialog/TESTS/gauge.c	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,41 +0,0 @@
-/*
- * small test-driver for new dialog functionality
- *
- * Copyright (c) 1995, Jordan Hubbard
- *
- * All rights reserved.
- *
- * This source code may be used, modified, copied, distributed, and
- * sold, in both source and binary form provided that the above
- * copyright and these terms are retained, verbatim, as the first
- * lines of this file.  Under no circumstances is the author
- * responsible for the proper functioning of the software nor does
- * the author assume any responsibility for damages incurred with
- * its use.
- */
-
-#include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-#include <sys/wait.h>
-#include <dialog.h>
-
-/* Kick it off, James! */
-int
-main(int argc, char **argv)
-{
-  int i;
-
-  init_dialog();
-
-  for (i = 0; i <= 100; i++) {
-    dialog_gauge("Gas tank", "When this gets 100% full, you'd better yank out the nozzle!", 10, 1, 7, 70, i);
-    usleep(30000);
-  }
-  end_dialog();
-  return 0;
-}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/TESTS/input1.c
--- a/head/gnu/lib/libodialog/TESTS/input1.c	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,45 +0,0 @@
-/*
- * small test-driver for new dialog functionality
- *
- * Copyright (c) 1995, Jordan Hubbard
- *
- * All rights reserved.
- *
- * This source code may be used, modified, copied, distributed, and
- * sold, in both source and binary form provided that the above
- * copyright and these terms are retained, verbatim, as the first
- * lines of this file.  Under no circumstances is the author
- * responsible for the proper functioning of the software nor does
- * the author assume any responsibility for damages incurred with
- * its use.
- */
-
-#include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-#include <sys/wait.h>
-#include <dialog.h>
-
-/* Kick it off, James! */
-int
-main(int argc, char **argv)
-{
-  int retval;
-  unsigned char result[128];
-
-  init_dialog();
-
-  strcpy(result, "not this!");
-  retval = dialog_inputbox("this is dialog_inputbox() in action, test #1",
-		       "Enter something really profound below, please.",
-		       -1, -1, result);
-  dialog_clear();
-  fprintf(stderr, "returned value for dialog_inputbox was %d (%s)\n", retval, result);
-
-  end_dialog();
-  return 0;
-}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/TESTS/input2.c
--- a/head/gnu/lib/libodialog/TESTS/input2.c	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,47 +0,0 @@
-/*
- * small test-driver for new dialog functionality
- *
- * Copyright (c) 1995, Jordan Hubbard
- *
- * All rights reserved.
- *
- * This source code may be used, modified, copied, distributed, and
- * sold, in both source and binary form provided that the above
- * copyright and these terms are retained, verbatim, as the first
- * lines of this file.  Under no circumstances is the author
- * responsible for the proper functioning of the software nor does
- * the author assume any responsibility for damages incurred with
- * its use.
- */
-
-#include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-#include <sys/wait.h>
-#include <dialog.h>
-
-/* Kick it off, James! */
-int
-main(int argc, char **argv)
-{
-  int retval;
-  unsigned char result[128];
-
-  init_dialog();
-
-  result[0]='\0';
-  DialogInputAttrs |= DITEM_NO_ECHO;
-  retval = dialog_inputbox("this is dialog_inputbox() in action, test #2 (no echo)",
-		       "Enter something really secret below, please.",
-		       -1, -1, result);
-  DialogInputAttrs &= DITEM_NO_ECHO;
-  dialog_clear();
-  fprintf(stderr, "returned value for dialog_inputbox was %d (%s)\n", retval, result);
-
-  end_dialog();
-  return 0;
-}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/TESTS/menu1.c
--- a/head/gnu/lib/libodialog/TESTS/menu1.c	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,96 +0,0 @@
-/*
- * small test-driver for new dialog functionality
- *
- * Copyright (c) 1995, Jordan Hubbard
- *
- * All rights reserved.
- *
- * This source code may be used, modified, copied, distributed, and
- * sold, in both source and binary form provided that the above
- * copyright and these terms are retained, verbatim, as the first
- * lines of this file.  Under no circumstances is the author
- * responsible for the proper functioning of the software nor does
- * the author assume any responsibility for damages incurred with
- * its use.
- */
-
-#include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-#include <sys/wait.h>
-#include <dialog.h>
-
-/* Start of hook functions */
-static enum { nowhere, berlin, rome, ny } where;
-
-static int
-_menu1_berlin_action(dialogMenuItem *self)
-{
-    if (where == berlin) {
-	dialog_mesgbox("excuse me?", "But you're already *in* Berlin!", -1, -1);
-    }
-    else {
-	where = berlin;
-	dialog_mesgbox("whoosh!", "Welcome to Berlin!  Have a beer!", -1, -1);
-    }
-    return DITEM_SUCCESS | DITEM_RESTORE | DITEM_CONTINUE;
-}
-
-static int
-_menu1_rome_action(dialogMenuItem *self)
-{
-    if (where == rome) {
-	dialog_mesgbox("The wine must be getting to you..", "You're already in Rome!", -1, -1);
-    }
-    else {
-	where = rome;
-	dialog_mesgbox("whoosh!", "Welcome to Rome!  Have a coffee!", -1, -1);
-    }
-    return DITEM_SUCCESS | DITEM_RESTORE | DITEM_CONTINUE;
-}
-
-static int
-_menu1_ny_action(dialogMenuItem *self)
-{
-    if (where == ny) {
-	dialog_mesgbox("Say what?", "You're already there!", -1, -1);
-    }
-    else {
-	where = ny;
-	dialog_mesgbox("whoosh!", "Welcome to New York!  Now go someplace else!", -1, -1);
-    }
-    return DITEM_SUCCESS | DITEM_RESTORE | DITEM_CONTINUE;
-}
-
-/* menu1 - show off the "fire" action hook */
-/* prompt	title					checked		fire */
-static dialogMenuItem menu1[] = {
-    { "Berlin",	"Go visit Germany's new capitol",	NULL,	_menu1_berlin_action	},
-    { "Rome",	"Go visit the Roman ruins",		NULL,	_menu1_rome_action	},
-    { "New York",	"Go visit the streets of New York",	NULL,	_menu1_ny_action	},
-};
-
-/* End of hook functions */
-
-/* Kick it off, James! */
-int
-main(int argc, char **argv)
-{
-    int retval;
-    
-    init_dialog();
-    
-    retval = dialog_menu("this is dialog_menu() in action, test #1",
-			 "this simple menu shows off some of the straight-forward features\n"
-			 "of the new menu system's action dispatch hooks.  Select Cancel to leave",
-			 -1, -1, 3, -3, menu1, NULL, NULL, NULL);
-    dialog_clear();
-    fprintf(stderr, "returned value for dialog_menu was %d\n", retval);
-    
-    end_dialog();
-    return 0;
-}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/TESTS/menu2.c
--- a/head/gnu/lib/libodialog/TESTS/menu2.c	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,96 +0,0 @@
-/*
- * small test-driver for new dialog functionality
- *
- * Copyright (c) 1995, Jordan Hubbard
- *
- * All rights reserved.
- *
- * This source code may be used, modified, copied, distributed, and
- * sold, in both source and binary form provided that the above
- * copyright and these terms are retained, verbatim, as the first
- * lines of this file.  Under no circumstances is the author
- * responsible for the proper functioning of the software nor does
- * the author assume any responsibility for damages incurred with
- * its use.
- */
-
-#include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-#include <sys/wait.h>
-#include <dialog.h>
-
-/* Start of hook functions */
-static enum { nowhere, berlin, rome, ny } where;
-
-static int
-_menu1_berlin_action(dialogMenuItem *self)
-{
-    if (where == berlin)
-	dialog_mesgbox("excuse me?", "But you're already *in* Berlin!", -1, -1);
-    else {
-	where = berlin;
-	dialog_mesgbox("whoosh!", "Welcome to Berlin!  Have a beer!", -1, -1);
-    }
-    return DITEM_SUCCESS | DITEM_RESTORE | DITEM_CONTINUE;
-}
-
-static int
-_menu1_rome_action(dialogMenuItem *self)
-{
-    if (where == rome)
-	dialog_mesgbox("The wine must be getting to you..", "You're already in Rome!", -1, -1);
-    else {
-	where = rome;
-	dialog_mesgbox("whoosh!", "Welcome to Rome!  Have a coffee!", -1, -1);
-    }
-    return DITEM_SUCCESS | DITEM_RESTORE | DITEM_CONTINUE;
-}
-
-static int
-_menu1_ny_action(dialogMenuItem *self)
-{
-    if (where == ny)
-	dialog_mesgbox("Say what?", "You're already there!", -1, -1);
-    else {
-	where = ny;
-	dialog_mesgbox("whoosh!", "Welcome to New York!  Now go someplace else!", -1, -1);
-    }
-    return DITEM_SUCCESS | DITEM_RESTORE | DITEM_CONTINUE;
-}
-
-/* menu1 - show off the "fire" action hook */
-/* prompt	title					checked		fire */
-static dialogMenuItem menu1[] = {
-    { "Berlin",	"Go visit Germany's new capitol",	NULL,	_menu1_berlin_action	},
-    { "Rome",	"Go visit the Roman ruins",		NULL,	_menu1_rome_action	},
-    { "New York",	"Go visit the streets of New York",	NULL,	_menu1_ny_action	},
-};
-
-/* End of hook functions */
-
-/* Kick it off, James! */
-int
-main(int argc, char **argv)
-{
-    int retval;
-    
-    init_dialog();
-    
-    use_helpfile("menu2.c");
-    use_helpline("Type F1 to view the source for this demo");
-    retval = dialog_menu("this is dialog_menu() in action, test #2",
-			 "this simple menu shows off some of the straight-forward features\n"
-			 "of the new menu system's action dispatch hooks as well as a helpline\n"
-			 "and a helpfile.  Select Cancel to leave",
-			 -1, -1, 3, -3, menu1, NULL, NULL, NULL);
-    dialog_clear();
-    fprintf(stderr, "returned value for dialog_menu was %d\n", retval);
-    
-    end_dialog();
-    return 0;
-}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/TESTS/menu3.c
--- a/head/gnu/lib/libodialog/TESTS/menu3.c	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,107 +0,0 @@
-/*
- * small test-driver for new dialog functionality
- *
- * Copyright (c) 1995, Jordan Hubbard
- *
- * All rights reserved.
- *
- * This source code may be used, modified, copied, distributed, and
- * sold, in both source and binary form provided that the above
- * copyright and these terms are retained, verbatim, as the first
- * lines of this file.  Under no circumstances is the author
- * responsible for the proper functioning of the software nor does
- * the author assume any responsibility for damages incurred with
- * its use.
- */
-
-#include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-#include <sys/wait.h>
-#include <dialog.h>
-
-/* Hook functions */
-
-static int
-stop(dialogMenuItem *self)
-{
-    dialog_mesgbox("!", "I'm no idiot!", -1, -1);
-    return DITEM_SUCCESS;
-}
-
-static int
-maybe(dialogMenuItem *self)
-{
-    dialog_mesgbox("!", "I said don't rush me!  I'm THINKING!", -1, -1);
-    return DITEM_SUCCESS | DITEM_RESTORE | DITEM_CONTINUE;
-}
-
-/* Dummy menu just to show of the ability */
-static char *insurance[] = {
-    "1,000,000",	"Mondo insurance policy", "Off",
-    "5,000,000",	"Mega insurance policy", "Off",
-    "10,000,000",	"Friend!  Most Favored customer!", "On"
-};
-
-static void
-preinsure(dialogMenuItem *self, int is_selected)
-{
-    if (is_selected) {
-	static WINDOW *w;
-	
-	/* This has to be here first if you want to see selection traverse properly in the invoking menu */
-	refresh();
-
-	w = dupwin(newscr);
-	DialogX = 1;
-	DialogY = 13;
-	dialog_radiolist("How much insurance would you like to take out?",
-			 "If you're really going to do this, we recommend some insurance\n"
-			 "first!  What kind of life insurance policy would you like?",
-			 -1, -1, 3, 3, insurance, NULL);
-	touchwin(w);
-	wrefresh(w);
-	delwin(w);
-    }
-}
-
-/*
- * Show a simple menu that puts up a sub menu when a certain item is traversed to
- */
-
-/* prompt	title						checked		fire		sel  */
-static dialogMenuItem doit[] = {
-    { "Rah!" },
-    { "No way!" },
-    { "Stop",	"No, I'm not going to do that!",		NULL,		stop,		NULL	},
-    { "Maybe",	"I'm still thinking about it, don't rush me!",	NULL,		maybe,		NULL,	},
-    { "Go",	"Yes!  Yes!  I want to do it!",			NULL,		NULL, 		preinsure },
-};
-
-/* End of hook functions */
-
-/* Kick it off, James! */
-int
-main(int argc, char **argv)
-{
-    int retval;
-    
-    init_dialog();
-    
-    
-    DialogX = 5;
-    DialogY = 1;
-    retval = dialog_menu("Do you have the GUTS?",
-			 "C'mon, macho man!  Do you have what it takes to do something REALLY\n"
-			 "dangerous and stupid?  WHAT ARE YOU WAITING FOR?!",
-			 -1, -1, 3, -3, doit + 2, (char *)TRUE, NULL, NULL);
-    dialog_clear();
-    fprintf(stderr, "returned value for dialog_menu was %d\n", retval);
-    
-    end_dialog();
-    return 0;
-}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/TESTS/msg.c
--- a/head/gnu/lib/libodialog/TESTS/msg.c	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,42 +0,0 @@
-/*
- * small test-driver for new dialog functionality
- *
- * Copyright (c) 1995, Jordan Hubbard
- *
- * All rights reserved.
- *
- * This source code may be used, modified, copied, distributed, and
- * sold, in both source and binary form provided that the above
- * copyright and these terms are retained, verbatim, as the first
- * lines of this file.  Under no circumstances is the author
- * responsible for the proper functioning of the software nor does
- * the author assume any responsibility for damages incurred with
- * its use.
- */
-
-#include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-#include <sys/wait.h>
-#include <dialog.h>
-
-/* Kick it off, James! */
-int
-main(int argc, char **argv)
-{
-  int retval;
-
-  init_dialog();
-
-  retval = dialog_msgbox("This is dialog_msgbox() in action with pause on", "Hi there.  Please press return now.",
-			 -1, -1, 1);
-  dialog_clear();
-  fprintf(stderr, "returned value for dialog_msgbox was %d\n", retval);
-
-  end_dialog();
-  return 0;
-}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/TESTS/prgbox.c
--- a/head/gnu/lib/libodialog/TESTS/prgbox.c	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,41 +0,0 @@
-/*
- * small test-driver for new dialog functionality
- *
- * Copyright (c) 1995, Jordan Hubbard
- *
- * All rights reserved.
- *
- * This source code may be used, modified, copied, distributed, and
- * sold, in both source and binary form provided that the above
- * copyright and these terms are retained, verbatim, as the first
- * lines of this file.  Under no circumstances is the author
- * responsible for the proper functioning of the software nor does
- * the author assume any responsibility for damages incurred with
- * its use.
- */
-
-#include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-#include <sys/wait.h>
-#include <dialog.h>
-
-/* Kick it off, James! */
-int
-main(int argc, char **argv)
-{
-  int retval;
-
-  init_dialog();
-
-  retval = dialog_prgbox("This is dialog_prgbox() in action with cal(1)", "cal", 14, 50, TRUE, TRUE);
-  dialog_clear();
-  fprintf(stderr, "returned value for dialog_prgbox was %d\n", retval);
-
-  end_dialog();
-  return 0;
-}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/TESTS/radio1.c
--- a/head/gnu/lib/libodialog/TESTS/radio1.c	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,71 +0,0 @@
-/*
- * small test-driver for new dialog functionality
- *
- * Copyright (c) 1995, Jordan Hubbard
- *
- * All rights reserved.
- *
- * This source code may be used, modified, copied, distributed, and
- * sold, in both source and binary form provided that the above
- * copyright and these terms are retained, verbatim, as the first
- * lines of this file.  Under no circumstances is the author
- * responsible for the proper functioning of the software nor does
- * the author assume any responsibility for damages incurred with
- * its use.
- */
-
-#include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-#include <sys/wait.h>
-#include <dialog.h>
-
-/* Hook functions */
-
-static int spending;
-
-static int
-check(dialogMenuItem *self)
-{
-    return ((int)(intptr_t)self->data == spending);
-}
-
-static int
-spend(dialogMenuItem *self)
-{
-    spending = (int)(intptr_t)self->data;
-    return DITEM_SUCCESS | DITEM_REDRAW;
-}
-
-/* menu5 - Show a simple radiolist menu that inherits the radio appearance by default */
-/* prompt	title			checked		fire		sel   data */
-static dialogMenuItem menu5[] = {
-    { "1000",	"Spend $1,000",		check,		spend,		NULL, (void *)1000 },
-    { "500",	"Spend $500",		check,		spend,		NULL, (void *)500 },
-    { "100",	"Spend $100",		check,		spend, 		NULL, (void *)100 },
-};
-
-/* End of hook functions */
-
-/* Kick it off, James! */
-int
-main(int argc, char **argv)
-{
-    int retval;
-    
-    init_dialog();
-    
-    
-    retval = dialog_radiolist("this is dialog_radiolist() in action, test #1",
-			      "this radio menu shows off some of the straight-forward features\n"
-			      "of the new menu system's check & fire dispatch hooks", -1, -1, 3, -3, menu5, NULL);
-    dialog_clear();
-    fprintf(stderr, "returned value for dialog_radiolist was %d (money set to %d)\n", retval, spending);
-    
-    end_dialog();
-    return 0;
-}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/TESTS/radio2.c
--- a/head/gnu/lib/libodialog/TESTS/radio2.c	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,89 +0,0 @@
-/*
- * small test-driver for new dialog functionality
- *
- * Copyright (c) 1995, Jordan Hubbard
- *
- * All rights reserved.
- *
- * This source code may be used, modified, copied, distributed, and
- * sold, in both source and binary form provided that the above
- * copyright and these terms are retained, verbatim, as the first
- * lines of this file.  Under no circumstances is the author
- * responsible for the proper functioning of the software nor does
- * the author assume any responsibility for damages incurred with
- * its use.
- */
-
-#include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-#include <sys/wait.h>
-#include <dialog.h>
-
-/* Hook functions */
-
-static char bachelor[10], bachelette[10];
-
-static int
-getBachelor(dialogMenuItem *self)
-{
-    return !strcmp(bachelor, self->prompt);
-}
-
-static int
-setBachelor(dialogMenuItem *self)
-{
-    strcpy(bachelor, self->prompt);
-    return DITEM_SUCCESS | DITEM_REDRAW;
-}
-
-static int
-getBachelette(dialogMenuItem *self)
-{
-    return !strcmp(bachelette, self->prompt);
-}
-
-static int
-setBachelette(dialogMenuItem *self)
-{
-    strcpy(bachelette, self->prompt);
-    return DITEM_SUCCESS | DITEM_REDRAW;
-}
-
-/* menu6- More complex radiolist menu that creates two groups in a single menu */
-/* prompt	title								checked		fire */
-static dialogMenuItem menu6[] = {
-    { "Tom",	"Tom's a dynamic shoe salesman from Tulsa, OK!",		getBachelor,	setBachelor },
-    { "Dick",	"Dick's a retired engine inspector from McDonnell-Douglas!",	getBachelor,	setBachelor },
-    { "Harry",	"Harry's a professional female impersonator from Las Vegas!",	getBachelor,	setBachelor },
-    { "-----",	"----------------------------------",		NULL, NULL, NULL, NULL, ' ', ' ', ' ' },
-    { "Jane",	"Jane's a twice-divorced housewife from Moose, Oregon!",	getBachelette,	setBachelette },
-    { "Sally",	"Sally's a shy Human Resources Manager for IBM!",		getBachelette,	setBachelette },
-    { "Mary",	"Mary's an energetic serial killer on the lam!",		getBachelette,	setBachelette },
-};
-
-/* End of hook functions */
-
-/* Kick it off, James! */
-int
-main(int argc, char **argv)
-{
-    int retval;
-    
-    init_dialog();
-    
-    retval = dialog_radiolist("this is dialog_radiolist() in action, test #2",
-			      "Welcome to \"The Love Blender!\" - America's favorite game show\n"
-			      "where YOU, the contestant, get to choose which of these two\n"
-			      "fine specimens of humanity will go home together, whether they\n"
-			      "like it or not!", -1, -1, 7, -7, menu6, NULL);
-    dialog_clear();
-    fprintf(stderr, "I'm sure that %s and %s will be very happy together!\n", bachelor, bachelette);
-    
-    end_dialog();
-    return 0;
-}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/TESTS/radio3.c
--- a/head/gnu/lib/libodialog/TESTS/radio3.c	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,98 +0,0 @@
-/*
- * small test-driver for new dialog functionality
- *
- * Copyright (c) 1995, Jordan Hubbard
- *
- * All rights reserved.
- *
- * This source code may be used, modified, copied, distributed, and
- * sold, in both source and binary form provided that the above
- * copyright and these terms are retained, verbatim, as the first
- * lines of this file.  Under no circumstances is the author
- * responsible for the proper functioning of the software nor does
- * the author assume any responsibility for damages incurred with
- * its use.
- */
-
-#include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-#include <sys/wait.h>
-#include <dialog.h>
-
-/* Hook functions */
-
-static int spending;
-
-static int
-check(dialogMenuItem *self)
-{
-    return ((int)(intptr_t)self->data == spending);
-}
-
-static int
-spend(dialogMenuItem *self)
-{
-    spending = (int)(intptr_t)self->data;
-    return DITEM_SUCCESS | DITEM_REDRAW;
-}
-
-static void
-ask(dialogMenuItem *self, int is_selected)
-{
-    if (is_selected) {
-	char *str;
-	
-	if (!strcmp(self->prompt, "1000"))
-	    str = "You'd better ask both your parents first! ";
-	else if (!strcmp(self->prompt, "500"))
-	    str = "You'd better at least ask your Dad!       ";
-	else
-	    str = "Yes, being frugal is probably a good idea!";
-	DialogX = 15;
-	DialogY = 17;
-	dialog_msgbox("Free Advice", str, -1, -1, 0);
-    }
-}
-
-/*
- * menu5 - Show a simple radiolist menu that inherits the radio appearance by default and appears at
- * a different location, leaving room for a msg box below it.  This shows off the DialogX/DialogY extensions.
- */
-
-/* prompt	title			checked		fire		sel	data */
-static dialogMenuItem menu5[] = {
-    { "1000",	"Spend $1,000",		check,		spend,		ask,	(void *)1000 },
-    { "500",	"Spend $500",		check,		spend,		ask,	(void *)500 },
-    { "100",	"Spend $100",		check,		spend, 		ask,	(void *)100 },
-};
-
-/* End of hook functions */
-
-/* Kick it off, James! */
-int
-main(int argc, char **argv)
-{
-    int retval;
-    
-    init_dialog();
-    
-    
-    DialogX = 5;
-    DialogY = 1;
-    retval = dialog_radiolist("this is dialog_radiolist() in action, test #3",
-			      "This radio menu shows off the ability to put dialog menus and other\n"
-			      "controls at different locations, as well as the `selected' hook which\n"
-			      "lets you follow the traversal of the selection bar as well as what's\n"
-			      "selected.",
-			      -1, -1, 3, -3, menu5, NULL);
-    dialog_clear();
-    fprintf(stderr, "returned value for dialog_radiolist was %d (money set to %d)\n", retval, spending);
-    
-    end_dialog();
-    return 0;
-}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/TESTS/text.c
--- a/head/gnu/lib/libodialog/TESTS/text.c	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,41 +0,0 @@
-/*
- * small test-driver for new dialog functionality
- *
- * Copyright (c) 1995, Jordan Hubbard
- *
- * All rights reserved.
- *
- * This source code may be used, modified, copied, distributed, and
- * sold, in both source and binary form provided that the above
- * copyright and these terms are retained, verbatim, as the first
- * lines of this file.  Under no circumstances is the author
- * responsible for the proper functioning of the software nor does
- * the author assume any responsibility for damages incurred with
- * its use.
- */
-
-#include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-#include <sys/wait.h>
-#include <dialog.h>
-
-/* Kick it off, James! */
-int
-main(int argc, char **argv)
-{
-  int retval;
-
-  init_dialog();
-
-  retval = dialog_textbox("This is dialog_textbox() in action with /etc/passwd", "/etc/passwd", 10, 60);
-  dialog_clear();
-  fprintf(stderr, "returned value for dialog_textbox was %d\n", retval);
-
-  end_dialog();
-  return 0;
-}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/TESTS/tree.c
--- a/head/gnu/lib/libodialog/TESTS/tree.c	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,111 +0,0 @@
-/*
- * tree.c
- *
- * small test-driver for new dialog functionality
- *
- * Copyright (c) 1998, Anatoly A. Orehovsky
- */
-
-#include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <dialog.h>
-
-unsigned char *names[] = {
-	"/",
-	"/dev",
-	"/dev/fd",
-	"/tmp",
-	"/usr",
-	"/var",
-	"/home",
-	"/stand",
-	"/stand/etc",
-	"/stand/en_US.ISO8859-1",
-	"/stand/info",
-	"/stand/info/bin",
-	"/stand/info/des",
-	"/stand/info/games",
-	"/stand/info/manpages",
-	"/stand/info/proflibs",
-	"/stand/info/dict",
-	"/stand/info/info",
-	"/stand/info/src",
-	"/etc",
-	"/etc/gnats",
-	"/etc/kerberosIV",
-	"/etc/mtree",
-	"/etc/namedb",
-	"/etc/ppp",
-	"/etc/uucp",
-	"/etc/sliphome",
-	"/proc",
-	"/lkm",
-	"/mnt",
-	"/root",
-	"/sbin",
-	"/bin",
-	0
-};
-
-unsigned char *names1[] = {
-	"a",
-	"a:b",
-	"a:b:c",
-	"a:d"
-};
-
-int
-main(int argc, char **argv)
-{
-	int retval;
-	unsigned char *tresult;
-	char comstr[BUFSIZ];
-
-	init_dialog();
-	do {
-		use_helpline("Press OK for listing directory");
-		retval = dialog_tree(names, 
-			sizeof(names)/sizeof(unsigned char *) - 1,
-			 '/',
-			"tree dialog box example",
-			"Typical find -x / -type d output", 
-			-1, -1, 15,
-                        	    &tresult);
-		
-		if (retval)
-			break;
-		
-		use_helpline(NULL);
-		(void)snprintf(comstr, sizeof(comstr), 
-			"ls -CF %s", tresult);
-
-		retval = dialog_prgbox(
-			comstr, 
-			comstr, 20, 60, TRUE, TRUE);
-
-		dialog_clear();
-  		
-		retval = dialog_tree(names1, 
-			sizeof(names1)/sizeof(unsigned char *),
-			 ':',
-			"tree dialog box example",
-			"Other tree", 
-			-1, -1, 5,
-                        	    &tresult);
-		if (!retval)
-		{
-	  		dialog_clear();
-  		}
-	} while (!retval);
-
-	dialog_update();
-	
-	dialog_clear();
-	
-	end_dialog();
-  	
-	exit(retval);
-}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/TESTS/yesno.c
--- a/head/gnu/lib/libodialog/TESTS/yesno.c	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,45 +0,0 @@
-/*
- * small test-driver for new dialog functionality
- *
- * Copyright (c) 1995, Jordan Hubbard
- *
- * All rights reserved.
- *
- * This source code may be used, modified, copied, distributed, and
- * sold, in both source and binary form provided that the above
- * copyright and these terms are retained, verbatim, as the first
- * lines of this file.  Under no circumstances is the author
- * responsible for the proper functioning of the software nor does
- * the author assume any responsibility for damages incurred with
- * its use.
- */
-
-#include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-#include <sys/wait.h>
-#include <dialog.h>
-
-/* Kick it off, James! */
-int
-main(int argc, char **argv)
-{
-  int rval1, rval2;
-
-  init_dialog();
-
-  rval1 = dialog_yesno("This is dialog_yesno() in action",
-		       "Have you stopped deliberately putting bugs into your code?", -1, -1);
-  dialog_clear();
-  rval2 = dialog_noyes("This is dialog_noyes() in action",
-		       "Have you stopped beating your wife?", -1, -1);
-  dialog_clear();
-  end_dialog();
-  fprintf(stderr, "returned value for dialog_yesno was %d\n", rval1);
-  fprintf(stderr, "returned value for dialog_noyes was %d\n", rval2);
-  return 0;
-}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/TODO
--- a/head/gnu/lib/libodialog/TODO	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,36 +0,0 @@
-- cut off names in the listbox that are to long
-done 27Jan95
-	The current behaviour may not be desirable. When browsing through
-	long names these, when highlighted, will be shown with the first
-	characters cut off, when not highlighted the last characters will
-	be cut off.
-
-- look at behaviour of TAB key when browsing through directories.
-done 28Jan95
-
-- make sure the full name of the directory is written to the 
-  "Directory:"-box
-done 28Jan95
-
-- mark current selections in listbox when initializing the listobject
-Idontknow
-- test and use Notify() when checking for error conditions
-ok
-- test overall
-- adapt color of buttons when changing focus to the button.
-done 28Jan95
-- add shade to dialog_fselect()-window
-done 29Jan95
-- add (nn%) indication to lists.
-done 30Jan95
-- add use_helpfile()
-done 13Feb95
-- add use_helpline()
-
-NOTE: apparently there is a bug (or a strange interaction between pkg_manage
-and dialog_textbox) in dialog_textbox. When I use this routine to display 
-the helpfile in display_helpfile() the program gets mysterious segmentation
-faults and bus errors.
-I now use dialog_mesgbox, after I have read the file into a buffer.
-
-
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/checklist.c
--- a/head/gnu/lib/libodialog/checklist.c	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,661 +0,0 @@
-/*
- *  checklist.c -- implements the checklist box
- *
- *  AUTHOR: Savio Lam (lam836 at cs.cuhk.hk)
- *
- *	Substantial rennovation:  12/18/95, Jordan K. Hubbard
- *
- *  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., 675 Mass Ave, Cambridge, MA 02139, USA.
- *
- */
-
-#include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
-
-#include <dialog.h>
-#include "dialog.priv.h"
-
-
-static void print_item(WINDOW *win, unsigned char *tag, unsigned char *item, int status, int choice, int selected, dialogMenuItem *me, int list_width, int item_x, int check_x);
-
-#define DREF(di, item)		((di) ? &((di)[(item)]) : NULL)
-
-/*
- * Display a dialog box with a list of options that can be turned on or off
- */
-int
-dialog_checklist(unsigned char *title, unsigned char *prompt, int height, int width,
-		 int list_height, int cnt, void *it, unsigned char *result)
-{
-    int i, j, x, y, cur_x, cur_y, old_x, old_y, box_x, box_y, key = 0, button,
-	choice, l, k, scroll, max_choice, item_no = 0, *status;
-    int redraw_menu = FALSE, cursor_reset = FALSE;
-    int rval = 0, onlist = 1, ok_space, cancel_space;
-    char okButton, cancelButton;
-    WINDOW *dialog, *list;
-    unsigned char **items = NULL;
-    dialogMenuItem *ditems;
-    int list_width, check_x, item_x;
-
-    /* Allocate space for storing item on/off status */
-    if ((status = alloca(sizeof(int) * abs(cnt))) == NULL) {
-	endwin();
-	fprintf(stderr, "\nCan't allocate memory in dialog_checklist().\n");
-	exit(-1);
-    }
-    
-draw:
-    choice = scroll = button = 0;
-    /* Previous calling syntax, e.g. just a list of strings? */
-    if (cnt >= 0) {
-	items = it;
-	ditems = NULL;
-	item_no = cnt;
-	/* Initializes status */
-	for (i = 0; i < item_no; i++)
-	    status[i] = !strcasecmp(items[i*3 + 2], "on");
-    }
-    /* It's the new specification format - fake the rest of the code out */
-    else {
-	item_no = abs(cnt);
-	ditems = it;
-	if (!items)
-	    items = (unsigned char **)alloca((item_no * 3) * sizeof(unsigned char *));
-	
-	/* Initializes status */
-	for (i = 0; i < item_no; i++) {
-	    status[i] = ditems[i].checked ? ditems[i].checked(&ditems[i]) : FALSE;
-	    items[i*3] = ditems[i].prompt;
-	    items[i*3 + 1] = ditems[i].title;
-	    items[i*3 + 2] = status[i] ? "on" : "off";
-	}
-    }
-    max_choice = MIN(list_height, item_no);
-    
-    check_x = 0;
-    item_x = 0;
-    /* Find length of longest item in order to center checklist */
-    for (i = 0; i < item_no; i++) {
-	l = strlen(items[i*3]);
-	for (j = 0; j < item_no; j++) {
-	    k = strlen(items[j*3 + 1]);
-	    check_x = MAX(check_x, l + k + 6);
-	}
-	item_x = MAX(item_x, l);
-    }
-    if (height < 0)
-	height = strheight(prompt)+list_height+4+2;
-    if (width < 0) {
-	i = strwidth(prompt);
-	j = ((title != NULL) ? strwidth(title) : 0);
-	width = MAX(i,j);
-	width = MAX(width,check_x+4)+4;
-    }
-    width = MAX(width,24);
-    
-    if (width > COLS)
-	width = COLS;
-    if (height > LINES)
-	height = LINES;
-    /* center dialog box on screen */
-    x = (COLS - width)/2;
-    y = (LINES - height)/2;
-
-#ifdef HAVE_NCURSES
-    if (use_shadow)
-	draw_shadow(stdscr, y, x, height, width);
-#endif
-    dialog = newwin(height, width, y, x);
-    if (dialog == NULL) {
-	endwin();
-	fprintf(stderr, "\nnewwin(%d,%d,%d,%d) failed, maybe wrong dims\n", height,width, y, x);
-	return -1;
-    }
-    keypad(dialog, TRUE);
-    
-    draw_box(dialog, 0, 0, height, width, dialog_attr, border_attr);
-    wattrset(dialog, border_attr);
-    wmove(dialog, height-3, 0);
-    waddch(dialog, ACS_LTEE);
-    for (i = 0; i < width-2; i++)
-	waddch(dialog, ACS_HLINE);
-    wattrset(dialog, dialog_attr);
-    waddch(dialog, ACS_RTEE);
-    wmove(dialog, height-2, 1);
-    for (i = 0; i < width-2; i++)
-	waddch(dialog, ' ');
-    
-    if (title != NULL) {
-	wattrset(dialog, title_attr);
-	wmove(dialog, 0, (width - strlen(title))/2 - 1);
-	waddch(dialog, ' ');
-	waddstr(dialog, title);
-	waddch(dialog, ' ');
-    }
-    wattrset(dialog, dialog_attr);
-    wmove(dialog, 1, 2);
-    print_autowrap(dialog, prompt, height - 1, width - 2, width, 1, 2, TRUE, FALSE);
-    
-    list_width = width - 6;
-    getyx(dialog, cur_y, cur_x);
-    box_y = cur_y + 1;
-    box_x = (width - list_width) / 2 - 1;
-    
-    /* create new window for the list */
-    list = subwin(dialog, list_height, list_width, y + box_y + 1, x + box_x + 1);
-    if (list == NULL) {
-	delwin(dialog);
-	endwin();
-	fprintf(stderr, "\nsubwin(dialog,%d,%d,%d,%d) failed, maybe wrong dims\n", list_height, list_width,
-		y + box_y + 1, x + box_x + 1);
-	return -1;
-    }
-    keypad(list, TRUE);
-    
-    /* draw a box around the list items */
-    draw_box(dialog, box_y, box_x, list_height + 2, list_width + 2, menubox_border_attr, menubox_attr);
-    
-    check_x = (list_width - check_x) / 2;
-    item_x = check_x + item_x + 6;
-    
-    /* Print the list */
-    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);
-    wnoutrefresh(list);
-    print_arrows(dialog, scroll, list_height, item_no, box_x, box_y, check_x + 4, cur_x, cur_y);
-    
-    display_helpline(dialog, height - 1, width);
-    
-    x = width / 2 - 11;
-    y = height - 2;
-    /* Is this a fancy new style argument string where we get to override
-     * the buttons, or an old style one where they're fixed?
-     */
-    if (ditems && result) {
-	cancelButton = toupper(ditems[CANCEL_BUTTON].prompt[0]);
-	print_button(dialog, ditems[CANCEL_BUTTON].prompt, y, x + strlen(ditems[OK_BUTTON].prompt) + 5, ditems[CANCEL_BUTTON].checked ? ditems[CANCEL_BUTTON].checked(&ditems[CANCEL_BUTTON]) : FALSE);
-	okButton = toupper(ditems[OK_BUTTON].prompt[0]);
-	print_button(dialog, ditems[OK_BUTTON].prompt, y, x, ditems[OK_BUTTON].checked ? ditems[OK_BUTTON].checked(&ditems[OK_BUTTON]) : TRUE);
-    }
-    else {
-	cancelButton = 'C';
-	print_button(dialog, "Cancel", y, x + 14, FALSE);
-	okButton = 'O';
-	print_button(dialog, "  OK  ", y, x, TRUE);
-    }
-    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);
-	
-	/* Shortcut to OK? */
-	if (toupper(key) == okButton) {
-	    if (ditems) {
-		if (result && ditems[OK_BUTTON].fire) {
-		    int st;
-		    WINDOW *save;
-
-		    save = dupwin(newscr);
-		    st = ditems[OK_BUTTON].fire(&ditems[OK_BUTTON]);
-		    if (st & DITEM_RESTORE) {
-			touchwin(save);
-			wrefresh(save);
-		    }
-		    delwin(save);
-		}
-	    }
-	    else if (result) {
-		*result = '\0';
-		for (i = 0; i < item_no; i++) {
-		    if (status[i]) {
-			strcat(result, items[i*3]);
-			strcat(result, "\n");
-		    }
-		}
-	    }
-	    rval = 0;
-	    key = ESC;	/* Lemme out! */
-	    break;
-	}
-
-	/* Shortcut to cancel? */
-	if (toupper(key) == cancelButton) {
-	    if (ditems && result && ditems[CANCEL_BUTTON].fire) {
-		int st;
-		WINDOW *save;
-
-		save = dupwin(newscr);
-		st = ditems[CANCEL_BUTTON].fire(&ditems[CANCEL_BUTTON]);
-		if (st & DITEM_RESTORE) {
-		    touchwin(save);
-		    wrefresh(save);
-		    wmove(dialog, cur_y, cur_x);
-		}
-		delwin(save);
-	    }
-	    rval = 1;
-	    key = ESC;	/* I gotta go! */
-	    break;
-	}
-	
-	/* Check if key pressed matches first character of any item tag in list */
-	for (i = 0; i < max_choice; i++)
-	    if (key != ' ' && key < 0x100 && toupper(key) == toupper(items[(scroll+i)*3][0]))
-		break;
-
-	if (i < max_choice || (key >= '1' && key <= MIN('9', '0'+max_choice)) ||
-	    KEY_IS_UP(key) || KEY_IS_DOWN(key) || ((key == ' ' || key == '\n' ||
-	    key == '\r') && onlist)) {
-
-	    /* if moving from buttons to the list, reset and redraw buttons */
-	    if (!onlist) {
-		onlist = 1;
-		button = 0;
-
-	        if (ditems && result) {
-		    print_button(dialog, ditems[CANCEL_BUTTON].prompt, y, x + strlen(ditems[OK_BUTTON].prompt) + 5, ditems[CANCEL_BUTTON].checked ? ditems[CANCEL_BUTTON].checked(&ditems[CANCEL_BUTTON]) : button);
-		    print_button(dialog, ditems[OK_BUTTON].prompt, y, x, ditems[OK_BUTTON].checked ? ditems[OK_BUTTON].checked(&ditems[OK_BUTTON]) : !button);
-		}
-		else {
-		    print_button(dialog, "Cancel", y, x + 14, button);
-		    print_button(dialog, "  OK  ", y, x, !button);
-		}
-		wmove(list, choice, check_x+1);
-		wnoutrefresh(dialog);
-		wrefresh(list);
-	    }
-
-	    if (key >= '1' && key <= MIN('9', '0'+max_choice))
-		i = key - '1';
-	    
-	    else if (KEY_IS_UP(key)) {
-		if (!choice) {
-		    if (scroll) {
-			/* Scroll list down */
-			getyx(dialog, cur_y, cur_x);    /* Save cursor position */
-			if (list_height > 1) {
-			    /* De-highlight current first item before scrolling down */
-			    print_item(list, items[scroll * 3], items[scroll * 3 + 1], status[scroll], 0,
-				       FALSE, DREF(ditems, scroll), list_width, item_x, check_x);
-			    scrollok(list, TRUE);
-			    wscrl(list, -1);
-			    scrollok(list, FALSE);
-			}
-			scroll--;
-			print_item(list, items[scroll*3], items[scroll*3 + 1], status[scroll], 0,
-				   TRUE, DREF(ditems, scroll), 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);
-		    }
-		    continue;    /* wait for another key press */
-		}
-		else
-		    i = choice - 1;
-	    }
-	    else if (KEY_IS_DOWN(key)) {
-		if (choice == max_choice - 1) {
-		    if (scroll + choice < item_no - 1) {
-			/* Scroll list up */
-			getyx(dialog, cur_y, cur_x);    /* Save cursor position */
-			if (list_height > 1) {
-			    /* De-highlight current last item before scrolling up */
-			    print_item(list, items[(scroll + max_choice - 1) * 3],
-				       items[(scroll + max_choice - 1) * 3 + 1],
-				       status[scroll + max_choice - 1], max_choice - 1,
-				       FALSE, DREF(ditems, scroll + max_choice - 1), list_width, item_x, check_x);
-			    scrollok(list, TRUE);
-			    scroll(list);
-			    scrollok(list, FALSE);
-			}
-			scroll++;
-			print_item(list, items[(scroll + max_choice - 1) * 3],
-				   items[(scroll + max_choice - 1) * 3 + 1],
-				   status[scroll + max_choice - 1], max_choice - 1, TRUE,
-				   DREF(ditems, scroll + max_choice - 1), 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);
-		    }
-		    continue;    /* wait for another key press */
-		}
-		else
-		    i = choice + 1;
-	    }
-	    else if ((key == ' ' || key == '\n' || key == '\r') && onlist) {    /* Toggle item status */
-		char lbra = 0, rbra = 0, mark = 0;
-
-		getyx(list, old_y, old_x);    /* Save cursor position */
-		
-		if (ditems) {
-		    if (ditems[scroll + choice].fire) {
-			int st;
-			WINDOW *save;
-
-			save = dupwin(newscr);
-			st = ditems[scroll + choice].fire(&ditems[scroll + choice]);	/* Call "fire" action */
-			if (st & DITEM_RESTORE) {
-			    touchwin(save);
-			    wrefresh(save);
-			}
-			delwin(save);
-			if (st & DITEM_REDRAW) {
-			    wclear(list);
-			    for (i = 0; i < item_no; i++)
-				status[i] = ditems[i].checked ? ditems[i].checked(&ditems[i]) : FALSE;
-			    for (i = 0; i < max_choice; i++) {
-				print_item(list, items[(scroll + i) * 3], items[(scroll + i) * 3 + 1],
-					   status[scroll + i], i, i == choice, DREF(ditems, scroll + i), list_width, item_x, check_x);
-			    }
-			    wnoutrefresh(list);
-			    print_arrows(dialog, scroll, list_height, item_no, box_x, box_y, check_x + 4,
-					 cur_x, cur_y);
-			    wrefresh(dialog);
-			}
-			if (st & DITEM_LEAVE_MENU) {
-			    /* Allow a fire action to take us out of the menu */
-			    key = ESC;
-			    rval = 0;
-			    break;
-			}
-			else if (st & DITEM_RECREATE) {
-			    delwin(list);
-			    delwin(dialog);
-			    dialog_clear();
-			    goto draw;
-			}
-		    }
-		    status[scroll + choice] = ditems[scroll + choice].checked ?
-			ditems[scroll + choice].checked(&ditems[scroll + choice]) : FALSE;
-		    lbra = ditems[scroll + choice].lbra;
-		    rbra = ditems[scroll + choice].rbra;
-		    mark = ditems[scroll + choice].mark;
-		}
-		else
-		    status[scroll + choice] = !status[scroll + choice];
-		wmove(list, choice, check_x);
-		wattrset(list, check_selected_attr);
-		if (!lbra)
-		    lbra = '[';
-		if (!rbra)
-		    rbra = ']';
-		if (!mark)
-		    mark = 'X';
-		wprintw(list, "%c%c%c", lbra, status[scroll + choice] ? mark : ' ', rbra);
-		wmove(list, old_y, old_x);  /* Restore cursor to previous position */
-		wrefresh(list);
-		continue;    /* wait for another key press */
-	    }
-	    
-	    if (i != choice) {
-		/* De-highlight current item */
-		getyx(dialog, cur_y, cur_x);    /* Save cursor position */
-		print_item(list, items[(scroll + choice) * 3], items[(scroll + choice) * 3 + 1],
-			   status[scroll + choice], choice, FALSE, DREF(ditems, scroll + choice), list_width, item_x, check_x);
-		
-		/* Highlight new item */
-		choice = i;
-		print_item(list, items[(scroll + choice) * 3], items[(scroll + choice) * 3 + 1], status[scroll + choice], choice, TRUE, DREF(ditems, scroll + choice), list_width, item_x, check_x);
-		wmove(list, choice, check_x+1);	  /* Restore cursor to previous position */
-		wrefresh(list);
-	    }
-	    continue;    /* wait for another key press */
-	}
-	
-	switch (key) {
-	case KEY_PPAGE:	/* can we go up? */
-	    if (scroll > height - 4)
-		scroll -= (height-4);
-	    else
-		scroll = 0;
-	    redraw_menu = TRUE;
-	    if (!onlist) {
-		onlist = 1;
-		button = 0;
-	    }
-	    break;
-	    
-	case KEY_NPAGE:      /* can we go down a full page? */
-	    if (scroll + list_height >= item_no-1 - list_height) {
-		scroll = item_no - list_height;
-		if (scroll < 0)
-		    scroll = 0;
-	    }
-	    else
-		scroll += list_height;
-	    redraw_menu = TRUE;
-	    if (!onlist) {
- 		onlist = 1;
-		button = 0;
-	    }
-	    break;
-	    
-	case KEY_HOME:      /* go to the top */
-	    scroll = 0;
-	    choice = 0;
-	    redraw_menu = TRUE;
-	    cursor_reset = TRUE;
-	    onlist = 1;
-	    break;
-	    
-	case KEY_END:      /* Go to the bottom */
-	    scroll = item_no - list_height;
-	    if (scroll < 0)
-		scroll = 0;
-	    choice = max_choice - 1;
-	    redraw_menu = TRUE;
-	    cursor_reset = TRUE;
-	    onlist = 1;
-	    break;
-	    
-	case TAB:
-	case KEY_BTAB:
-	    /* move to next component */
-	    if (onlist) {       /* on list, next is ok button */
-		onlist = 0;
-		if (ditems && result) {
-		    print_button(dialog, ditems[CANCEL_BUTTON].prompt, y, x + strlen(ditems[OK_BUTTON].prompt) + 5, ditems[CANCEL_BUTTON].checked ? ditems[CANCEL_BUTTON].checked(&ditems[CANCEL_BUTTON]) : button);
-		    print_button(dialog, ditems[OK_BUTTON].prompt, y, x, ditems[OK_BUTTON].checked ? ditems[OK_BUTTON].checked(&ditems[OK_BUTTON]) : !button);
-		    ok_space = 1;
-		    cancel_space = strlen(ditems[OK_BUTTON].prompt) + 6;
-		}
-		else {
-		    print_button(dialog, "Cancel", y, x + 14, button);
-		    print_button(dialog, "  OK  ", y, x, !button);
-		    ok_space = 3;
-		    cancel_space = 15;
-		}
-		if (button)
-		    wmove(dialog, y, x + cancel_space);
-		else
-		    wmove(dialog, y, x + ok_space);
-		wrefresh(dialog);
-		break;
-	    }
-	    else if (button) {     /* on cancel button, next is list */
-		button = 0;
-		onlist = 1;
-		redraw_menu = TRUE;
-		break; 
-	    }
-	    /* on ok button, next is cancel button, same as left/right case */
-
-	case KEY_LEFT:
-	case KEY_RIGHT:
-	    onlist = 0;
-	    button = !button;
-	    if (ditems && result) {
-		print_button(dialog, ditems[CANCEL_BUTTON].prompt, y, x + strlen(ditems[OK_BUTTON].prompt) + 5, ditems[CANCEL_BUTTON].checked ? ditems[CANCEL_BUTTON].checked(&ditems[CANCEL_BUTTON]) : button);
-		print_button(dialog, ditems[OK_BUTTON].prompt, y, x, ditems[OK_BUTTON].checked ?  ditems[OK_BUTTON].checked(&ditems[OK_BUTTON]) : !button);
-		ok_space = 1;
-		cancel_space = strlen(ditems[OK_BUTTON].prompt) + 6;
-	    }
-	    else {
-		print_button(dialog, "Cancel", y, x + 14, button);
-		print_button(dialog, "  OK  ", y, x, !button);
-		ok_space = 3;
-		cancel_space = 15;
-	    }
-	    if (button)
-		wmove(dialog, y, x + cancel_space);
-	    else
-		wmove(dialog, y, x + ok_space);
-	    wrefresh(dialog);
-	    break;
-
-	case ' ':
-	case '\n':
-	case '\r':
-	    if (!onlist) {
-		if (ditems) {
-		    if (result && ditems[button ? CANCEL_BUTTON : OK_BUTTON].fire) {
-			int st;
-			WINDOW *save = dupwin(newscr);
-
-			st = ditems[button ? CANCEL_BUTTON : OK_BUTTON].fire(&ditems[button ? CANCEL_BUTTON : OK_BUTTON]);
-			if (st & DITEM_RESTORE) {
-			    touchwin(save);
-			    wrefresh(save);
-			}
-			delwin(save);
-			if (st == DITEM_FAILURE)
-			continue;
-		    }
-		}
-		else if (result) {
-		    *result = '\0';
-		    for (i = 0; i < item_no; i++) {
-			if (status[i]) {
-			    strcat(result, items[i*3]);
-			    strcat(result, "\n");
-			}
-		    }
-		}
-		rval = button;
-		key = ESC;	/* Bail out! */
-		break;
-	    }
-	    
-	    /* Let me outta here! */
-	case ESC:
-	    rval = -1;
-	    break;
-	    
-	    /* Help! */
-	case KEY_F(1):
-	case '?':
-	    display_helpfile();
-	    break;
-	}
-	
-	if (redraw_menu) {
-	    getyx(list, old_y, old_x);
-	    wclear(list);
-
-    	    /*
-	     * Re-draw a box around the list items.  It is required
-	     * if amount of list items is smaller than height of listbox.
-	     * Otherwise un-redrawn field will be filled with default
-	     * screen attributes instead of dialog attributes.
-	     */
-	    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[(scroll + i) * 3], items[(scroll + i) * 3 + 1], status[scroll + i], i, i == choice, DREF(ditems, scroll + 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);
-
-	    /* redraw buttons to fix highlighting */
-	    if (ditems && result) {
-		print_button(dialog, ditems[CANCEL_BUTTON].prompt, y, x + strlen(ditems[OK_BUTTON].prompt) + 5, ditems[CANCEL_BUTTON].checked ? ditems[CANCEL_BUTTON].checked(&ditems[CANCEL_BUTTON]) : button);
-		print_button(dialog, ditems[OK_BUTTON].prompt, y, x, ditems[OK_BUTTON].checked ? ditems[OK_BUTTON].checked(&ditems[OK_BUTTON]) : !button);
-	    }
-	    else {
-		print_button(dialog, "Cancel", y, x + 14, button);
-		print_button(dialog, "  OK  ", y, x, !button);
-	    }
-	    wnoutrefresh(dialog);
-	    if (cursor_reset) {
-		wmove(list, choice, check_x+1);
-		cursor_reset = FALSE;
-	    }
-	    else {
-		wmove(list, old_y, old_x);
-	    }
-	    wrefresh(list);
-	    redraw_menu = FALSE;
-	}
-    }
-    delwin(list);
-    delwin(dialog);
-    return rval;
-}
-
-
-/*
- * Print list item
- */
-static void
-print_item(WINDOW *win, unsigned char *tag, unsigned char *item, int status, int choice, int selected, dialogMenuItem *me, int list_width, int item_x, int check_x)
-{
-    int i;
-    
-    /* Clear 'residue' of last item */
-    wattrset(win, menubox_attr);
-    wmove(win, choice, 0);
-    for (i = 0; i < list_width; i++)
-	waddch(win, ' ');
-    wmove(win, choice, check_x);
-    wattrset(win, selected ? check_selected_attr : check_attr);
-    wprintw(win, "%c%c%c",  me && me->lbra ? me->lbra : '[',
-	    status ? me && me->mark ? me->mark : 'X' : ' ',
-	    me && me->rbra ? me->rbra : ']');
-    wattrset(win, menubox_attr);
-    waddch(win, ' ');
-    wattrset(win, selected ? tag_key_selected_attr : tag_key_attr);
-    waddch(win, tag[0]);
-    wattrset(win, selected ? tag_selected_attr : tag_attr);
-    waddstr(win, tag + 1);
-    wmove(win, choice, item_x);
-    wattrset(win, selected ? item_selected_attr : item_attr);
-    waddstr(win, item);
-    /* If have a selection handler for this, call it */
-    if (me && me->selected) {
-	wrefresh(win);
-	me->selected(me, selected);
-    }
-}
-/* End of print_item() */
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/colors.h
--- a/head/gnu/lib/libodialog/colors.h	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,219 +0,0 @@
-/*
- *  colors.h -- color attribute definitions
- *
- *  AUTHOR: Savio Lam (lam836 at cs.cuhk.hk)
- *
- *  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., 675 Mass Ave, Cambridge, MA 02139, USA.
- */
-
-
-/*
- *   Default color definitions
- *
- *   *_FG = foreground
- *   *_BG = background
- *   *_HL = highlight?
- */
-#define SCREEN_FG                    COLOR_CYAN
-#define SCREEN_BG                    COLOR_BLUE
-#define SCREEN_HL                    TRUE
-
-#define SHADOW_FG                    COLOR_BLACK
-#define SHADOW_BG                    COLOR_BLACK
-#define SHADOW_HL                    TRUE
-
-#define DIALOG_FG                    COLOR_BLACK
-#define DIALOG_BG                    COLOR_WHITE
-#define DIALOG_HL                    FALSE
-
-#define TITLE_FG                     COLOR_YELLOW
-#define TITLE_BG                     COLOR_WHITE
-#define TITLE_HL                     TRUE
-
-#define BORDER_FG                    COLOR_WHITE
-#define BORDER_BG                    COLOR_WHITE
-#define BORDER_HL                    TRUE
-
-#define BUTTON_ACTIVE_FG             COLOR_WHITE
-#define BUTTON_ACTIVE_BG             COLOR_BLUE
-#define BUTTON_ACTIVE_HL             TRUE
-
-#define BUTTON_INACTIVE_FG           COLOR_BLACK
-#define BUTTON_INACTIVE_BG           COLOR_WHITE
-#define BUTTON_INACTIVE_HL           FALSE
-
-#define BUTTON_KEY_ACTIVE_FG         COLOR_WHITE
-#define BUTTON_KEY_ACTIVE_BG         COLOR_BLUE
-#define BUTTON_KEY_ACTIVE_HL         TRUE
-
-#define BUTTON_KEY_INACTIVE_FG       COLOR_RED
-#define BUTTON_KEY_INACTIVE_BG       COLOR_WHITE
-#define BUTTON_KEY_INACTIVE_HL       FALSE
-
-#define BUTTON_LABEL_ACTIVE_FG       COLOR_YELLOW
-#define BUTTON_LABEL_ACTIVE_BG       COLOR_BLUE
-#define BUTTON_LABEL_ACTIVE_HL       TRUE
-
-#define BUTTON_LABEL_INACTIVE_FG     COLOR_BLACK
-#define BUTTON_LABEL_INACTIVE_BG     COLOR_WHITE
-#define BUTTON_LABEL_INACTIVE_HL     TRUE
-
-#define INPUTBOX_FG                  COLOR_BLACK
-#define INPUTBOX_BG                  COLOR_WHITE
-#define INPUTBOX_HL                  FALSE
-
-#define INPUTBOX_BORDER_FG           COLOR_BLACK
-#define INPUTBOX_BORDER_BG           COLOR_WHITE
-#define INPUTBOX_BORDER_HL           FALSE
-
-#define SEARCHBOX_FG                 COLOR_BLACK
-#define SEARCHBOX_BG                 COLOR_WHITE
-#define SEARCHBOX_HL                 FALSE
-
-#define SEARCHBOX_TITLE_FG           COLOR_YELLOW
-#define SEARCHBOX_TITLE_BG           COLOR_WHITE
-#define SEARCHBOX_TITLE_HL           TRUE
-
-#define SEARCHBOX_BORDER_FG          COLOR_WHITE
-#define SEARCHBOX_BORDER_BG          COLOR_WHITE
-#define SEARCHBOX_BORDER_HL          TRUE
-
-#define POSITION_INDICATOR_FG        COLOR_YELLOW
-#define POSITION_INDICATOR_BG        COLOR_WHITE
-#define POSITION_INDICATOR_HL        TRUE
-
-#define MENUBOX_FG                   COLOR_BLACK
-#define MENUBOX_BG                   COLOR_WHITE
-#define MENUBOX_HL                   FALSE
-
-#define MENUBOX_BORDER_FG            COLOR_WHITE
-#define MENUBOX_BORDER_BG            COLOR_WHITE
-#define MENUBOX_BORDER_HL            TRUE
-
-#define ITEM_FG                      COLOR_BLACK
-#define ITEM_BG                      COLOR_WHITE
-#define ITEM_HL                      FALSE
-
-#define ITEM_SELECTED_FG             COLOR_WHITE
-#define ITEM_SELECTED_BG             COLOR_BLUE
-#define ITEM_SELECTED_HL             TRUE
-
-#define TAG_FG                       COLOR_YELLOW
-#define TAG_BG                       COLOR_WHITE
-#define TAG_HL                       TRUE
-
-#define TAG_SELECTED_FG              COLOR_YELLOW
-#define TAG_SELECTED_BG              COLOR_BLUE
-#define TAG_SELECTED_HL              TRUE
-
-#define TAG_KEY_FG                   COLOR_RED
-#define TAG_KEY_BG                   COLOR_WHITE
-#define TAG_KEY_HL                   TRUE
-
-#define TAG_KEY_SELECTED_FG          COLOR_RED
-#define TAG_KEY_SELECTED_BG          COLOR_BLUE
-#define TAG_KEY_SELECTED_HL          TRUE
-
-#define CHECK_FG                     COLOR_BLACK
-#define CHECK_BG                     COLOR_WHITE
-#define CHECK_HL                     FALSE
-
-#define CHECK_SELECTED_FG            COLOR_WHITE
-#define CHECK_SELECTED_BG            COLOR_BLUE
-#define CHECK_SELECTED_HL            TRUE
-
-#define UARROW_FG                    COLOR_GREEN
-#define UARROW_BG                    COLOR_WHITE
-#define UARROW_HL                    TRUE
-
-#define DARROW_FG                    COLOR_GREEN
-#define DARROW_BG                    COLOR_WHITE
-#define DARROW_HL                    TRUE
-
-/* End of default color definitions */
-
-#define C_ATTR(x,y)                  ((x ? A_BOLD : 0) | COLOR_PAIR((y)))
-#define COLOR_NAME_LEN               10
-#define COLOR_COUNT                  8
-
-
-/*
- * Global variables
- */
-
-typedef struct {
-  unsigned char name[COLOR_NAME_LEN];
-  int  value;
-} color_names_st;
-
-
-#ifdef __DIALOG_MAIN__
-
-/*
- * For matching color names with color values
- */
-color_names_st color_names[] = {
-  {"BLACK",   COLOR_BLACK},
-  {"RED",     COLOR_RED},
-  {"GREEN",   COLOR_GREEN},
-  {"YELLOW",  COLOR_YELLOW},
-  {"BLUE",    COLOR_BLUE},
-  {"MAGENTA", COLOR_MAGENTA},
-  {"CYAN",    COLOR_CYAN},
-  {"WHITE",   COLOR_WHITE},
-};    /* color names */
-
-
-/*
- * Table of color values
- */
-int color_table[][3] = {
-  {SCREEN_FG,               SCREEN_BG,               SCREEN_HL               },
-  {SHADOW_FG,               SHADOW_BG,               SHADOW_HL               },
-  {DIALOG_FG,               DIALOG_BG,               DIALOG_HL               },
-  {TITLE_FG,                TITLE_BG,                TITLE_HL                },
-  {BORDER_FG,               BORDER_BG,               BORDER_HL               },
-  {BUTTON_ACTIVE_FG,        BUTTON_ACTIVE_BG,        BUTTON_ACTIVE_HL        },
-  {BUTTON_INACTIVE_FG,      BUTTON_INACTIVE_BG,      BUTTON_INACTIVE_HL      },
-  {BUTTON_KEY_ACTIVE_FG,    BUTTON_KEY_ACTIVE_BG,    BUTTON_KEY_ACTIVE_HL    },
-  {BUTTON_KEY_INACTIVE_FG,  BUTTON_KEY_INACTIVE_BG,  BUTTON_KEY_INACTIVE_HL  },
-  {BUTTON_LABEL_ACTIVE_FG,  BUTTON_LABEL_ACTIVE_BG,  BUTTON_LABEL_ACTIVE_HL  },
-  {BUTTON_LABEL_INACTIVE_FG,BUTTON_LABEL_INACTIVE_BG,BUTTON_LABEL_INACTIVE_HL},
-  {INPUTBOX_FG,             INPUTBOX_BG,             INPUTBOX_HL             },
-  {INPUTBOX_BORDER_FG,      INPUTBOX_BORDER_BG,      INPUTBOX_BORDER_HL      },
-  {SEARCHBOX_FG,            SEARCHBOX_BG,            SEARCHBOX_HL            },
-  {SEARCHBOX_TITLE_FG,      SEARCHBOX_TITLE_BG,      SEARCHBOX_TITLE_HL      },
-  {SEARCHBOX_BORDER_FG,     SEARCHBOX_BORDER_BG,     SEARCHBOX_BORDER_HL     },
-  {POSITION_INDICATOR_FG,   POSITION_INDICATOR_BG,   POSITION_INDICATOR_HL   },
-  {MENUBOX_FG,              MENUBOX_BG,              MENUBOX_HL              },
-  {MENUBOX_BORDER_FG,       MENUBOX_BORDER_BG,       MENUBOX_BORDER_HL       },
-  {ITEM_FG,                 ITEM_BG,                 ITEM_HL                 },
-  {ITEM_SELECTED_FG,        ITEM_SELECTED_BG,        ITEM_SELECTED_HL        },
-  {TAG_FG,                  TAG_BG,                  TAG_HL                  },
-  {TAG_SELECTED_FG,         TAG_SELECTED_BG,         TAG_SELECTED_HL         },
-  {TAG_KEY_FG,              TAG_KEY_BG,              TAG_KEY_HL              },
-  {TAG_KEY_SELECTED_FG,     TAG_KEY_SELECTED_BG,     TAG_KEY_SELECTED_HL     },
-  {CHECK_FG,                CHECK_BG,                CHECK_HL                },
-  {CHECK_SELECTED_FG,       CHECK_SELECTED_BG,       CHECK_SELECTED_HL       },
-  {UARROW_FG,               UARROW_BG,               UARROW_HL               },
-  {DARROW_FG,               DARROW_BG,               DARROW_HL               },
-};    /* color_table */
-
-#else
-
-extern color_names_st color_names[];
-extern int color_table[][3];
-
-#endif    /* __DIALOG_MAIN__ */
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/dialog.3
--- a/head/gnu/lib/libodialog/dialog.3	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,842 +0,0 @@
-.\"
-.\" Copyright (c) 1995, Jordan Hubbard
-.\"
-.\" All rights reserved.
-.\"
-.\" This manual page may be used, modified, copied, distributed, and
-.\" sold, in both source and binary form provided that the above
-.\" copyright and these terms are retained, verbatim, as the first
-.\" lines of this file.  Under no circumstances is the author
-.\" responsible for the proper functioning of the software described herein
-.\" nor does the author assume any responsibility for damages incurred with
-.\" its use.
-.\"
-.\" $FreeBSD$
-.\"
-.Dd January 1, 2000
-.Dt DIALOG 3
-.Os
-.Sh NAME
-.Nm draw_shadow ,
-.Nm draw_box ,
-.Nm line_edit ,
-.Nm strheight ,
-.Nm strwidth ,
-.Nm dialog_create_rc ,
-.Nm dialog_yesno ,
-.Nm dialog_noyes ,
-.Nm dialog_prgbox ,
-.Nm dialog_msgbox ,
-.Nm dialog_textbox ,
-.Nm dialog_menu ,
-.Nm dialog_checklist ,
-.Nm dialog_radiolist ,
-.Nm dialog_inputbox ,
-.Nm dialog_clear_norefresh ,
-.Nm dialog_clear ,
-.Nm dialog_update ,
-.Nm dialog_fselect ,
-.Nm dialog_notify ,
-.Nm dialog_mesgbox ,
-.Nm dialog_gauge ,
-.Nm init_dialog ,
-.Nm end_dialog ,
-.Nm use_helpfile ,
-.Nm use_helpline ,
-.Nm get_helpline ,
-.Nm restore_helpline ,
-.Nm dialog_ftree ,
-.Nm dialog_tree
-.Nd provide a simple ncurses-based GUI interface
-.Sh SYNOPSIS
-.In dialog.h
-.Ft "void"
-.Fn draw_shadow "WINDOW *win" "int y" "int x" "int height" "int width"
-.Ft "void"
-.Fn draw_box "WINDOW *win" "int y" "int x" "int height" "int width" "chtype box" "chtype border"
-.Ft "int"
-.Fo line_edit
-.Fa "WINDOW *dialog"
-.Fa "int box_y"
-.Fa "int box_x"
-.Fa "int flen"
-.Fa "int box_width"
-.Fa "chtype attr"
-.Fa "int first"
-.Fa "unsigned char *result"
-.Fa "int attr_mask"
-.Fc
-.Ft "int"
-.Fn strheight "const char *p"
-.Ft "int"
-.Fn strwidth "const char *p"
-.Ft "void"
-.Fn dialog_create_rc "unsigned char *filename"
-.Ft "int"
-.Fn dialog_yesno "unsigned char *title" "unsigned char *prompt" "int height" "int width"
-.Ft "int"
-.Fn dialog_noyes "unsigned char *title" "unsigned char *prompt" "int height" "int width"
-.Ft "int"
-.Fn dialog_prgbox "unsigned char *title" "const unsigned char *line" "int height" "int width" "int pause" "int use_shell"
-.Ft "int"
-.Fn dialog_textbox "unsigned char *title" "unsigned char *file" "int height" "int width"
-.Ft "int"
-.Fo dialog_menu
-.Fa "unsigned char *title"
-.Fa "unsigned char *prompt"
-.Fa "int height"
-.Fa "int width"
-.Fa "int menu_height"
-.Fa "int cnt"
-.Fa "void *it"
-.Fa "unsigned char *result"
-.Fa "int *ch"
-.Fa "int *sc"
-.Fc
-.Ft "int"
-.Fn dialog_checklist "unsigned char *title" "unsigned char *prompt" "int height" "int width" "int list_height" "int cnt" "void *it" "unsigned char *result"
-.Ft "int"
-.Fn dialog_radiolist "unsigned char *title" "unsigned char *prompt" "int height" "int width" "int list_height" "int cnt" "void *it" "unsigned char *result"
-.Ft "int"
-.Fn dialog_inputbox "unsigned char *title" "unsigned char *prompt" "int height" "int width" "unsigned char *result"
-.Ft "char *"
-.Fn dialog_fselect "char *dir" "char *fmask"
-.Ft "int"
-.Fn dialog_dselect "char *dir" "char *fmask"
-.Ft "void"
-.Fn dialog_notify "char *msg"
-.Ft "int"
-.Fn dialog_mesgbox "unsigned char *title" "unsigned char *prompt" "int height" "int width"
-.Ft "void"
-.Fn dialog_gauge "char *title" "char *prompt" "int y" "int x" "int height" "int width" "int perc"
-.Ft "void"
-.Fn use_helpfile "char *hfile"
-.Ft "void"
-.Fn use_helpline "char *hline"
-.Ft "char *"
-.Fn get_helpline "void"
-.Ft "void"
-.Fn dialog_clear_norefresh "void"
-.Ft "void"
-.Fn dialog_clear "void"
-.Ft "void"
-.Fn dialog_update "void"
-.Ft "void"
-.Fn init_dialog "void"
-.Ft "void"
-.Fn end_dialog "void"
-.Ft "int"
-.Fn dialog_ftree "unsigned char *filename" "unsigned char FS" "unsigned char *title" "unsigned char *prompt" "int height" "int width" "int menu_height" "unsigned char **result"
-.Ft "int"
-.Fo dialog_tree
-.Fa "unsigned char **names"
-.Fa "int size"
-.Fa "unsigned char FS"
-.Fa "unsigned char *title"
-.Fa "unsigned char *prompt"
-.Fa "int height"
-.Fa "int width"
-.Fa "int menu_height"
-.Fa "unsigned char **result"
-.Fc
-.Sh DESCRIPTION
-The dialog library attempts to provide a fairly simplistic set of
-fixed-presentation menus, input boxes, gauges, file requestors and
-other general purpose GUI (a bit of a stretch, since it uses
-ncurses) objects.
-Since the library also had its roots in a
-shell-script writer's utility (see the
-.Xr dialog 1
-command), the
-early API was somewhat primitively based on strings being passed in or
-out and parsed.
-This API was later extended to take either the
-original arguments or arrays of
-.Va dialogMenuItem
-structures,
-giving the user much more control over the internal behavior of each
-control.
-The
-.Va dialogMenuItem
-structure internals are public:
-.Bd -literal -offset indent
-typedef struct _dmenu_item {
-   char *prompt;
-   char *title;
-   int (*checked)(struct _dmenu_item *self);
-   int (*fire)(struct _dmenu_item *self);
-   int (*selected)(struct _dmenu_item *self, int is_selected);
-   void *data;
-   char lbra, mark, rbra;
-   long aux;
-} dialogMenuItem;
-.Ed
-.Pp
-The
-.Dv prompt
-and
-.Dv title
-strings are pretty much self-explanatory,
-and the
-.Va checked
-and
-.Va fire
-function pointers provide optional
-display and action hooks (the
-.Dv data
-variable being available for
-the convenience of those hooks) when more tightly coupled feedback between
-a menu object and user code is required.
-The
-.Va selected
-hook also
-allows you to verify whether or not a given item is selected (the cursor is
-over it) for implementing pretty much any possible context-sensitive
-behavior.
-A number of clever tricks for simulating various kinds of item
-types can also be done by adjusting the values of
-.Va lbra
-(default: '['),
-.Va mark
-(default: '*' for radio menus, 'X' for check menus)
-and
-.Va rbra
-(default: ']') and declaring a reasonable
-.Va checked
-hook,
-which should return TRUE for the
-.Dq marked
-state and FALSE for
-.Dq unmarked .
-The
-.Va aux
-field is not used internally, and is available for miscellaneous usage.
-If an item has a
-.Va fire
-hook associated with it, it will also be called
-whenever the item is "toggled" in some way and should return one of the
-following codes:
-.Bd -literal -offset 4n
-#define DITEM_SUCCESS           0    /* Successful completion */
-#define DITEM_FAILURE           1    /* Failed to "fire" */
-.Ed
-.Pp
-The following flags are in the upper 16 bits of return status:
-.Bd -literal -offset 4n
-#define DITEM_LEAVE_MENU        (1 << 16)
-#define DITEM_REDRAW            (1 << 17)
-#define DITEM_RECREATE          (1 << 18)
-#define DITEM_RESTORE           (1 << 19)
-#define DITEM_CONTINUE          (1 << 20)
-.Ed
-.Pp
-Two special globals also exist for putting a dialog at any arbitrary
-X,Y location (the early designers rather short-sightedly made no provisions
-for this).
-If set to zero, the default centering behavior will be in
-effect.
-.Pp
-Below is a short description of the various functions:
-.Pp
-The
-.Fn draw_shadow
-function draws a shadow in curses window
-.Va win
-using the dimensions of
-.Va x , y , width
-and
-.Va height .
-.Pp
-The
-.Fn draw_box
-function draws a bordered box using the dimensions of
-.Va x , y , width
-and
-.Va height .
-The attributes from
-.Va box
-and
-.Va border
-are used, if specified, while painting the box and border regions of the
-object.
-.Pp
-The
-.Fn line_edit
-function invokes a simple line editor with an edit box of dimensions
-.Va box_x , box_y
-and
-.Va box_width .
-The field length is constrained by
-.Va flen ,
-starting at the
-.Va first
-character specified and
-optionally displayed with character attributes
-.Va attr .
-The string being edited is stored in
-.Va result .
-Returns 0 on success, 1 on Cancel, and -1 on failure or ESC.
-.Pp
-The
-.Fn strheight
-function returns the height of string in
-.Va p ,
-counting newlines.
-.Pp
-The
-.Fn strwidth
-function returns the width of string in
-.Va p ,
-counting newlines.
-.Pp
-The
-.Fn dialog_create_rc
-function dumps dialog library settings into
-.Pa filename
-for later retrieval as defaults.
-Returns 0 on success, -1 on failure.
-.Pp
-The
-.Fn dialog_yesno
-function displays a text box using
-.Va title
-and
-.Va prompt
-strings of dimensions
-.Va height
-and
-.Va width .
-Also paint a pair of
-.Em Yes
-and
-.Em \&No
-buttons at the bottom.
-The default selection is
-.Em Yes .
-If the
-.Em Yes
-button is chosen, return FALSE.
-If
-.Em \&No ,
-return TRUE.
-.Pp
-The
-.Fn dialog_noyes
-function is the same as
-.Fn dialog_yesno ,
-except the default selection is
-.Em \&No .
-.Pp
-The
-.Fn dialog_prgbox
-function displays a text box of dimensions
-.Va height
-and
-.Va width
-containing the output of command
-.Va line .
-If
-.Va use_shell
-is TRUE,
-.Va line
-is passed as an argument to
-.Xr sh 1 ,
-otherwise it is simply passed to
-.Xr exec 3 .
-If
-.Va pause
-is TRUE, a final confirmation requestor will be put up when execution
-terminates.
-Returns 0 on success, -1 on failure.
-.Pp
-The
-.Fn dialog_textbox
-function displays a text box containing the contents of
-.Va file
-with dimensions of
-.Va height
-and
-.Va width .
-.Pp
-The
-.Fn dialog_menu
-function displays a menu of dimensions
-.Va height
-and
-.Va width
-with an optional internal menu height of
-.Va menu_height .
-The
-.Va cnt
-and
-.Va it
-arguments are of particular importance since they,
-together, determine which of the 2 available APIs to use.
-To use the
-older and traditional interface,
-.Va cnt
-should be a positive
-integer representing the number of string pointer pairs to find in
-.Va it
-(which should be of type
-.Ft char "**" ) ,
-the strings are
-expected to be in prompt and title order for each item and the
-.Va result
-parameter is expected to point to an array where the
-prompt string of the item selected will be copied.
-To use the newer
-interface,
-.Va cnt
-should be a
-.Va negative
-integer representing the number of
-.Va dialogMenuItem
-structures pointed to by
-.Va it
-(which should be of type
-.Vt dialogMenuItem "*" ) ,
-one structure per item.
-In the new interface, the
-.Va result
-variable is used as a simple boolean (not a pointer) and should be NULL if
-.Va it
-only points to menu items and the default OK and Cancel buttons are desired.
-If
-.Va result
-is non-NULL, then
-.Va it
-is actually expected to point 2 locations
-.Va past
-the start of the menu item list.
-.Va it
-is then expected to
-point to an item representing the Cancel button, from which the
-.Va prompt
-and
-.Va fire
-actions are used to override the default behavior, and
-.Va it
-to the same for the OK button.
-.Pp
-Using either API behavior, the
-.Va ch
-and
-.Va sc
-values may be passed in to preserve current
-item selection and scroll position values across calls.
-.Pp
-The
-.Fn dialog_checklist
-function displays a menu of dimensions
-.Va height
-and
-.Va width
-with an
-optional internal menu height of
-.Va list_height .
-The
-.Va cnt
-and
-.Va it
-arguments are of particular importance since they,
-together, determine which of the 2 available APIs to use.
-To use the
-older and traditional interface,
-.Va cnt
-should be a positive
-integer representing the number of string pointer tuples to find in
-.Va it
-(which should be of type
-.Ft "char **" ) ,
-the strings are
-expected to be in prompt, title and state ("on" or "off") order for
-each item and the
-.Va result
-parameter is expected to point to an
-array where the prompt string of the item(s) selected will be
-copied.
-To use the newer interface,
-.Va cnt
-should be a
-.Em negative
-integer representing the number of
-.Ft dialogMenuItem
-structures pointed to by
-.Va it
-(which should be of type
-.Ft "dialogMenuItem *" ) ,
-one structure per item.
-In the new interface,
-the
-.Va result
-variable is used as a simple boolean (not a pointer)
-and should be NULL if
-.Va it
-only points to menu items and the default OK and Cancel
-buttons are desired.
-If
-.Va result
-is non-NULL, then
-.Va it
-is actually expected to
-point 2 locations
-.Va past
-the start of the menu item list.
-.Va it
-is then expected to point to an item representing the Cancel
-button, from which the
-.Va prompt
-and
-.Va fire
-actions are used to override the default behavior, and
-.Va it
-to the same for the OK button.
-.Pp
-In the standard API model, the menu supports the selection of multiple items,
-each of which is marked with an `X' character to denote selection.
-When
-the OK button is selected, the prompt values for all items selected are
-concatenated into the
-.Va result
-string.
-.Pp
-In the new API model, it is not actually necessary to preserve
-"checklist" semantics at all since practically everything about how
-each item is displayed or marked as "selected" is fully configurable.
-You could have a single checklist menu that actually contained a group
-of items with "radio" behavior, "checklist" behavior and standard menu
-item behavior.
-The only reason to call
-.Fn dialog_checklist
-over
-.Fn dialog_radiolist
-in the new API model is to inherit the base
-behavior, you are no longer constrained by it.
-.Pp
-Returns 0 on success, 1 on Cancel, and -1 on failure or ESC.
-.Pp
-The
-.Fn dialog_radiolist
-function displays a menu of dimensions
-.Va height
-and
-.Va width
-with an
-optional internal menu height of
-.Va list_height .
-The
-.Va cnt
-and
-.Va it
-arguments are of particular importance since they,
-together, determine which of the 2 available APIs to use.
-To use the
-older and traditional interface,
-.Va cnt
-should be a positive
-integer representing the number of string pointer tuples to find in
-.Va it
-(which should be of type
-.Ft "char **" ) ,
-the strings are
-expected to be in prompt, title and state ("on" or "off") order for
-each item and the
-.Va result
-parameter is expected to point to an
-array where the prompt string of the item(s) selected will be
-copied.
-To use the newer interface,
-.Va cnt
-should be a
-.Dv negative
-integer representing the number of
-.Ft dialogMenuItem
-structures pointed to by
-.Va it
-(which should be of type
-.Ft "dialogMenuItem *" ,
-one structure per item.
-In the new interface,
-the
-.Va result
-variable is used as a simple boolean (not a pointer)
-and should be NULL if
-.Va it
-only points to menu items and the default OK and Cancel
-buttons are desired.
-If
-.Va result
-is non-NULL, then
-.Va it
-is actually expected to point 2 locations
-.Va past
-the start of the menu item list.
-.Va it
-is then expected to point to an item representing the Cancel
-button, from which the
-.Va prompt
-and
-.Va fire
-actions are used to override the default behavior, and
-.Va it
-does the same for the traditional OK button.
-.Pp
-In the standard API model, the menu supports the selection of only one
-of multiple items, the currently active item marked with an `*'
-character to denote selection.
-When the OK button is selected, the
-prompt value for this item is copied into the
-.Va result
-string.
-.Pp
-In the new API model, it is not actually necessary to preserve
-"radio button" semantics at all since practically everything about how
-each item is displayed or marked as "selected" is fully configurable.
-You could have a single radio menu that actually contained a group
-of items with "checklist" behavior, "radio" behavior and standard menu
-item behavior.
-The only reason to call
-.Fn dialog_radiolist
-over
-.Fn dialog_checklistlist
-in the new API model is to inherit the base
-behavior.
-.Pp
-Returns 0 on success, 1 on Cancel and -1 on failure or ESC.
-.Pp
-The
-.Fn dialog_inputbox
-function displays a single-line text input field in a box displaying
-.Va title
-and
-.Va prompt
-of dimensions
-.Va height
-and
-.Va width .
-The field entered is stored in
-.Va result .
-.Pp
-Returns 0 on success, -1 on failure or ESC.
-.Pp
-The
-.Fn dialog_fselect
-function brings up a file selector dialog starting at
-.Va dir
-and showing only those file names
-matching
-.Va fmask .
-.Pp
-Returns filename selected or NULL.
-.Pp
-The
-.Fn dialog_dselect
-function brings up a directory selector dialog starting at
-.Va dir
-and showing only those directory names
-matching
-.Va fmask .
-.Pp
-Returns directory name selected or NULL.
-.Pp
-The
-.Fn dialog_notify
-function brings up a generic "hey, you!" notifier dialog containing
-.Va msg .
-.Pp
-The
-.Fn dialog_mesgbox
-function displays a notifier dialog, but with more control over
-.Va title ,
-.Va prompt ,
-.Va width
-and
-.Va height .
-This object will also wait for user confirmation, unlike
-.Fn dialog_notify .
-.Pp
-Returns 0 on success, -1 on failure.
-.Pp
-The
-.Fn dialog_gauge
-function displays a horizontal bar-graph style gauge.
-A value of
-.Em 100
-for
-.Em perc
-constitutes a full gauge, a value of
-.Em 0
-an empty one.
-.Pp
-The
-.Fn use_helpfile
-function for any menu supporting context sensitive help, invokes the text box
-object on this file whenever the
-.Em F1
-key is pressed.
-.Pp
-The
-.Fn use_helpline
-function displays this line of helpful text below any menu being displayed.
-.Pp
-The
-.Fn get_helpline
-function gets the current value of the helpful text line.
-.Pp
-The
-.Fn dialog_clear_norefresh
-function clears the screen back to the dialog background color, but do not
-refresh the contents just yet.
-.Pp
-The
-.Fn dialog_clear
-function clears the screen back to the dialog background color immediately.
-.Pp
-The
-.Fn dialog_update
-function does any pending screen refreshes now.
-.Pp
-The
-.Fn init_dialog
-function initializes the dialog library (call this routine before any other
-dialog API calls).
-.Pp
-The
-.Fn end_dialog
-function shuts down the dialog library (call this if you need to get back to
-sanity).
-.Pp
-The
-.Fn dialog_ftree
-function shows a tree described by the data from the file
-.Pa filename .
-The data in the file should look like
-.Xr find 1
-output.
-For the
-.Xr find 1
-output, the field separator
-.Va FS
-will be
-.Dq \&/ .
-If
-.Va height
-and
-.Va width
-are positive numbers, they set the absolute
-size of the whole
-.Fn dialog_ftree
-box.
-If
-.Va height
-and
-.Va width
-are negative numbers, the size of the
-.Fn dialog_ftree
-box will be calculated automatically.
-.Va menu_height
-sets the height of the tree subwindow inside the
-.Fn dialog_ftree
-box and must be set.
-.Va title
-is shown centered on the upper border of the
-.Fn dialog_ftree
-box.
-.Va prompt
-is shown inside the
-.Fn dialog_ftree
-box above the tree subwindow and can contain
-.Ql \e\&n
-to split lines.
-One can navigate in
-the tree by pressing UP/DOWN or
-.Sm off
-.So \&+ Sc \&/ So \&- Sc ,
-.Sm on
-PG_UP/PG_DOWN or
-.Sm off
-.So b Sc \&/SPACE
-.Sm on
-and
-HOME/END or
-.Sm off
-.So g Sc \&/ So G Sc .
-.Sm on
-A leaf of the
-tree is selected by pressing TAB or LEFT/RIGHT the OK
-button and pressing ENTER.
-filename may contain data like
-.Xr find 1
-output, as well as like the output of
-.Xr find 1
-with
-.Fl d
-option.
-Some of the transient paths to the leaves of the tree may
-be absent.
-Such data is corrected when fed from filename.
-.Pp
-The function returns 0 and a pointer to the selected leaf (to the path to
-the leaf from the root of the tree) into result, if the OK button was
-selected.
-The memory allocated for the building of the tree is freed on
-exiting
-.Fn dialog_ftree .
-The memory for the result line should be freed
-later manually, if necessary.
-If the Cancel button was selected, the
-function returns 1.
-In case of exiting
-.Fn dialog_ftree
-on ESC, the function returns -1.
-.Pp
-The
-.Fn dialog_tree
-function returns the same results as
-.Fn dialog_ftree .
-If 0 is returned, result will contain a pointer from the array
-.Va names .
-.\" \fBdialog_tree\fR displays the tree very much like \fBdialog_ftree\fR does,
-.\" with some exceptions. The source data for the building of the tree is an
-.\" array \fBnames\fR of paths to the leaves (should be similar to \fBfind(1)\fR
-.\" output) of the size \fBsize\fR. However, there is no correction of data like
-.\" in \fBdialog_ftree\fR. Thus, to display a correct tree, the array must
-.\" already contain correct data. Besides, in each session every unique use of
-.\" \fBdialog_tree\fR is kept in memory, and later, when calling
-.\" \fBdialog_tree\fR with the same \fBnames\fR, \fBsize\fR, \fBFS\fR,
-.\" \fBheight\fR, \fBwidth\fR and \fBmenu_height\fR the position of the cursor
-.\" in the tree subwindow is restored.
-.Sh SEE ALSO
-.Xr dialog 1 ,
-.Xr ncurses 3
-.Sh HISTORY
-These functions appeared in
-.Fx 2.0
-as the
-.Xr dialog 1
-command and were soon split into a separate library
-and command by
-.An Andrey Chernov .
-.An Marc van Kempen
-implemented most of the extra controls and objects,
-.An Jordan Hubbard
-added the dialogMenuItem renovations and this man page and
-.An Anatoly A. Orehovsky
-implemented
-.Fn dialog_ftree
-and
-.Fn dialog_tree .
-.Sh AUTHORS
-.An -nosplit
-The primary author would appear to be
-.An Savio Lam Aq lam836 at cs.cuhk.hk
-with contributions over the years by
-.An Stuart Herbert Aq S.Herbert at sheffield.ac.uk ,
-.An Marc van Kempen Aq wmbfmk at urc.tue.nl ,
-.An Andrey Chernov Aq ache at FreeBSD.org ,
-.An Jordan Hubbard Aq jkh at FreeBSD.org
-and
-.An Anatoly A. Orehovsky Aq tolik at mpeks.tomsk.su .
-.Sh BUGS
-Sure!
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/dialog.h
--- a/head/gnu/lib/libodialog/dialog.h	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,211 +0,0 @@
-#ifndef _DIALOG_H_INCLUDE
-#define _DIALOG_H_INCLUDE
-
-/*
- *  dialog.h -- common declarations for all dialog modules
- *
- *  AUTHOR: Savio Lam (lam836 at cs.cuhk.hk)
- *
- *	Substantial rennovation:  12/18/95, Jordan K. Hubbard
- *
- *  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., 675 Mass Ave, Cambridge, MA 02139, USA.
- *
- * $FreeBSD$
- *
- */
-
-#define HAVE_NCURSES
-
-#ifdef HAVE_NCURSES
-#include <ncurses.h>
-
-#else
-
-#ifdef ultrix
-#include <cursesX.h>
-#else
-#include <curses.h>
-#endif
-
-#endif
-
-/* special return codes for `fire' actions */
-#define DITEM_STATUS(flag)	((flag) & 0x0000FFFF)
-#define DITEM_SUCCESS		0
-#define DITEM_FAILURE		1
-
-/* Flags - returned in upper 16 bits of return status */
-#define DITEM_LEAVE_MENU	(1 << 16)
-#define DITEM_REDRAW		(1 << 17)
-#define DITEM_RECREATE		(1 << 18)
-#define DITEM_RESTORE		(1 << 19)
-#define DITEM_CONTINUE		(1 << 20)
-
-/* Attributes as used by entry fields right now */
-#define DITEM_NO_ECHO		0x0001
-
-
-/* negative offsets for buttons in item lists, if specified */
-#define OK_BUTTON		-2
-#define CANCEL_BUTTON		-1
-
-/* for use in describing more exotic behaviors */
-typedef struct _dmenu_item {
-  char *prompt;
-  char *title;
-  int (*checked)(struct _dmenu_item *self);
-  int (*fire)(struct _dmenu_item *self);
-  void (*selected)(struct _dmenu_item *self, int is_selected);
-  void *data;
-  char lbra, mark, rbra;
-  long aux;
-} dialogMenuItem;
-
-#define VERSION "0.4"
-#define MAX_LEN 4096
-
-#ifndef TRUE
-#define TRUE (1)
-#endif
-#ifndef FALSE
-#define FALSE (0)
-#endif
-
-extern int DialogX, DialogY, DialogInputAttrs;
-
-/*
- * Attribute names
- */
-#define screen_attr                   attributes[0]
-#define shadow_attr                   attributes[1]
-#define dialog_attr                   attributes[2]
-#define title_attr                    attributes[3]
-#define border_attr                   attributes[4]
-#define button_active_attr            attributes[5]
-#define button_inactive_attr          attributes[6]
-#define button_key_active_attr        attributes[7]
-#define button_key_inactive_attr      attributes[8]
-#define button_label_active_attr      attributes[9]
-#define button_label_inactive_attr    attributes[10]
-#define inputbox_attr                 attributes[11]
-#define inputbox_border_attr          attributes[12]
-#define searchbox_attr                attributes[13]
-#define searchbox_title_attr          attributes[14]
-#define searchbox_border_attr         attributes[15]
-#define position_indicator_attr       attributes[16]
-#define menubox_attr                  attributes[17]
-#define menubox_border_attr           attributes[18]
-#define item_attr                     attributes[19]
-#define item_selected_attr            attributes[20]
-#define tag_attr                      attributes[21]
-#define tag_selected_attr             attributes[22]
-#define tag_key_attr                  attributes[23]
-#define tag_key_selected_attr         attributes[24]
-#define check_attr                    attributes[25]
-#define check_selected_attr           attributes[26]
-#define uarrow_attr                   attributes[27]
-#define darrow_attr                   attributes[28]
-
-/* number of attributes */
-#define ATTRIBUTE_COUNT               29
-
-extern chtype attributes[];
-
-#ifdef HAVE_NCURSES
-extern bool use_shadow;
-void draw_shadow(WINDOW *win, int y, int x, int height, int width);
-#endif
-void draw_box(WINDOW *win, int y, int x, int height, int width, chtype box, chtype border);
-int line_edit(WINDOW *dialog, int box_y, int box_x, int flen, int box_width, chtype attrs, int first, unsigned char *result, int attr_mask);
-int     strheight(const char *p);
-int     strwidth(const char *p);
-
-void dialog_create_rc(unsigned char *filename);
-int dialog_yesno(unsigned char *title, unsigned char *prompt, int height, int width);
-int dialog_noyes(unsigned char *title, unsigned char *prompt, int height, int width);
-int dialog_prgbox(unsigned char *title, const unsigned char *line, int height, int width, int pause, int use_shell);
-int dialog_msgbox(unsigned char *title, unsigned char *prompt, int height, int width, int pause);
-int dialog_textbox(unsigned char *title, unsigned char *file, int height, int width);
-int dialog_menu(unsigned char *title, unsigned char *prompt, int height, int width, int menu_height,
-		int item_no, void *itptr, unsigned char *result, int *ch, int *sc);
-int dialog_checklist(unsigned char *title, unsigned char *prompt, int height, int width, int list_height,
-		     int item_no, void *itptr, unsigned char *result);
-int dialog_radiolist(unsigned char *title, unsigned char *prompt, int height, int width, int list_height,
-		     int item_no, void *itptr, unsigned char *result);
-int dialog_inputbox(unsigned char *title, unsigned char *prompt, int height, int width, unsigned char *result);
-void dialog_clear_norefresh(void);
-void dialog_clear(void);
-void dialog_update(void);
-void init_dialog(void);
-void end_dialog(void);
-
-/* Additions to libdialog */
-char *dialog_fselect(char *dir, char *fmask);
-int  dialog_dselect(char *dir, char *fmask);
-void dialog_notify(char *msg);
-int  dialog_mesgbox(unsigned char *title, unsigned char *prompt, int height, int width);
-void use_helpfile(char *helpfile);
-void use_helpline(char *helpline);
-char *get_helpline(void);
-void restore_helpline(char *helpline);
-void dialog_gauge(char *title, char *prompt, int y, int x, int height, int width, int perc);
-
-/*
- * Display a tree menu from file
- *
- * filename	- file with like find(1) output
- * FS		- fields separator
- * title	- title of dialog box
- * prompt	- prompt text into dialog box
- * height	- height of dialog box
- * width	- width of dialog box
- * menu_height	- height of menu box
- * result	- pointer to char array
- *
- * return values:
- * -1		- ESC pressed
- * 0		- Ok, result set (must be freed later)
- * 1		- Cancel
- */
-int dialog_ftree(unsigned char *filename, unsigned char FS,
-		unsigned char *title, unsigned char *prompt, 
-			int height, int width, int menu_height, 
-					unsigned char **result);
-
-/*
- * Display a tree menu from array
- *
- * names	- array with like find(1) output
- * size		- size of array
- * FS		- fields separator
- * title	- title of dialog box
- * prompt	- prompt text into dialog box
- * height	- height of dialog box
- * width	- width of dialog box
- * menu_height	- height of menu box
- * result	- pointer to char array
- *
- * return values:
- * -1		- ESC pressed
- * 0		- Ok, result set
- * 1		- Cancel
- */
- 
-int dialog_tree(unsigned char **names, int size, unsigned char FS,
-		unsigned char *title, unsigned char *prompt, 
-			int height, int width, int menu_height, 
-					unsigned char **result);
-
-#endif /* _DIALOG_H_INCLUDE */
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/dialog.priv.h
--- a/head/gnu/lib/libodialog/dialog.priv.h	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,183 +0,0 @@
-/*
- *  dialog.h -- common declarations for all dialog modules
- *
- *  AUTHOR: Savio Lam (lam836 at cs.cuhk.hk)
- *
- *  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., 675 Mass Ave, Cambridge, MA 02139, USA.
- */
-
-
-#include <sys/types.h>
-#include <fcntl.h>
-#include <unistd.h>
-#include <ctype.h>
-#include <stdlib.h>
-#include <string.h>
-#include <termios.h>
-
-#if defined(LOCALE)
-#include <locale.h>
-#endif
-
-  
-/*
- * Change these if you want
- */
-#define USE_SHADOW TRUE
-#define USE_COLORS TRUE
-
-#define ESC 27
-#define TAB 9
-#define BUF_SIZE (10*1024)
-
-#ifndef MIN
-#define MIN(x,y) (x < y ? x : y)
-#endif
-#ifndef MAX
-#define MAX(x,y) (x > y ? x : y)
-#endif
-
-#ifndef ctrl
-#define ctrl(a)          ((a) - 'a' + 1)
-#endif
-
-#ifndef HAVE_NCURSES
-#ifndef ACS_ULCORNER
-#define ACS_ULCORNER '+'
-#endif
-#ifndef ACS_LLCORNER
-#define ACS_LLCORNER '+'
-#endif
-#ifndef ACS_URCORNER
-#define ACS_URCORNER '+'
-#endif
-#ifndef ACS_LRCORNER
-#define ACS_LRCORNER '+'
-#endif
-#ifndef ACS_HLINE
-#define ACS_HLINE '-'
-#endif
-#ifndef ACS_VLINE
-#define ACS_VLINE '|'
-#endif
-#ifndef ACS_LTEE
-#define ACS_LTEE '+'
-#endif
-#ifndef ACS_RTEE
-#define ACS_RTEE '+'
-#endif
-#ifndef ACS_UARROW
-#define ACS_UARROW '^'
-#endif
-#ifndef ACS_DARROW
-#define ACS_DARROW 'v'
-#endif
-#endif    /* HAVE_NCURSES */
-
-/* Travel key conventions */
-#define KEY_IS_UP(key)		((key) == KEY_UP || (key) == '-' || key == '\020' /* ^P */)
-#define KEY_IS_DOWN(key)	((key) == KEY_DOWN || (key) == '+' || key == '\016' /* ^N */)
-
-/*
- * Global variables
- */
-#ifdef __DIALOG_MAIN__
-
-#ifdef HAVE_NCURSES
-
-/* use colors by default? */
-bool use_colors = USE_COLORS;
-
-/* shadow dialog boxes by default?
-   Note that 'use_shadow' implies 'use_colors' */
-bool use_shadow = USE_SHADOW;
-
-#endif
-
-
-/*
- * Attribute values, default is for mono display
- */
-chtype attributes[] = {
-  A_NORMAL,       /* screen_attr */
-  A_NORMAL,       /* shadow_attr */
-  A_REVERSE,      /* dialog_attr */
-  A_REVERSE,      /* title_attr */
-  A_REVERSE,      /* border_attr */
-  A_BOLD,         /* button_active_attr */
-  A_DIM,          /* button_inactive_attr */
-  A_UNDERLINE,    /* button_key_active_attr */
-  A_UNDERLINE,    /* button_key_inactive_attr */
-  A_NORMAL,       /* button_label_active_attr */
-  A_NORMAL,       /* button_label_inactive_attr */
-  A_REVERSE,      /* inputbox_attr */
-  A_REVERSE,      /* inputbox_border_attr */
-  A_REVERSE,      /* searchbox_attr */
-  A_REVERSE,      /* searchbox_title_attr */
-  A_REVERSE,      /* searchbox_border_attr */
-  A_REVERSE,      /* position_indicator_attr */
-  A_REVERSE,      /* menubox_attr */
-  A_REVERSE,      /* menubox_border_attr */
-  A_REVERSE,      /* item_attr */
-  A_NORMAL,       /* item_selected_attr */
-  A_REVERSE,      /* tag_attr */
-  A_REVERSE,      /* tag_selected_attr */
-  A_NORMAL,       /* tag_key_attr */
-  A_BOLD,         /* tag_key_selected_attr */
-  A_REVERSE,      /* check_attr */
-  A_REVERSE,      /* check_selected_attr */
-  A_REVERSE,      /* uarrow_attr */
-  A_REVERSE       /* darrow_attr */
-};
-
-#else
-
-#ifdef HAVE_NCURSES
-extern bool use_colors;
-#endif
-
-#endif    /* __DIALOG_MAIN__ */
-
-
-
-#ifdef HAVE_NCURSES
-
-/*
- * Function prototypes
- */
-#ifdef __DIALOG_MAIN__
-
-extern int parse_rc(void);
-
-#endif    /* __DIALOG_MAIN__ */
-
-#endif
-
-
-#ifdef HAVE_NCURSES
-void color_setup(void);
-#endif
-
-void attr_clear(WINDOW *win, int height, int width, chtype attr);
-void print_autowrap(WINDOW *win, unsigned char *prompt, int height, int width, int maxwidth,
-		    int y, int x, int center, int rawmode);
-void print_button(WINDOW *win, unsigned char *label, int y, int x, int selected);
-FILE *raw_popen(const char *program, char * const *argv, const char *type);
-int raw_pclose(FILE *iop);
-void display_helpfile(void);
-void display_helpline(WINDOW *w, int y, int width);
-void print_arrows(WINDOW *dialog, int scroll, int menu_height, int item_no, int box_x,
-		  int box_y, int tag_x, int cur_x, int cur_y);
-
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/dir.c
--- a/head/gnu/lib/libodialog/dir.c	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,549 +0,0 @@
-/****************************************************************************
- *
- *	Program:	dir.c
- *	Author:		Marc van Kempen
- *	desc:		Directory routines, sorting and reading
- *
- * Copyright (c) 1995, Marc van Kempen
- *
- * All rights reserved.
- *
- * This software may be used, modified, copied, distributed, and
- * sold, in both source and binary form provided that the above
- * copyright and these terms are retained, verbatim, as the first
- * lines of this file.  Under no circumstances is the author
- * responsible for the proper functioning of this software, nor does
- * the author assume any responsibility for damages incurred with
- * its use.
- *
- ****************************************************************************/
-
-#include <sys/types.h>
-#include <sys/stat.h>
-
-#include <unistd.h>		/* XXX for _POSIX_VERSION ifdefs */
-
-#if !defined sgi && !defined _POSIX_VERSION
-#include <sys/dir.h>
-#endif
-#if defined __sun__
-#include <sys/dirent.h>
-#endif
-#if defined sgi || defined _POSIX_VERSION
-#include <dirent.h>
-#endif
-
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-#include <fnmatch.h>
-#include <sys/param.h>
-#include "dir.h"
-
-/****************************************************************************
- *
- *	local prototypes
- *
- ****************************************************************************/
-
-void toggle_dotfiles(void);
-int  show_dotfiles(void);
-int  dir_alphasort(const void *d1, const void *d2);
-int  dir_sizesort(const void *d1, const void *d2);
-int  dir_datesort(const void *d1, const void *d2);
-int  dir_extsort(const void *d1, const void *d2);
-
-/****************************************************************************
- *
- *	global variables
- *
- ****************************************************************************/
-
-
-/* This is user-selectable, I've set them fixed for now however */
-
-void		*_sort_func = dir_alphasort;
-static int	_showdotfiles = TRUE;
-
-/****************************************************************************
- *
- *	Functions
- *
- ****************************************************************************/
-
-int
-dir_select_nd(
-#if defined __linux__
-  const struct dirent *d
-#else
-  struct dirent *d
-#endif
-)
-/*
- *	desc:	allways include a directory entry <d>, except
- *		for the current directory and other dot-files
- *		keep '..' however.
- *	pre:	<d> points to a dirent
- *	post:	returns TRUE if d->d_name != "." else FALSE
- */
-{
-    if (strcmp(d->d_name, ".")==0 ||
-	  (d->d_name[0] == '.' && strlen(d->d_name) > 1 && d->d_name[1] != '.')) {
-	return(FALSE);
-    } else {
-	return(TRUE);
-    }
-}/* dir_select_nd() */
-
-
-int
-dir_select(
-#ifdef __linux__
-  const struct dirent *d
-#else
-  struct dirent *d
-#endif
-)
-/*
- *	desc:	allways include a directory entry <d>, except
- *		for the current directory
- *	pre:	<d> points to a dirent
- *	post:	returns TRUE if d->d_name != "." else FALSE
- */
-{
-	if (strcmp(d->d_name, ".")==0) {	/* don't include the current directory */
-		return(FALSE);
-	} else {
-	    return(TRUE);
-	}
-} /* dir_select() */
-
-int
-dir_select_root_nd(
-#ifdef __linux__
-  const struct dirent *d
-#else
-  struct dirent *d
-#endif
-)
-/*
- *	desc:	allways include a directory entry <d>, except
- *		for the current directory and the parent directory.
- *		Also skip any other dot-files.
- *	pre:	<d> points to a dirent
- *	post:	returns TRUE if d->d_name[0] != "." else FALSE
- */
-{
-	if (d->d_name[0] == '.') {	/* don't include the current directory */
-		return(FALSE);		/* nor the parent directory */
-	} else {
-	    return(TRUE);
-	}
-} /* dir_select_root_nd() */
-
-
-int
-dir_select_root(
-#ifdef __linux__
-  const struct dirent *d
-#else
-  struct dirent *d
-#endif
-)
-/*
- *	desc:	allways include a directory entry <d>, except
- *		for the current directory and the parent directory
- *	pre:	<d> points to a dirent
- *	post:	returns TRUE if d->d_name[0] != "." else FALSE
- */
-{
-	if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) {
-		return(FALSE);
-	} else {
-	    return(TRUE);
-	}
-}/* dir_select_root() */
-
-
-#ifdef NO_ALPHA_SORT
-int
-alphasort(const void *d1, const void *d2)
-/*
- *	desc:	a replacement for what should be in the library
- */
-{
-    return(strcmp(((struct dirent *) d1)->d_name,
-		  ((struct dirent *) d2)->d_name));
-} /* alphasort() */
-#endif
-
-int
-dir_alphasort(const void *d1, const void *d2)
-/*
- *	desc:	compare d1 and d2, but put directories always first
- *		put '..' always on top
- *
- */
-{
-    DirList	*f1 = ((DirList *) d1),
-		*f2 = ((DirList *) d2);
-    struct stat	*s1 = &(f1->filestatus);
-    struct stat	*s2 = &(f2->filestatus);
-
-    /* check for '..' */
-    if (strcmp(((DirList *) d1)->filename, "..") == 0) {
-	return(-1);
-    }
-    if (strcmp(((DirList *) d2)->filename, "..") == 0) {
-	return(1);
-    }
-
-    /* put directories first */
-    if ((s1->st_mode & S_IFDIR) && (s2->st_mode & S_IFDIR)) {
-	return(strcmp(f1->filename, f2->filename));
-    };
-    if (s1->st_mode & S_IFDIR) {
-	return(-1);
-    }
-    if (s2->st_mode & S_IFDIR) {
-	return(1);
-    }
-    return(strcmp(f1->filename, f2->filename));
-
-} /* dir_alphasort() */
-
-
-int
-dir_sizesort(const void *d1, const void *d2)
-/*
- *	desc:	compare d1 and d2, but put directories always first
- *
- */
-{
-    DirList	*f1 = ((DirList *) d1),
-		*f2 = ((DirList *) d2);
-    struct stat	*s1 = &(f1->filestatus);
-    struct stat	*s2 = &(f2->filestatus);
-
-    /* check for '..' */
-    if (strcmp(((DirList *) d1)->filename, "..") == 0) {
-	return(-1);
-    }
-    if (strcmp(((DirList *) d2)->filename, "..") == 0) {
-	return(1);
-    }
-
-    /* put directories first */
-    if ((s1->st_mode & S_IFDIR) && (s2->st_mode & S_IFDIR)) {
-	return(s1->st_size < s2->st_size ?
-	       -1
-	       :
-	       s1->st_size >= s2->st_size);
-    };
-    if (s1->st_mode & S_IFDIR) {
-	return(-1);
-    }
-    if (s2->st_mode & S_IFDIR) {
-	return(1);
-    }
-    return(s1->st_size < s2->st_size ?
-	   -1
-	   :
-	   s1->st_size >= s2->st_size);
-
-} /* dir_sizesort() */
-
-int
-dir_datesort(const void *d1, const void *d2)
-/*
- *	desc:	compare d1 and d2 on date, but put directories always first
- */
-{
-    DirList	*f1 = ((DirList *) d1),
-		*f2 = ((DirList *) d2);
-    struct stat	*s1 = &(f1->filestatus);
-    struct stat	*s2 = &(f2->filestatus);
-
-
-    /* check for '..' */
-    if (strcmp(((DirList *) d1)->filename, "..") == 0) {
-	return(-1);
-    }
-    if (strcmp(((DirList *) d2)->filename, "..") == 0) {
-	return(1);
-    }
-
-    /* put directories first */
-    if ((s1->st_mode & S_IFDIR) && (s2->st_mode & S_IFDIR)) {
-	return(s1->st_mtime < s2->st_mtime ?
-	       -1
-	       :
-	       s1->st_mtime >= s2->st_mtime);
-    };
-    if (s1->st_mode & S_IFDIR) {
-	return(-1);
-    }
-    if (s2->st_mode & S_IFDIR) {
-	return(1);
-    }
-    return(s1->st_mtime < s2->st_mtime ?
-	   -1
-	   :
-	   s1->st_mtime >= s2->st_mtime);
-
-} /* dir_datesort() */
-
-
-int
-null_strcmp(char *s1, char *s2)
-/*
- *	desc:	compare strings allowing NULL pointers
- */
-{
-	if ((s1 == NULL) && (s2 == NULL)) {
-		return(0);
-	}
-	if (s1 == NULL) {
-		return(-1);
-	}
-	if (s2 == NULL) {
-		return(1);
-	}
-	return(strcmp(s1, s2));
-} /* null_strcmp() */
-
-
-int
-dir_extsort(const void *d1, const void *d2)
-/*
- *	desc:	compare d1 and d2 on extension, but put directories always first
- *		extension = "the characters after the last dot in the filename"
- *	pre:	d1 and d2 are pointers to  DirList type records
- *	post:	see code
- */
-{
-    DirList	*f1 = ((DirList *) d1),
-		*f2 = ((DirList *) d2);
-    struct stat	*s1 = &(f1->filestatus);
-    struct stat	*s2 = &(f2->filestatus);
-    char 	*ext1, *ext2;
-    int		extf, ret;
-
-
-    /* check for '..' */
-    if (strcmp(((DirList *) d1)->filename, "..") == 0) {
-	return(-1);
-    }
-    if (strcmp(((DirList *) d2)->filename, "..") == 0) {
-	return(1);
-    }
-
-
-    /* find the first extension */
-
-    ext1 = f1->filename + strlen(f1->filename);
-    extf = FALSE;
-    while (!extf && (ext1 > f1->filename)) {
-	extf = (*--ext1 == '.');
-    }
-    if (!extf) {
-	ext1 = NULL;
-    } else {
-	ext1++;
-    }
-    /* ext1 == NULL if there's no "extension" else ext1 points */
-    /* to the first character of the extension string */
-
-    /* find the second extension */
-
-    ext2 = f2->filename + strlen(f2->filename);
-    extf = FALSE;
-    while (!extf && (ext2 > f2->filename)) {
-	extf = (*--ext2 == '.');
-    }
-    if (!extf) {
-	ext2 = NULL;
-    } else {
-	ext2++;
-    }
-    /* idem as for ext1 */
-
-    if ((s1->st_mode & S_IFDIR) && (s2->st_mode & S_IFDIR)) {
-	ret = null_strcmp(ext1, ext2);
-	if (ret == 0) {
-	    return(strcmp(f1->filename, f2->filename));
-	} else {
-	    return(ret);
-	}
-    };
-    if (s1->st_mode & S_IFDIR) {
-	return(-1);
-    }
-    if (s2->st_mode & S_IFDIR) {
-	return(1);
-    }
-    ret = null_strcmp(ext1, ext2);
-    if (ret == 0) {
-	return(strcmp(f1->filename, f2->filename));
-    } else {
-	return(ret);
-    }
-
-} /* dir_extsort() */
-
-
-void
-get_dir(char *dirname, char *fmask, DirList **dir, int *n)
-/*
- *	desc:	get the files in the current directory
- *	pre:	<dir> == NULL
- *	post:	<dir> contains <n> dir-entries
- */
-{
-	char		cwd[MAXPATHLEN];
-	char		buf[256];
-	struct dirent	**dire;
-	struct stat	status;
-	int		i, j, nb;
-	long		d;
-
-
-	getcwd(cwd, MAXPATHLEN);
-	if (strcmp(cwd, "/") == 0) {	/* we are in the root directory */
-	    if (show_dotfiles()) {
-		*n = scandir(dirname, &dire, dir_select_root, alphasort);
-	    } else {
-		*n = scandir(dirname, &dire, dir_select_root_nd, alphasort);
-	    }
-	} else {
-	    if (show_dotfiles()) {
-		*n = scandir(dirname, &dire, dir_select, alphasort);
-	    } else {
-		*n = scandir(dirname, &dire, dir_select_nd, alphasort);
-	    }
-	}
-
-	/* There is the possibility that we have entered a directory	*/
-	/* which we are not allowed to read, scandir thus returning  	*/
-	/* -1 for *n.	 						*/
-	/* Actually I should also check for lack of memory, but I'll 	*/
-	/* let my application happily crash if this is the case		*/
-	/* Solution:							*/
-	/*	manually insert the parent directory as the only	*/
-	/*	directory entry, and return.				*/
-
-	if (*n == -1) {
-	    *n = 1;
-	    *dir = (DirList *) malloc(sizeof(DirList));
-	    strcpy((*dir)[0].filename, "..");
-	    lstat("..", &status);
-	    (*dir)[0].filestatus = status;
-	    (*dir)[0].link = FALSE;
-	    return;
-	}
-
-	*dir = (DirList *) malloc( *n * sizeof(DirList) );
-	d = 0;
-	i = 0;
-	j = 0;
-	while (j<*n) {
-	    lstat(dire[j]->d_name, &status);
-	    /* check if this file is to be included */
-	    /* always include directories, the rest is subject to fmask */
-	    if (S_ISDIR(status.st_mode)
-		|| fnmatch(fmask, dire[j]->d_name, FNM_NOESCAPE) != FNM_NOMATCH) {
-		strcpy((*dir)[i].filename, dire[j]->d_name);
-		(*dir)[i].filestatus = status;
-		if ((S_IFMT & status.st_mode) == S_IFLNK) {  /* handle links */
-		    (*dir)[i].link = TRUE;
-		    stat(dire[j]->d_name, &status);
-		    nb = readlink(dire[j]->d_name, buf, sizeof(buf) - 1);
-		    if (nb == -1) {
-			printf("get_dir(): Error reading link: %s\n", dire[j]->d_name);
-			exit(-1);
-		    } else {
-			(*dir)[i].linkname = malloc(sizeof(char) * nb + 1);
-			strncpy((*dir)[i].linkname, buf, nb);
-			(*dir)[i].linkname[nb] = 0;
-		    }
-		    (*dir)[i].filestatus = status;
-		} else {
-		    (*dir)[i].link = FALSE;
-		    (*dir)[i].linkname = NULL;
-		}
-		i++;
-	    } else {
-		/* skip this entry */
-	    }
-	    j++;
-	}
-	*n = i;
-
-	/* sort the directory with the directory names on top */
-	qsort((*dir), *n, sizeof(DirList), _sort_func);
-
-	/* Free the allocated memory */
-	for (i=0; i<*n; i++) {
-	    free(dire[i]);
-	}
-	free(dire);
-
-	return;
-}/* get_dir() */
-
-
-void
-FreeDir(DirList *d, int n)
-/*
- * 	desc:	free the dirlist d
- *	pre:	d != NULL
- *	post:	memory allocated to d has been released
- */
-{
-    int i;
-
-    if (d) {
-	for (i=0; i<n; i++) {
-	    if (d[i].linkname) {
-		free(d[i].linkname);
-	    }
-	}
-	free(d);
-    } else {
-	printf("dir.c:FreeDir(): d == NULL\n");
-	exit(-1);
-    }
-
-    return;
-} /* FreeDir() */
-
-void
-toggle_dotfiles(void)
-/*
- *	desc: toggle visibility of dot-files
- */
-{
-    _showdotfiles = !_showdotfiles;
-
-    return;
-} /* toggle_dotfiles() */
-
-int
-show_dotfiles(void)
-/*
- *	desc: return the value of _showdotfiles
- */
-{
-    return(_showdotfiles);
-} /* show_dotfiles() */
-
-void
-set_dotfiles(int b)
-/*
- *	desc: set the value of _showdotfiles
- */
-{
-    _showdotfiles = b;
-
-    return;
-} /* set_dotfiles() */
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/dir.h
--- a/head/gnu/lib/libodialog/dir.h	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,38 +0,0 @@
-/*
- * include file for dir.c
- *
- * Copyright (c) 1995, Marc van Kempen
- *
- * All rights reserved.
- *
- * This software may be used, modified, copied, distributed, and
- * sold, in both source and binary form provided that the above
- * copyright and these terms are retained, verbatim, as the first
- * lines of this file.  Under no circumstances is the author
- * responsible for the proper functioning of this software, nor does
- * the author assume any responsibility for damages incurred with
- * its use.
- *
- */
-
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <sys/dirent.h>
-
-typedef struct DirList {             /* structure to hold the directory entries */
-    char        filename[MAXNAMLEN]; /* together with the stat-info per file */
-    struct stat filestatus;          /* filename, or the name to which it points */
-    int         link;                /* is it a link ? */
-    char        *linkname;           /* the name of the file the link points to */
-} DirList;
-
-#ifndef TRUE
-#define TRUE (1)
-#endif
-#ifndef FALSE
-#define FALSE (0)
-#endif
-
-void get_dir(char *dirname, char *fmask, DirList **dir, int *n);
-void get_filenames(DirList *d, int n, char ***names, int *nf);
-void FreeDir(DirList *d, int n);
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/fselect.c
--- a/head/gnu/lib/libodialog/fselect.c	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,402 +0,0 @@
-/*
- * program:	fselect.c
- * author:	Marc van Kempen (wmbfmk at urc.tue.nl)
- * Desc:	File selection routine
- *
- * Copyright (c) 1995, Marc van Kempen
- *
- * All rights reserved.
- *
- * This software may be used, modified, copied, distributed, and
- * sold, in both source and binary form provided that the above
- * copyright and these terms are retained, verbatim, as the first
- * lines of this file.  Under no circumstances is the author
- * responsible for the proper functioning of this software, nor does
- * the author assume any responsibility for damages incurred with
- * its use.
- *
- */
-
-#include <stdlib.h>
-#include <unistd.h>
-#include <sys/param.h>
-#include <dialog.h>
-#include "ui_objects.h"
-#include "dir.h"
-#include "dialog.priv.h"
-
-/*
- * Local prototypes
- */
-
-char *dialog_dfselect(char *dir, char *fmask, int is_fselect);
-
-/*
- * Functions
- */
-
-void
-get_directories(DirList *d, int n, char ***names, int *nd)
-/*
- * Desc: return the directorienames in <dir> as an array in
- *	 <names>, the # of entries in <nd>, memory allocated
- *       to *names should be freed when done with it.
- */
-{
-    int i;
-
-    /* count the directories, which are in front */
-    *nd = 0;
-    while ((*nd < n) && (S_ISDIR(d[*nd].filestatus.st_mode))) (*nd)++;
-    *names = (char **) malloc( *nd * sizeof(char *) );
-    for (i=0; i<*nd; i++) {
-	(*names)[i] = (char *) malloc( strlen(d[i].filename) + 1);
-	strcpy((*names)[i], d[i].filename);
-    }
-
-    return;
-} /* get_directories() */
-
-void
-get_filenames(DirList *d, int n, char ***names, int *nf)
-/*
- * Desc: return the filenames in <dir> as an arry in
- *  	 <names>, the # of entries in <nf>, memory allocated
- *	 to *names should be freed when done.
- */
-{
-    int nd, i;
-
-    /* the # of regular files is the total # of files - # of directories */
-    /* count the # of directories */
-    nd = 0;
-    while ((nd < n) && (S_ISDIR(d[nd].filestatus.st_mode))) nd++;
-
-    *names = (char **) malloc( (n-nd) * sizeof(char *) );
-    *nf = n - nd;
-    for (i=0; i<*nf; i++) {
-	(*names)[i] = (char *) malloc( strlen(d[i+nd].filename) + 1);
-	strcpy((*names)[i], d[i+nd].filename);
-    }
-
-    return;
-} /* get_filenames() */
-
-void
-FreeNames(char **names, int n)
-/*
- * Desc: free the space occupied by names
- */
-{
-    int i;
-
-     /* free the space occupied by names */
-    for (i=0; i<n; i++) {
-	free(names[i]);
-    }
-    free(names);
-
-    return;
-} /* FreeNames() */
-
-int
-dialog_dselect_old(void)
-/*
- * Desc: starting from the current directory,
- *	 choose a new current directory
- */
-{
-    DirList		*d = NULL;
-    char		**names, old_dir[MAXPATHLEN];
-    WINDOW		*ds_win;
-    ButtonObj		*okbut, *cancelbut;
-    ListObj		*dirs_obj;
-    StringObj		*dir_obj;
-    char		o_dir[MAXPATHLEN];
-    struct ComposeObj	*obj = NULL;
-    int			n, nd, okbutton, cancelbutton,
-			quit, cancel, ret;
-
-    ds_win = newwin(LINES-8, COLS-30, 4, 15);
-    if (ds_win == NULL) {
-	fprintf(stderr, "\nnewwin(%d,%d,%d,%d) failed, maybe wrong dims\n",
- 		LINES-8, COLS-30, 4, 15);
-	exit(1);
-    }
-    draw_box(ds_win, 0, 0, LINES-8, COLS-30, dialog_attr, border_attr);
-    wattrset(ds_win, dialog_attr);
-    mvwaddstr(ds_win, 0, (COLS-30)/2 - 9, " Directory Select ");
-    draw_shadow(stdscr, 4, 15, LINES-8, COLS-30);
-    display_helpline(ds_win, LINES-9, COLS-30);
-
-    /* the Directory string input field */
-    getcwd(o_dir, MAXPATHLEN);
-    dir_obj = NewStringObj(ds_win, "Directory:", o_dir, 1, 2, COLS-34, MAXPATHLEN-1);
-    AddObj(&obj, STRINGOBJ, (void *) dir_obj);
-
-    /* the list of directories */
-    get_dir(".", "*", &d, &n);
-    get_directories(d, n, &names, &nd);
-    dirs_obj = NewListObj(ds_win, "Directories:", names, o_dir, 5, 2,
-			  LINES-15, COLS-48, nd);
-    AddObj(&obj, LISTOBJ, (void *) dirs_obj);
-
-    /* the Ok-button */
-    okbutton = FALSE;
-    okbut = NewButtonObj(ds_win, "Continue", &okbutton, 7, COLS-45);
-    AddObj(&obj, BUTTONOBJ, (void *) okbut);
-
-    /* the Cancel-button */
-    cancelbutton = FALSE;
-    cancelbut = NewButtonObj(ds_win, "Return", &cancelbutton, 11, COLS-44);
-    AddObj(&obj, BUTTONOBJ, (void *) cancelbut);
-
-    quit = FALSE;
-    cancel = FALSE;
-    strcpy(old_dir, o_dir);
-    while (!quit) {
-	ret = PollObj(&obj);
-	switch(ret) {
-	case SEL_BUTTON:
-	    if (okbutton) {
-		quit = TRUE;
-	    }
-	    if (cancelbutton) {
-		quit = TRUE;
-		cancel = TRUE;
-	    }
-	    break;
-	case SEL_CR:
-	    if (strcmp(old_dir, o_dir)) {
-		/* the directory was changed, cd into it */
-		if (chdir(o_dir)) {
-		    dialog_notify("Could not change into directory");
-		    strcpy(o_dir, old_dir);
-		} else {
-		    getcwd(o_dir, MAXPATHLEN);
-		    strcpy(old_dir, o_dir);
-		}
-		RefreshStringObj(dir_obj);
-	    }
-	    get_dir(".", "*", &d, &n);
-	    FreeNames(names, nd);
-	    get_directories(d, n, &names, &nd);
-	    UpdateListObj(dirs_obj, names, nd);
-	    if (((obj->prev)->obj == (void *) dirs_obj)) {
-		obj=obj->prev;
-	    }
-	    break;
-	case SEL_ESC:
-	    quit = TRUE;
-	    cancel = TRUE;
-	    break;
-	case KEY_F(1):
-	    display_helpfile();
-	    break;
-	}
-    }
-
-    FreeNames(names, nd);
-    DelObj(obj);
-    delwin(ds_win);
-
-    return(cancel);
-
-} /* dialog_dselect() */
-
-int
-dialog_dselect(char *dir, char *fmask)
-/*
- * Desc: Choose a directory
- */
-{
-    if (dialog_dfselect(dir, fmask, FALSE)) {
-	return(FALSE);	/* esc or cancel was pressed */
-    } else {
-	return(TRUE);   /* directory was selected */
-    }
-} /* dialog_dselect() */
-
-char *
-dialog_fselect(char *dir, char *fmask)
-/*
- * Desc: Choose a file from a directory
- */
-{
-    return(dialog_dfselect(dir, fmask, TRUE));
-} /* dialog_fselect() */
-
-char *
-dialog_dfselect(char *dir, char *fmask, int is_fselect)
-/*
- * Desc: choose a file from the directory <dir>, which
- *	 initially display files with the mask <filemask>
- * pre:  <dir> is the initial directory
- *	 only files corresponding to the mask <fmask> are displayed
- * post: returns NULL if no file was selected
- *       else returns pointer to filename, space is allocated, should
- *       be freed after use.
- */
-{
-    DirList 		*d = NULL;
-    char		msg[512];
-    char		**fnames, **dnames, *ret_name;
-    WINDOW		*fs_win;
-    int			n, nd, nf, ret;
-    StringObj		*fm_obj, *dir_obj, *sel_obj;
-    char		o_fm[255], o_dir[MAXPATHLEN], o_sel[MAXPATHLEN];
-    char		old_fmask[255], old_dir[MAXPATHLEN];
-    ListObj		*dirs_obj,   *files_obj;
-    struct ComposeObj	*obj = NULL, *o;
-    int 		quit, cancel;
-    ButtonObj		*okbut_obj, *canbut_obj;
-    int			ok_button, cancel_button;
-
-    if (chdir(dir)) {
-	sprintf(msg, "Could not move into specified directory: %s", dir);
-	dialog_notify(msg);
-	return(NULL);
-    }
-    getcwd(o_dir, MAXPATHLEN);
-
-    /* setup the fileselect-window and initialize its components */
-    fs_win = newwin(LINES-2, COLS-20, 1, 10);
-    if (fs_win == NULL) {
-	endwin();
-	fprintf(stderr, "\nnewwin(%d,%d,%d,%d) failed, maybe wrong dims\n",
-		LINES-2, COLS-20, 2, 10);
-	exit(1);
-    }
-    draw_box(fs_win, 0, 0, LINES-2, COLS-20, dialog_attr, border_attr);
-    wattrset(fs_win, dialog_attr);
-    if (is_fselect) {
-	mvwaddstr(fs_win, 0, (COLS-20)/2 - 7, " File Select ");
-    } else {
-	mvwaddstr(fs_win, 0, (COLS-20)/2 - 9, " Directory Select ");
-    }
-    draw_shadow(stdscr, 1, 10, LINES-2, COLS-20);
-    display_helpline(fs_win, LINES-3, COLS-20);
-
-    /* Filemask entry */
-    strcpy(o_fm, fmask);
-    fm_obj = NewStringObj(fs_win, "Filemask:", o_fm, 1, 2, 19, 255);
-    AddObj(&obj, STRINGOBJ, (void *) fm_obj);
-
-    /* Directory entry */
-    dir_obj = NewStringObj(fs_win, "Directory:", o_dir, 1, 22, COLS-44, 255);
-    AddObj(&obj, STRINGOBJ, (void *) dir_obj);
-
-    /* Directory list */
-    get_dir(".", fmask, &d, &n);	/* read the entire directory */
-    get_directories(d, n, &dnames, &nd); /* extract the dir-entries */
-    if (is_fselect) {
-	dirs_obj = NewListObj(fs_win, "Directories:", dnames, o_dir, 5, 2,
-			      LINES-16, (COLS-20)/2-2, nd);
-    } else {
-	dirs_obj = NewListObj(fs_win, "Directories:", dnames, o_dir, 5, 2,
-			      LINES-12, (COLS-20)/2-2, nd);
-    }
-    AddObj(&obj, LISTOBJ, (void *) dirs_obj);
-
-    /* Filenames list */
-    get_filenames(d, n, &fnames, &nf);		/* extract the filenames */
-    if (is_fselect) {
-	files_obj = NewListObj(fs_win, "Files:", fnames, o_sel, 5, (COLS-20)/2+1,
-			       LINES-16, (COLS-20)/2-3, nf);
-    } else {
-	files_obj = NewListObj(fs_win, "Files:", fnames, o_sel, 5, (COLS-20)/2+1,
-			       LINES-12, (COLS-20)/2-3, nf);
-    }
-    AddObj(&obj, LISTOBJ, (void *) files_obj);
-
-    if (is_fselect) {
-	/* Selection entry */
-	o_sel[0] = '\0';
-	sel_obj = NewStringObj(fs_win, "Selection:", o_sel, LINES-10, 2, COLS-24, 255);
-	AddObj(&obj, STRINGOBJ, (void *) sel_obj);
-    }
-
-    /* Ok button */
-    ok_button = FALSE;
-    okbut_obj = NewButtonObj(fs_win, "Ok", &ok_button, LINES-6, 20);
-    AddObj(&obj, BUTTONOBJ, (void *) okbut_obj);
-
-    /* Cancel button */
-    cancel_button = FALSE;
-    canbut_obj = NewButtonObj(fs_win, "Cancel", &cancel_button, LINES-6, 30);
-    AddObj(&obj, BUTTONOBJ, (void *) canbut_obj);
-
-    /* Make sure all objects on the window are drawn */
-    wrefresh(fs_win);
-    keypad(fs_win, TRUE);
-
-    /* Start the reading */
-    o = obj;
-    strcpy(old_fmask, o_fm);
-    strcpy(old_dir, o_dir);
-    quit = FALSE;
-    cancel = FALSE;
-    while (!quit) {
-	ret = PollObj(&o);
-	switch(ret) {
-	case SEL_CR:
-	    if (strcmp(old_fmask, o_fm) || strcmp(old_dir, o_dir)) {
-		/* reread directory and update the listobjects */
-		if (strcmp(old_dir, o_dir)) { /* dir entry was changed */
-		    if (chdir(o_dir)) {
-			dialog_notify("Could not change into directory");
-			strcpy(o_dir, old_dir);
-		    } else {
-			getcwd(o_dir, MAXPATHLEN);
-			strcpy(old_dir, o_dir);
-		    }
-		    RefreshStringObj(dir_obj);
-		} else {		      /* fmask entry was changed */
-		    strcpy(old_fmask, o_fm);
-		}
-		get_dir(".", o_fm, &d, &n);
-		FreeNames(dnames, nd);
-		get_directories(d, n, &dnames, &nd);
-		UpdateListObj(dirs_obj, dnames, nd);
-		FreeNames(fnames, nf);
-		get_filenames(d, n, &fnames, &nf);
-		UpdateListObj(files_obj, fnames, nf);
-		if (((o->prev)->obj == (void *) dirs_obj)) {
-		    o=o->prev;
-		}
-	    }
-	    break;
-	case SEL_BUTTON:
-	    /* check which button was pressed */
-	    if (ok_button) {
-		quit = TRUE;
-	    }
-	    if (cancel_button) {
-		quit = TRUE;
-		cancel = TRUE;
-	    }
-	    break;
-	case SEL_ESC:
-	    quit = TRUE;
-	    cancel = TRUE;
-	    break;
-	case KEY_F(1):
-	case '?':
-	    display_helpfile();
-	    break;
-	}
-    }
-    DelObj(obj);
-    FreeNames(dnames, nd);
-    FreeNames(fnames, nf);
-    delwin(fs_win);
-
-    if (cancel || (strlen(o_sel) == 0)) {
-	return(NULL);
-    } else {
-	ret_name = (char *) malloc( strlen(o_sel) + 1 );
-	strcpy(ret_name, o_sel);
-	return(ret_name);
-    }
-} /* dialog_fselect() */
-
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/gauge.c
--- a/head/gnu/lib/libodialog/gauge.c	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,79 +0,0 @@
-/*
- * gauge.c
- *
- * progress indicator for libdialog
- *
- *
- * Copyright (c) 1995, Marc van Kempen
- *
- * All rights reserved.
- *
- * This software may be used, modified, copied, distributed, and
- * sold, in both source and binary form provided that the above
- * copyright and these terms are retained, verbatim, as the first
- * lines of this file.  Under no circumstances is the author
- * responsible for the proper functioning of this software, nor does
- * the author assume any responsibility for damages incurred with
- * its use.
- */
-
-#include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
-
-#include <stdlib.h>
-#include <string.h>
-
-#include "dialog.h"
-
-void
-dialog_gauge(char *title, char *prompt, int y, int x,
-	     int height, int width, int perc)
-/*
- * Desc: display a progress bar, progress indicated by <perc>
- */
-{
-    WINDOW 	*gw;
-    int		glen, i;
-    char	percs[5];
-
-    gw = newwin(height, width, y, x);
-    if (!gw) {
-	fprintf(stderr, "dialog_gauge: Error creating window (%d, %d, %d, %d)",
-		height, width, y, x);
-	exit(-1);
-    }
-
-    draw_box(gw, 0, 0, height, width, dialog_attr, border_attr);
-    draw_shadow(stdscr, y, x, height, width);
-
-    wattrset(gw, title_attr);
-    if (title) {
-	wmove(gw, 0, (width - strlen(title))/2 - 1);
-	waddstr(gw, "[ ");
-	waddstr(gw, title);
-	waddstr(gw, " ]");
-    }
-    wattrset(gw, dialog_attr);
-    if (prompt) {
-	wmove(gw, 1, (width - strlen(prompt))/2 - 1);
-	waddstr(gw, prompt);
-    }
-
-    draw_box(gw, 2, 2, 3, width-4, dialog_attr, border_attr);
-    glen = (int) ((float) perc/100 * (width-6));
-
-    wattrset(gw, dialog_attr);
-    sprintf(percs, "%3d%%", perc);
-    wmove(gw, 5, width/2 - 2);
-    waddstr(gw, percs);
-
-    wattrset(gw, A_BOLD);
-    wmove(gw, 3, 3);
-    for (i=0; i<glen; i++) waddch(gw, ' ');
-
-    wrefresh(gw);
-    delwin(gw);
-
-    return;
-} /* dialog_gauge() */
-
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/help.c
--- a/head/gnu/lib/libodialog/help.c	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,194 +0,0 @@
-/***************************************************************
- *
- * Program:	help.c
- * Author:	Marc van Kempen
- * Desc:	get help
- *
- *
- * Copyright (c) 1995, Marc van Kempen
- *
- * All rights reserved.
- *
- * This software may be used, modified, copied, distributed, and
- * sold, in both source and binary form provided that the above
- * copyright and these terms are retained, verbatim, as the first
- * lines of this file.  Under no circumstances is the author
- * responsible for the proper functioning of this software, nor does
- * the author assume any responsibility for damages incurred with
- * its use.
- *
- ***************************************************************/
-
-#include <stdlib.h>
-#include <sys/param.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <string.h>
-#include <dialog.h>
-
-static char	_helpfilebuf[MAXPATHLEN];
-static char	_helplinebuf[77];	  /* limit the helpline to 76 characters */
-static char	*_helpfile = NULL;
-static char	*_helpline = NULL;
-
-/******************************************************************
- *
- * 	helpfile routines
- *
- ******************************************************************/
-
-void
-use_helpfile(char *hfile)
-/*
- * desc: set the helpfile to be opened on pressing F1 to <helpfile>
- */
-{
-    if (hfile != NULL) {
-	_helpfile = _helpfilebuf;
-	strcpy(_helpfile, hfile);
-    } else {
-	_helpfile = NULL;
-    }
-
-    return;
-} /* use_helpfile() */
-
-void
-display_helpfile(void)
-/*
- * desc: display the current helpfile in a window
- */
-{
-    WINDOW	*w;
-    FILE	*f;
-    struct stat sb;
-    char	msg[80], *buf;
-    static int	in_help = FALSE;
-    char        *savehline = NULL;
-
-    if (in_help) return;	/* dont call help when you're in help */
-
-    if (_helpfile != NULL) {
-	if ((w = dupwin(newscr)) == NULL) {
-	    dialog_notify("No memory to dup previous screen\n");
-	    return;
-	}
-	if ((f = fopen(_helpfile, "r")) == NULL) {
-	    sprintf(msg, "Can't open helpfile : %s\n", _helpfile);
-	    dialog_notify(msg);
-	    return;
-	}
-	if (fstat(fileno(f), &sb)) {
-	    sprintf(msg, "Can't stat helpfile : %s\n", _helpfile);
-	    dialog_notify(msg);
-	    return;
-	}
-	if ((buf = (char *) malloc( sb.st_size )) == NULL) {
-	    sprintf(msg, "Could not malloc space for helpfile : %s\n", _helpfile);
-	    dialog_notify(msg);
-	    return;
-	}
-	if (fread(buf, 1, sb.st_size, f) != sb.st_size) {
-	    sprintf(msg, "Could not read entire help file : %s", _helpfile);
-	    dialog_notify(msg);
-	    free(buf);
-	    return;
-	}
-	buf[sb.st_size] = 0;
-	in_help = TRUE;
-	savehline = get_helpline();
-	use_helpline("Use arrowkeys, PgUp, PgDn, Home and End to move through text");
-	dialog_mesgbox("Online help", buf, LINES-4, COLS-4);
-	restore_helpline(savehline);
-	in_help = FALSE;
-	touchwin(w);
-	wrefresh(w);
-	delwin(w);
-	free(buf);
-    } else {
-	/* do nothing */
-    }
-
-    return;
-} /* display_helpfile() */
-
-
-/******************************************************************
- *
- * 	helpline routines
- *
- ******************************************************************/
-
-void
-use_helpline(char *hline)
-/*
- * desc: set the helpline to printed in dialogs
- */
-{
-    if (hline) {
-	_helpline = _helplinebuf;
-	if (strlen(hline) > 76) {
-	    /* only display the first 76 characters in the helpline */
-	    strncpy(_helpline, hline, 76);
-	    _helpline[76] = 0;
-	} else {
-	    strcpy(_helpline, hline);
-	}
-    } else {
-	_helpline = NULL;
-    }
-
-    return;
-} /* use_helpline() */
-
-void
-display_helpline(WINDOW *w, int y, int width)
-/*
- * desc: display the helpline at the given coordinates <y, x> in the window <w>
- */
-{
-    if (_helpline != NULL) {
-	if (strlen(_helpline) > width - 6) {
-	    _helpline[width - 6] = 0;
-	}
-	wmove(w, y, (int) (width - strlen(_helpline)- 4) / 2);
-	wattrset(w, title_attr);
-	waddstr(w, "[ ");
-	waddstr(w, _helpline);
-	waddstr(w, " ]");
-    } else {
-	/* do nothing */
-    }
-
-    return;
-}
-
-char *
-get_helpline(void)
-/*
- * desc: allocate new space, copy the helpline to it and return a pointer to it
- */
-{
-    char *hlp;
-
-    if (_helpline) {
-        hlp = (char *) malloc( strlen(_helpline) + 1 );
-        strcpy(hlp, _helpline);
-    } else {
-        hlp = NULL;
-    }
-
-    return(hlp);
-} /* get_helpline() */
-
-void
-restore_helpline(char *helpline)
-/*
- * Desc: set the helpline to <helpline> and free the space allocated to it
- */
-{
-    use_helpline(helpline);
-    free(helpline);
-
-    return;
-} /* restore_helpline() */
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/inputbox.c
--- a/head/gnu/lib/libodialog/inputbox.c	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,190 +0,0 @@
-/*
- *  inputbox.c -- implements the input box
- *
- *  AUTHOR: Savio Lam (lam836 at cs.cuhk.hk)
- *
- *  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., 675 Mass Ave, Cambridge, MA 02139, USA.
- */
-
-
-#include <dialog.h>
-#include "dialog.priv.h"
-
-
-/*
- * Display a dialog box for inputing a string
- */
-int dialog_inputbox(unsigned char *title, unsigned char *prompt, int height, int width, unsigned char *result)
-{
-  int i, j, x, y, box_y, box_x, box_width, first,
-      key = 0, button = -1;
-  unsigned char instr[MAX_LEN+1];
-  WINDOW *dialog;
-
-  if (height < 0)
-	height = strheight(prompt)+2+4;
-  if (width < 0) {
-	i = strwidth(prompt);
-	j = ((title != NULL) ? strwidth(title) : 0);
-	width = MAX(i,j) + 4;
-  }
-  width = MAX(width,24);
-
-  if (width > COLS)
-	width = COLS;
-  if (height > LINES)
-	height = LINES;
-  /* center dialog box on screen */
-  x = DialogX ? DialogX : (COLS - width)/2;
-  y = DialogY ? DialogY : (LINES - height)/2;
-
-#ifdef HAVE_NCURSES
-  if (use_shadow)
-    draw_shadow(stdscr, y, x, height, width);
-#endif
-  dialog = newwin(height, width, y, x);
-  if (dialog == NULL) {
-    endwin();
-    fprintf(stderr, "\nnewwin(%d,%d,%d,%d) failed, maybe wrong dims\n", height,width,y,x);
-    exit(1);
-  }
-  keypad(dialog, TRUE);
-
-  draw_box(dialog, 0, 0, height, width, dialog_attr, border_attr);
-  wattrset(dialog, border_attr);
-  wmove(dialog, height-3, 0);
-  waddch(dialog, ACS_LTEE);
-  for (i = 0; i < width-2; i++)
-    waddch(dialog, ACS_HLINE);
-  wattrset(dialog, dialog_attr);
-  waddch(dialog, ACS_RTEE);
-  wmove(dialog, height-2, 1);
-  for (i = 0; i < width-2; i++)
-    waddch(dialog, ' ');
-
-  if (title != NULL) {
-    wattrset(dialog, title_attr);
-    wmove(dialog, 0, (width - strlen(title))/2 - 1);
-    waddch(dialog, ' ');
-    waddstr(dialog, title);
-    waddch(dialog, ' ');
-  }
-  wattrset(dialog, dialog_attr);
-  wmove(dialog, 1, 2);
-  print_autowrap(dialog, prompt, height-1, width-2, width, 1, 2, TRUE, FALSE);
-
-  /* Draw the input field box */
-  box_width = width-6;
-  getyx(dialog, y, x);
-  box_y = y + 2;
-  box_x = (width - box_width)/2;
-  draw_box(dialog, y+1, box_x-1, 3, box_width+2, border_attr, dialog_attr);
-
-  display_helpline(dialog, height-1, width);
-
-  x = width/2-11;
-  y = height-2;
-  print_button(dialog, "Cancel", y, x+14, FALSE);
-  print_button(dialog, "  OK  ", y, x, TRUE);
-
-  first = 1;
-  strcpy(instr, result);
-  wattrset(dialog, dialog_attr);
-
-  while (key != ESC) {
-
-    if (button == -1) {    /* Input box selected */
-      key = line_edit(dialog, box_y, box_x, -1, box_width, inputbox_attr, first, instr, DialogInputAttrs);
-      first = 0;
-    }
-    else
-      key = wgetch(dialog);
-
-    switch (key) {
-      case 'O':
-      case 'o':
-        delwin(dialog);
-	strcpy(result, instr);
-        return 0;
-      case 'C':
-      case 'c':
-        delwin(dialog);
-        return 1;
-      case KEY_UP:
-      case KEY_LEFT:
-      case KEY_BTAB:
-        switch (button) {
-	  case -1:
-            button = 1;    /* Indicates "Cancel" button is selected */
-	    print_button(dialog, "  OK  ", y, x, FALSE);
-	    print_button(dialog, "Cancel", y, x+14, TRUE);
-            wrefresh(dialog);
-	    break;
-          case 0:
-            button = -1;   /* Indicates input box is selected */
-	    print_button(dialog, "Cancel", y, x+14, FALSE);
-	    print_button(dialog, "  OK  ", y, x, TRUE);
-            break;
-          case 1:
-	    button = 0;    /* Indicates "OK" button is selected */
-	    print_button(dialog, "Cancel", y, x+14, FALSE);
-	    print_button(dialog, "  OK  ", y, x, TRUE);
-            wrefresh(dialog);
-            break;
-        }
-        break;
-      case TAB:
-      case KEY_DOWN:
-      case KEY_RIGHT:
-        switch (button) {
-	  case -1:
-	    button = 0;    /* Indicates "OK" button is selected */
-	    print_button(dialog, "Cancel", y, x+14, FALSE);
-	    print_button(dialog, "  OK  ", y, x, TRUE);
-            wrefresh(dialog);
-            break;
-          case 0:
-            button = 1;    /* Indicates "Cancel" button is selected */
-	    print_button(dialog, "  OK  ", y, x, FALSE);
-	    print_button(dialog, "Cancel", y, x+14, TRUE);
-            wrefresh(dialog);
-	    break;
-          case 1:
-            button = -1;   /* Indicates input box is selected */
-	    print_button(dialog, "Cancel", y, x+14, FALSE);
-	    print_button(dialog, "  OK  ", y, x, TRUE);
-            break;
-        }
-        break;
-      case ' ':
-      case '\n':
-      case '\r':
-        delwin(dialog);
-	if (button < 1)
-	  strcpy(result, instr);
-        return (button == -1 ? 0 : button);
-      case ESC:
-        break;
-    case KEY_F(1):
-    case '?':
-	display_helpfile();
-	break;
-    }
-  }
-
-  delwin(dialog);
-  return -1;    /* ESC pressed */
-}
-/* End of dialog_inputbox() */
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/kernel.c
--- a/head/gnu/lib/libodialog/kernel.c	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,536 +0,0 @@
-/*
- *  dialog - Display simple dialog boxes from shell scripts
- *
- *  AUTHOR: Savio Lam (lam836 at cs.cuhk.hk)
- *
- *  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., 675 Mass Ave, Cambridge, MA 02139, USA.
- *
- *
- *  HISTORY:
- *
- *  17/12/93 - Version 0.1 released.
- *
- *  19/12/93 - menu will now scroll if there are more items than can fit
- *             on the screen.
- *           - added 'checklist', a dialog box with a list of options that
- *             can be turned on or off. A list of options that are on is
- *             returned on exit.
- *
- *  20/12/93 - Version 0.15 released.
- *
- *  29/12/93 - Incorporated patch from Patrick J. Volkerding
- *             (volkerdi at mhd1.moorhead.msus.edu) that made these changes:
- *             - increased MAX_LEN to 2048
- *             - added 'infobox', equivalent to a message box without pausing
- *             - added option '--clear' that will clear the screen
- *             - Explicit line breaking when printing prompt text can be
- *               invoked by real newline '\n' besides the string "\n"
- *           - an optional parameter '--title <string>' can be used to
- *             specify a title string for the dialog box
- *
- *  03/01/94 - added 'textbox', a dialog box for displaying text from a file.
- *           - Version 0.2 released.
- *
- *  04/01/94 - some fixes and improvements for 'textbox':
- *             - fixed a bug that will cause a segmentation violation when a
- *               line is longer than MAX_LEN characters. Lines will now be
- *               truncated if they are longer than MAX_LEN characters.
- *             - removed wrefresh() from print_line(). This will increase
- *               efficiency of print_page() which calls print_line().
- *             - display current position in the form of percentage into file.
- *           - Version 0.21 released.
- *
- *  05/01/94 - some changes for faster screen update.
- *
- *  07/01/94 - much more flexible color settings. Can use all 16 colors
- *             (8 normal, 8 highlight) of the Linux console.
- *
- *  08/01/94 - added run-time configuration using configuration file.
- *
- *  09/01/94 - some minor bug fixes and cleanups for menubox, checklist and
- *             textbox.
- *
- *  11/01/94 - added a man page.
- *
- *  13/01/94 - some changes for easier porting to other Unix systems (tested
- *             on Ultrix, SunOS and HPUX)
- *           - Version 0.3 released.
- *
- *  08/06/94 - Patches by Stuart Herbert - S.Herbert at shef.ac.uk
- * 	       Fixed attr_clear and the textbox stuff to work with ncurses 1.8.5
- * 	       Fixed the wordwrap routine - it'll actually wrap properly now
- *	       Added a more 3D look to everything - having your own rc file could
- *	         prove 'interesting' to say the least :-)
- *             Added radiolist option
- *	     - Version 0.4 released.
- */
-
-#include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
-
-#define __DIALOG_MAIN__
-
-#include <dialog.h>
-#include <err.h>
-#include "dialog.priv.h"
-#ifdef HAVE_NCURSES
-#include "colors.h"
-#endif
-
-/* These are two "secret" globals that can be fiddled to make a dialog
- * come up someplace other than a "centered" calculation for X,Y
- */
-int DialogX, DialogY;
-
-/* This "secret" global allows you to change the behavior of an input field */
-int DialogInputAttrs;
-
-/*
- * Do some initialization for dialog
- */
-void init_dialog(void)
-{
-
-  if (issetugid()) {
-	errx(1, "libdialog is unsafe to use in setugid applications");
-  }
-
-#if defined(LOCALE)
-  (void) setlocale(LC_ALL, "");
-#endif
-
-#ifdef HAVE_NCURSES
-  if (parse_rc() == -1)    /* Read the configuration file */
-    exit(-1);
-#endif
-
-  if (initscr() == NULL) { /* Init curses */
-    fprintf(stderr, "\nCurses initialization error.\n");
-    exit(-1);
-  }
-  keypad(stdscr, TRUE);
-  cbreak();
-  noecho();
-
-#ifdef HAVE_NCURSES
-  if (use_colors || use_shadow)    /* Set up colors */
-    color_setup();
-#endif
-
-  /* Set screen to screen attribute */
-  dialog_clear_norefresh();
-  DialogX = DialogY = 0;
-}
-/* End of init_dialog() */
-
-
-#ifdef HAVE_NCURSES
-/*
- * Setup for color display
- */
-void color_setup(void)
-{
-  int i;
-
-  if (has_colors()) {    /* Terminal supports color? */
-    start_color();
-
-    /* Initialize color pairs */
-    for (i = 0; i < ATTRIBUTE_COUNT; i++)
-      init_pair(i+1, color_table[i][0], color_table[i][1]);
-
-    /* Setup color attributes */
-    for (i = 0; i < ATTRIBUTE_COUNT; i++)
-      attributes[i] = C_ATTR(color_table[i][2], i+1);
-  }
-}
-/* End of color_setup() */
-#endif
-
-
-/*
- * Set window to attribute 'attr'
- */
-void attr_clear(WINDOW *win, int height, int width, chtype attr)
-{
-  int i, j;
-
-  wattrset(win, attr);    /* Set window to attribute 'attr' */
-  for (i = 0; i < height; i++) {
-    wmove(win, i, 0);
-    for (j = 0; j < width; j++)
-      waddch(win, ' ');
-  }
-}
-/* End of attr_clear() */
-
-
-/*
- * Print a string of text in a window, automatically wrap around to the
- * next line if the string is too long to fit on one line. Note that the
- * string may contain "\n" to represent a newline character or the real
- * newline '\n', but in that case, auto wrap around will be disabled.
- */
-void print_autowrap(WINDOW *win, unsigned char *prompt, int height, int width, int maxwidth, int y, int x, int center, int rawmode)
-{
-  int cur_x, cur_y, i;
-  unsigned char tempstr[MAX_LEN+1], *word, *tempptr, *tempptr1;
-  chtype ostuff[132], attrs = 0, init_bottom = 0;
-
-  wsetscrreg(win, y, height);
-  getyx(win, cur_y, cur_x);
-
-  strncpy(tempstr, prompt, MAX_LEN);
-  tempstr[MAX_LEN] = '\0';
-  if ((!rawmode && strstr(tempstr, "\\n") != NULL) ||
-      (strchr(tempstr, '\n') != NULL)) {    /* Prompt contains "\n" or '\n' */
-    word = tempstr;
-    while (1) {
-      tempptr = rawmode ? NULL : strstr(word, "\\n");
-      tempptr1 = strchr(word, '\n');
-      if (tempptr == NULL && tempptr1 == NULL)
-        break;
-      else if (tempptr == NULL) {    /* No more "\n" */
-        tempptr = tempptr1;
-        tempptr[0] = '\0';
-      }
-      else if (tempptr1 == NULL) {    /* No more '\n' */
-        tempptr[0] = '\0';
-        tempptr++;
-      }
-      else {    /* Prompt contains both "\n" and '\n' */
-        if (strlen(tempptr)-2 < strlen(tempptr1)-1) {
-          tempptr = tempptr1;
-          tempptr[0] = '\0';
-        }
-        else {
-          tempptr[0] = '\0';
-          tempptr++;
-        }
-      }
-
-      waddstr(win, word);
-      word = tempptr + 1;
-      if (++cur_y > height) {
-	cur_y--;
-	if (!init_bottom) {
-	  for (i = 0; i < x; i++)
-	    ostuff[i] = mvwinch(win, cur_y, i);
-	  for (i = width; i < maxwidth; i++)
-	    ostuff[i] = mvwinch(win, cur_y, i);
-	  attrs = getattrs(win);
-	  init_bottom = 1;
-	}
-	scrollok(win, TRUE);
-	scroll(win);
-	scrollok(win, FALSE);
-	wmove(win, cur_y, 0);
-	for (i = 0; i < x; i++) {
-	  wattrset(win, ostuff[i]&A_ATTRIBUTES);
-	  waddch(win, ostuff[i]);
-	}
-	wattrset(win, attrs);
-	for ( ; i < width; i++)
-	  waddch(win, ' ');
-	for ( ; i < maxwidth; i++) {
-	  wattrset(win, ostuff[i]&A_ATTRIBUTES);
-	  waddch(win, ostuff[i]);
-	}
-	wattrset(win, attrs);
-	wrefresh(win);
-      }
-      wmove(win, cur_y, cur_x = x);
-    }
-    waddstr(win, word);
-  }
-  else if (center && strlen(tempstr) <= width-x*2) {    /* If prompt is short */
-    wmove(win, cur_y, (width - strlen(tempstr)) / 2);
-    waddstr(win, tempstr);
-  }
-  else if (!center && strlen(tempstr) <= width-cur_x) {    /* If prompt is short */
-    waddstr(win, tempstr);
-  }
-  else {
-    char *p = tempstr;
-
-    /* Print prompt word by word, wrap around if necessary */
-    while ((word = strsep(&p, "\t\n ")) != NULL) {
-      int loop;
-      unsigned char sc;
-
-      if (*word == '\0')
-	continue;
-      do {
-	loop = 0;
-	if (cur_x+strlen(word) >= width+1) {    /* wrap around to next line */
-	  if (x+strlen(word) >= width+1) {
-	    sc = word[width-cur_x-1];
-	    word[width-cur_x-1] = '\0';
-	    wmove(win, cur_y, cur_x);
-	    waddstr(win, word);
-	    word[width-cur_x-1] = sc;
-	    word += width-cur_x-1;
-	    getyx(win, cur_y, cur_x);
-	    loop = 1;
-	  }
-	  cur_y++;
-	  cur_x = x;
-	  if (cur_y > height) {
-	    cur_y--;
-	    if (!init_bottom) {
-	      for (i = 0; i < x; i++)
-		ostuff[i] = mvwinch(win, cur_y, i);
-	      for (i = width; i < maxwidth; i++)
-		ostuff[i] = mvwinch(win, cur_y, i);
-	      attrs = getattrs(win);
-	      init_bottom = 1;
-	    }
-	    scrollok(win, TRUE);
-	    scroll(win);
-	    scrollok(win, FALSE);
-	    wmove(win, cur_y, 0);
-	    for (i = 0; i < x; i++) {
-	      wattrset(win, ostuff[i]&A_ATTRIBUTES);
-	      waddch(win, ostuff[i]);
-	    }
-	    wattrset(win, attrs);
-	    for ( ; i < width; i++)
-	      waddch(win, ' ');
-	    for ( ; i < maxwidth; i++) {
-	      wattrset(win, ostuff[i]&A_ATTRIBUTES);
-	      waddch(win, ostuff[i]);
-	    }
-	    wattrset(win, attrs);
-	    wrefresh(win);
-	  }
-	}
-      }
-      while(loop);
-      wmove(win, cur_y, cur_x);
-      waddstr(win, word);
-      getyx(win, cur_y, cur_x);
-      cur_x++;
-    }
-  }
-}
-/* End of print_autowrap() */
-
-
-/*
- * Print a button
- */
-void print_button(WINDOW *win, unsigned char *label, int y, int x, int selected)
-{
-  int i, temp;
-
-  wmove(win, y, x);
-  wattrset(win, selected ? button_active_attr : button_inactive_attr);
-  waddstr(win, selected ? "[" : " ");
-  temp = strspn(label, " ");
-  label += temp;
-  for (i = 0; i < temp; i++)
-    waddch(win, ' ');
-  wattrset(win, selected ? button_key_active_attr : button_key_inactive_attr);
-  waddch(win, label[0]);
-  wattrset(win, selected ? button_active_attr : button_inactive_attr);
-  waddstr(win, label+1);
-  waddstr(win, selected ? "]" : " ");
-  wmove(win, y, x+temp+1);
-}
-/* End of print_button() */
-
-
-/*
- * Draw a rectangular box with line drawing characters
- */
-void draw_box(WINDOW *win, int y, int x, int height, int width, chtype box, chtype border)
-{
-  int i, j;
-
-  wattrset(win, 0);
-  for (i = 0; i < height; i++) {
-    wmove(win, y + i, x);
-    for (j = 0; j < width; j++)
-      if (!i && !j)
-        waddch(win, border | ACS_ULCORNER);
-      else if (i == height-1 && !j)
-        waddch(win, border | ACS_LLCORNER);
-      else if (!i && j == width-1)
-        waddch(win, box | ACS_URCORNER);
-      else if (i == height-1 && j == width-1)
-        waddch(win, box | ACS_LRCORNER);
-      else if (!i)
-        waddch(win, border | ACS_HLINE);
-      else if (i == height-1)
-        waddch(win, box | ACS_HLINE);
-      else if (!j)
-        waddch(win, border | ACS_VLINE);
-      else if (j == width-1)
-        waddch(win, box | ACS_VLINE);
-      else
-        waddch(win, box | ' ');
-  }
-}
-/* End of draw_box() */
-
-
-#ifdef HAVE_NCURSES
-/*
- * Draw shadows along the right and bottom edge to give a more 3D look
- * to the boxes
- */
-void draw_shadow(WINDOW *win, int y, int x, int height, int width)
-{
-  int i,sx,sy;
-  chtype attrs;
-
-  if (has_colors()) {    /* Whether terminal supports color? */
-    getbegyx(win,sy,sx);
-    attrs = getattrs(win);
-    if (y+height < getmaxy(win)) {
-	/* small touch */
-	wattrset(win, A_INVIS);
-	wmove(win, y + height, x + 2);
-	for (i = 0; i < width; i++)
-	    if (i+x+2 < getmaxx(win))
-	       waddch(win, ' ');
-	/* end touch */
-	wattrset(win, shadow_attr);
-	wmove(win, y + height, x + 2);
-	for (i = 0; i < width; i++)
-	    if (i+x+2 < getmaxx(win))
-	       waddch(win, mvwinch(newscr, sy+y+height, sx+x+2+i) & A_CHARTEXT);
-    }
-    if (x+width < getmaxx(win)) {
-	for (i = y + 1; i < y + height + 1; i++) {
-	  if (i < getmaxy(win)) {
-	      /* small touch */
-	      wattrset(win, A_INVIS);
-	      wmove(win, i, x + width);
-	      waddch(win, ' ');
-	      if (x+width+1 < getmaxx(win))
-		    waddch(win, ' ');
-	      /* end touch */
-	      wattrset(win, shadow_attr);
-	      wmove(win, i, x + width);
-	      waddch(win, mvwinch(newscr, sy+i, sx+x+width) & A_CHARTEXT);
-	      if (x+width+1 < getmaxx(win))
-		    waddch(win, mvwinch(newscr, sy+i, sx+x+width+1) & A_CHARTEXT);
-	  }
-	}
-    }
-    wattrset(win, attrs);
-    wnoutrefresh(win);
-  }
-}
-/* End of draw_shadow() */
-#endif
-
-void dialog_clear_norefresh(void)
-{
-    attr_clear(stdscr, LINES, COLS, screen_attr);
-    touchwin(stdscr);
-    wnoutrefresh(stdscr);
-}
-
-void dialog_clear(void)
-{
-    dialog_clear_norefresh();
-    doupdate();
-}
-
-void dialog_update(void)
-{
-    refresh();
-}
-
-void end_dialog(void)
-{
-    endwin();
-}
-
-int strwidth(const char *p)
-{
-	int i = 0, len, incr;
-	const char *start, *s, *s1, *s2;
-
-	for (start = s = p; ; start = (s += incr)) {
-		s1 = strchr(s, '\n');
-		s2 = strstr(s, "\\n");
-		if (s2 == NULL)
-			s = s1;
-		else if (s1 == NULL)
-			s = s2;
-		else
-			s = MIN(s1, s2);
-		if (s == NULL)
-			break;
-		incr = 1 + (s == s2);
-		len = s - start;
-		if (len > i)
-			i = len;
-	}
-	len = strlen(start);
-	if (len > i)
-		i = len;
-	return i;
-}
-
-int strheight(const char *p)
-{
-	int i = 1, incr;
-	const char *s, *s1, *s2;
-
-	for (s = p; ; s += incr) {
-		s1 = strchr(s, '\n');
-		s2 = strstr(s, "\\n");
-		if (s2 == NULL)
-			s = s1;
-		else if (s1 == NULL)
-			s = s2;
-		else
-			s = MIN(s1, s2);
-		if (s == NULL)
-			break;
-		incr = 1 + (s == s2);
-		i++;
-	}
-	return i;
-}
-
-void print_arrows(WINDOW *dialog, int scroll, int menu_height, int item_no,
-		  int box_x, int box_y, int tag_x, int cur_x, int cur_y)
-{
-    wmove(dialog, box_y, box_x + tag_x + 1);
-    wattrset(dialog, scroll ? uarrow_attr : menubox_attr);
-    waddch(dialog, scroll ? ACS_UARROW : ACS_HLINE);
-    wmove(dialog, box_y, box_x + tag_x + 2);
-    waddch(dialog, scroll ? '(' : ACS_HLINE);
-    wmove(dialog, box_y, box_x + tag_x + 3);
-    waddch(dialog, scroll ? '-' : ACS_HLINE);
-    wmove(dialog, box_y, box_x + tag_x + 4);
-    waddch(dialog, scroll ? ')' : ACS_HLINE);
-    wmove(dialog, box_y + menu_height + 1, box_x + tag_x + 1);
-    wattrset(dialog, scroll+menu_height < item_no ? darrow_attr : menubox_border_attr);
-    waddch(dialog, scroll+menu_height < item_no ? ACS_DARROW : ACS_HLINE);
-    wmove(dialog, box_y + menu_height + 1, box_x + tag_x + 2);
-    waddch(dialog, scroll+menu_height < item_no ? '(' : ACS_HLINE);
-    wmove(dialog, box_y + menu_height + 1, box_x + tag_x + 3);
-    waddch(dialog, scroll+menu_height < item_no ? '+' : ACS_HLINE);
-    wmove(dialog, box_y + menu_height + 1, box_x + tag_x + 4);
-    waddch(dialog, scroll+menu_height < item_no ? ')' : ACS_HLINE);
-    wmove(dialog, cur_y, cur_x);  /* Restore cursor position */
-}
-
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/lineedit.c
--- a/head/gnu/lib/libodialog/lineedit.c	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,213 +0,0 @@
-/*
- *  Changes Copyright (C) 1995 by Andrey A. Chernov, Moscow
- *
- *  Original Copyright:
- *
- *  AUTHOR: Savio Lam (lam836 at cs.cuhk.hk)
- *
- *  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., 675 Mass Ave, Cambridge, MA 02139, USA.
- */
-
-
-#include <dialog.h>
-#include "dialog.priv.h"
-
-static void redraw_field(WINDOW *dialog, int box_y, int box_x, int flen, int box_width, unsigned char instr[], int input_x, int scroll, chtype attr, chtype old_attr, int fexit, int attr_mask);
-
-/*
- * Line editor
- */
-int line_edit(WINDOW* dialog, int box_y, int box_x, int flen, int box_width, chtype attr, int first, unsigned char *result, int attr_mask)
-{
-  int i, key;
-  chtype old_attr;
-  static int input_x, scroll;
-  static unsigned char instr[MAX_LEN+1];
-  unsigned char erase_char = erasechar();
-  unsigned char kill_char = killchar();
-#ifdef notyet
-  unsignec char werase_char = cur_term->Ottyb.c_cc[VWERASE];
-#endif
-
-  old_attr = getattrs(dialog);
-  keypad(dialog, TRUE);
-
-  if (first) {
-    memset(instr, 0, sizeof(instr));
-    strcpy(instr, result);
-    i = strlen(instr);
-/*    input_x = i % box_width;*/
-    input_x = (i > box_width) ? box_width - 1 : i;
-/*    scroll = i - input_x;*/
-    scroll = (i > box_width) ? i - box_width + 1: 0;
-  }
-  redraw_field(dialog, box_y, box_x, flen, box_width, instr, input_x, scroll, attr, old_attr, FALSE, attr_mask);
-
-  for (;;) {
-    wattrset(dialog, attr);
-    wrefresh(dialog);
-    key = wgetch(dialog);
-    switch (key) {
-      case ctrl('q'):
-	goto ret;
-	break;
-      case KEY_F(1):
-	display_helpfile();
-	break;
-      case TAB:
-      case KEY_BTAB:
-      case KEY_UP:
-      case KEY_DOWN:
-      case ESC:
-      case '\r':
-      case '\n':
-	for (i = strlen(instr) - 1; i >= scroll + input_x && instr[i] == ' '; i--)
-	  instr[i] = '\0';
-	if (key == '\r')
-	  key = '\n';
-	goto ret;
-      case '\025':
-      case '\030':
-      kill_it:
-	input_x = scroll = 0;
-	/* fall through */
-      case '\013':
-      case KEY_EOL:
-	memset(instr + scroll + input_x, '\0', sizeof(instr) - scroll - input_x);
-	redraw_field(dialog, box_y, box_x, flen, box_width, instr, input_x, scroll, attr, old_attr, FALSE, attr_mask);
-	continue;
-      case '\001':
-      case KEY_HOME:
-	input_x = scroll = 0;
-	redraw_field(dialog, box_y, box_x, flen, box_width, instr, input_x, scroll, attr, old_attr, FALSE, attr_mask);
-	continue;
-      case '\005':
-      case KEY_END:
-	for (i = strlen(instr) - 1; i >= scroll + input_x && instr[i] == ' '; i--)
-	  instr[i] = '\0';
-	i++;
-	input_x = i % box_width;
-	scroll = i - input_x;
-	redraw_field(dialog, box_y, box_x, flen, box_width, instr, input_x, scroll, attr, old_attr, FALSE, attr_mask);
-	continue;
-      case '\002':
-      case KEY_LEFT:
-	if (input_x || scroll) {
-	  if (!input_x) {
-	    int oldscroll = scroll;
-	    scroll = scroll < box_width-1 ? 0 : scroll-(box_width-1);
-	    input_x = oldscroll - 1 - scroll;
-	    redraw_field(dialog, box_y, box_x, flen, box_width, instr, input_x, scroll, attr, old_attr, FALSE, attr_mask);
-	  } else {
-	    input_x--;
-	    wmove(dialog, box_y, input_x + box_x);
-	  }
-	} else
-	  beep();
-	continue;
-      case '\006':
-      case KEY_RIGHT:
-	  if (   scroll+input_x < MAX_LEN
-	      && (flen < 0 || scroll+input_x < flen)
-	     ) {
-	    if (!instr[scroll+input_x])
-	      instr[scroll+input_x] = ' ';
-	    if (input_x == box_width-1) {
-	      scroll++;
-	      redraw_field(dialog, box_y, box_x, flen, box_width, instr, input_x, scroll, attr, old_attr, FALSE, attr_mask);
-	    }
-	    else {
-	      wmove(dialog, box_y, input_x + box_x);
-	      waddch(dialog, instr[scroll+input_x]);
-	      input_x++;
-	    }
-	  } else
-	    beep(); /* Alarm user about overflow */
-	continue;
-      case '\b':
-      case '\177':
-      case KEY_BACKSPACE:
-      erase_it:
-	if (input_x || scroll) {
-	  i = strlen(instr);
-	  memmove(instr+scroll+input_x-1, instr+scroll+input_x, i-(scroll+input_x)+1);
-	  if (!input_x) {
-	    int oldscroll = scroll;
-	    scroll = scroll < box_width-1 ? 0 : scroll-(box_width-1);
-	    input_x = oldscroll - 1 - scroll;
-	  } else
-	    input_x--;
-	  redraw_field(dialog, box_y, box_x, flen, box_width, instr, input_x, scroll, attr, old_attr, FALSE, attr_mask);
-	} else
-	  beep();
-	continue;
-      case '\004':
-      case KEY_DC:
-	for (i = strlen(instr) - 1; i >= scroll + input_x && instr[i] == ' '; i--)
-	  instr[i] = '\0';
-	i++;
-	if (i == 0) {
-	  beep();
-	  continue;
-	}
-	memmove(instr+scroll+input_x, instr+scroll+input_x+1, i-(scroll+input_x));
-	redraw_field(dialog, box_y, box_x, flen, box_width, instr, input_x, scroll, attr, old_attr, FALSE, attr_mask);
-	continue;
-      default:
-	if (CCEQ(key, erase_char))
-	  goto erase_it;
-	if (CCEQ(key, kill_char))
-	  goto kill_it;
-	if (key < 0x100 && isprint(key)) {
-	  for (i = strlen(instr) - 1; i >= scroll + input_x && instr[i] == ' '; i--)
-	    instr[i] = '\0';
-	  i++;
-	  if (i < MAX_LEN && (flen < 0 || scroll+input_x < flen)) {
-	    if (flen < 0 || i < flen)
-	      memmove(instr+scroll+input_x+1, instr+scroll+input_x, i-(scroll+input_x));
-	    instr[scroll+input_x] = key;
-	    if (input_x == box_width-1 && (flen < 0 || i < flen))
-	      scroll++;
-	    else
-	      input_x++;
-	    redraw_field(dialog, box_y, box_x, flen, box_width, instr, input_x, scroll, attr, old_attr, FALSE, attr_mask);
-	  } else
-	    beep(); /* Alarm user about overflow */
-	  continue;
-	}
-      }
-    }
-ret:
-    redraw_field(dialog, box_y, box_x, flen, box_width, instr, input_x, scroll, attr, old_attr, TRUE, attr_mask);
-    wrefresh(dialog);
-    strcpy(result, instr);
-    return key;
-}
-
-static void
-redraw_field(WINDOW *dialog, int box_y, int box_x, int flen, int box_width, unsigned char instr[], int input_x, int scroll, chtype attr, chtype old_attr, int fexit, int attr_mask)
-{
-  int i, fix_len;
-
-  wattrset(dialog, fexit ? old_attr : attr);
-  wmove(dialog, box_y, box_x);
-  fix_len = flen >= 0 ? MIN(flen-scroll,box_width) : box_width;
-  for (i = 0; i < fix_len; i++)
-      waddch(dialog, instr[scroll+i] ? ((attr_mask & DITEM_NO_ECHO) ? '*' : instr[scroll+i]) : ' ');
-  wattrset(dialog, old_attr);
-  for ( ; i < box_width; i++)
-      waddch(dialog, instr[scroll+i] ? ((attr_mask & DITEM_NO_ECHO) ? '*' : instr[scroll+i]) : ' ');
-  wmove(dialog, box_y, input_x + box_x);
-}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/menubox.c
--- a/head/gnu/lib/libodialog/menubox.c	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,469 +0,0 @@
-/*
- *  menubox.c -- implements the menu box
- *
- *  AUTHOR: Savio Lam (lam836 at cs.cuhk.hk)
- *
- *	Substantial rennovation:  12/18/95, Jordan K. Hubbard
- *
- *  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., 675 Mass Ave, Cambridge, MA 02139, USA.
- */
-
-#include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
-
-#include <dialog.h>
-#include "dialog.priv.h"
-#include <err.h>
-#include <ncurses.h>
-
-static void print_item(WINDOW *win, unsigned char *tag, unsigned char *item, int choice, int selected, dialogMenuItem *me, int menu_width, int tag_x, int item_x);
-
-#define DREF(di, item)		((di) ? &((di)[(item)]) : NULL)
-
-/*
- * Display a menu for choosing among a number of options
- */
-int
-dialog_menu(unsigned char *title, unsigned char *prompt, int height, int width, int menu_height, int cnt, void *it, unsigned char *result, int *ch, int *sc)
-{
-    int i, j, x, y, cur_x, cur_y, box_x, box_y, key = 0, button, choice,
-	l, k, scroll, max_choice, item_no, redraw_menu = FALSE;
-    char okButton, cancelButton;
-    int rval = 0, ok_space, cancel_space;
-    WINDOW *dialog, *menu;
-    unsigned char **items = NULL;
-    dialogMenuItem *ditems;
-    int menu_width, tag_x, item_x;
-    
-draw:
-    choice = ch ? *ch : 0;
-    scroll = sc ? *sc : 0;
-    button = 0;
-    
-    /* If item_no is a positive integer, use old item specification format */
-    if (cnt >= 0) {
-	items = it;
-	ditems = NULL;
-	item_no = cnt;
-    }
-    /* It's the new specification format - fake the rest of the code out */
-    else {
-	item_no = abs(cnt);
-	ditems = it;
-	if (!items)
-	    items = (unsigned char **)alloca((item_no * 2) * sizeof(unsigned char *));
-	
-	/* Initializes status */
-	for (i = 0; i < item_no; i++) {
-	    items[i*2] = ditems[i].prompt;
-	    items[i*2 + 1] = ditems[i].title;
-	}
-    }
-    max_choice = MIN(menu_height, item_no);
-    
-    tag_x = 0;
-    item_x = 0;
-    /* Find length of longest item in order to center menu */
-    for (i = 0; i < item_no; i++) {
-	l = strlen(items[i * 2]);
-	for (j = 0; j < item_no; j++) {
-	    k = strlen(items[j * 2 + 1]);
-	    tag_x = MAX(tag_x, l + k + 2);
-	}
-	item_x = MAX(item_x, l);
-    }
-    if (height < 0)
-	height = strheight(prompt) + menu_height + 4 + 2;
-    if (width < 0) {
-	i = strwidth(prompt);
-	j = ((title != NULL) ? strwidth(title) : 0);
-	width = MAX(i, j);
-	width = MAX(width, tag_x + 4) + 4;
-    }
-    width = MAX(width, 24);
-    
-    if (width > COLS)
-	width = COLS;
-    if (height > LINES)
-	height = LINES;
-    /* center dialog box on screen */
-    x = DialogX ? DialogX : (COLS - width) / 2;
-    y = DialogY ? DialogY : (LINES - height) / 2;
-    
-#ifdef HAVE_NCURSES
-    if (use_shadow)
-	draw_shadow(stdscr, y, x, height, width);
-#endif
-    dialog = newwin(height, width, y, x);
-    if (dialog == NULL) {
-	endwin();
-	fprintf(stderr, "\nnewwin(%d,%d,%d,%d) failed, maybe wrong dims\n", height, width, y, x);
-	return -1;
-    }
-    keypad(dialog, TRUE);
-    
-    draw_box(dialog, 0, 0, height, width, dialog_attr, border_attr);
-    wattrset(dialog, border_attr);
-    wmove(dialog, height - 3, 0);
-    waddch(dialog, ACS_LTEE);
-    for (i = 0; i < width - 2; i++)
-	waddch(dialog, ACS_HLINE);
-    wattrset(dialog, dialog_attr);
-    waddch(dialog, ACS_RTEE);
-    wmove(dialog, height - 2, 1);
-    for (i = 0; i < width - 2; i++)
-	waddch(dialog, ' ');
-    
-    if (title != NULL) {
-	wattrset(dialog, title_attr);
-	wmove(dialog, 0, (width - strlen(title)) / 2 - 1);
-	waddch(dialog, ' ');
-	waddstr(dialog, title);
-	waddch(dialog, ' ');
-    }
-    wattrset(dialog, dialog_attr);
-    wmove(dialog, 1, 2);
-    print_autowrap(dialog, prompt, height - 1, width - 2, width, 1, 2, TRUE, FALSE);
-    
-    menu_width = width - 6;
-    getyx(dialog, cur_y, cur_x);
-    box_y = cur_y + 1;
-    box_x = (width - menu_width) / 2 - 1;
-    
-    /* create new window for the menu */
-    menu = subwin(dialog, menu_height, menu_width, y + box_y + 1, x + box_x + 1);
-    if (menu == NULL) {
-	delwin(dialog);
-	endwin();
-	fprintf(stderr, "\nsubwin(dialog,%d,%d,%d,%d) failed, maybe wrong dims\n", menu_height, menu_width,
-		y + box_y + 1, x + box_x + 1);
-	return -1;
-    }
-    keypad(menu, TRUE);
-    
-    /* draw a box around the menu items */
-    draw_box(dialog, box_y, box_x, menu_height+2, menu_width+2, menubox_border_attr, menubox_attr);
-    
-    tag_x = menu_width > tag_x + 1 ? (menu_width - tag_x) / 2 : 1;
-    item_x = menu_width > item_x + 4 ? tag_x + item_x + 2 : menu_width - 3;
-    
-    /* Print the menu */
-    for (i = 0; i < max_choice; i++)
-	print_item(menu, items[(scroll + i) * 2], items[(scroll + i) * 2 + 1], i, i == choice, DREF(ditems, scroll + i), menu_width, tag_x, item_x);
-    wnoutrefresh(menu);
-    print_arrows(dialog, scroll, menu_height, item_no, box_x, box_y, tag_x, cur_x, cur_y);
-    
-    display_helpline(dialog, height - 1, width);
-    
-    x = width / 2 - 11;
-    y = height - 2;
-    
-    if (ditems && result) {
-	cancelButton = toupper(ditems[CANCEL_BUTTON].prompt[0]);
-	print_button(dialog, ditems[CANCEL_BUTTON].prompt, y, x + strlen(ditems[OK_BUTTON].prompt) + 5, ditems[CANCEL_BUTTON].checked ? ditems[CANCEL_BUTTON].checked(&ditems[CANCEL_BUTTON]) : FALSE);
-	okButton = toupper(ditems[OK_BUTTON].prompt[0]);
-	print_button(dialog, ditems[OK_BUTTON].prompt, y, x, ditems[OK_BUTTON].checked ? ditems[OK_BUTTON].checked(&ditems[OK_BUTTON]) : TRUE);
-    }
-    else {
-	cancelButton = 'C';
-	print_button(dialog, "Cancel", y, x + 14, FALSE);
-	okButton = 'O';
-	print_button(dialog, "  OK  ", y, x, TRUE);
-    }
-    
-    wrefresh(dialog);
-    while (key != ESC) {
-	key = wgetch(dialog);
-	
-	/* Shortcut to OK? */
-	if (toupper(key) == okButton) {
-	    if (ditems) {
-		if (result && ditems[OK_BUTTON].fire) {
-		    int status;
-		    WINDOW *save;
-
-		    save = dupwin(newscr);
-		    status = ditems[OK_BUTTON].fire(&ditems[OK_BUTTON]);
-		    if (status & DITEM_RESTORE) {
-			touchwin(save);
-			wrefresh(save);
-		    }
-		    delwin(save);
-		}
-	    }
-	    else if (result)
-		strcpy(result, items[(scroll + choice) * 2]);
-	    rval = 0;
-	    key = ESC;	/* Punt! */
-	    break;
-	}
-
-	/* Shortcut to cancel? */
-	if (toupper(key) == cancelButton) {
-	    if (ditems && result && ditems[CANCEL_BUTTON].fire) {
-		int status;
-		WINDOW *save;
-
-		save = dupwin(newscr);
-		status = ditems[CANCEL_BUTTON].fire(&ditems[CANCEL_BUTTON]);
-		if (status & DITEM_RESTORE) {
-		    touchwin(save);
-		    wrefresh(save);
-		}
-		delwin(save);
-	    }
-	    rval = 1;
-	    key = ESC;	/* Run away! */
-	    break;
-	}
-
-	/* Check if key pressed matches first character of any item tag in menu */
-	for (i = 0; i < max_choice; i++)	
-	    if (key < 0x100 && key != ' ' && toupper(key) == toupper(items[(scroll + i) * 2][0]))
-		break;
-
-	if (i < max_choice || (key >= '1' && key <= MIN('9', '0'+max_choice)) || KEY_IS_UP(key) || KEY_IS_DOWN(key)) {
-	    if (key >= '1' && key <= MIN('9', '0'+max_choice))
-		i = key - '1';
-	    else if (KEY_IS_UP(key)) {
-		if (!choice) {
-		    if (scroll) {
-			/* Scroll menu down */
-			getyx(dialog, cur_y, cur_x);    /* Save cursor position */
-			if (menu_height > 1) {
-			    /* De-highlight current first item before scrolling down */
-			    print_item(menu, items[scroll * 2], items[scroll * 2 + 1], 0, FALSE, DREF(ditems, scroll), menu_width, tag_x, item_x);
-			    scrollok(menu, TRUE);
-			    wscrl(menu, -1);
-			    scrollok(menu, FALSE);
-			}
-			scroll--;
-			print_item(menu, items[scroll * 2], items[scroll * 2 + 1], 0, TRUE, DREF(ditems, scroll), menu_width, tag_x, item_x);
-			wnoutrefresh(menu);
-			print_arrows(dialog, scroll, menu_height, item_no, box_x, box_y, tag_x, cur_x, cur_y);
-			wrefresh(dialog);
-		    }
-		    continue;    /* wait for another key press */
-		}
-		else
-		    i = choice - 1;
-	    }
-	    else if (KEY_IS_DOWN(key)) {
-		if (choice == max_choice - 1) {
-		    if (scroll + choice < item_no - 1) {
-			/* Scroll menu up */
-			getyx(dialog, cur_y, cur_x);    /* Save cursor position */
-			if (menu_height > 1) {
-			    /* De-highlight current last item before scrolling up */
-			    print_item(menu, items[(scroll + max_choice - 1) * 2],
-				       items[(scroll + max_choice - 1) * 2 + 1],
-				       max_choice-1, FALSE, DREF(ditems, scroll + max_choice - 1), menu_width, tag_x, item_x);
-			    scrollok(menu, TRUE);
-			    scroll(menu);
-			    scrollok(menu, FALSE);
-			}
-			scroll++;
-			print_item(menu, items[(scroll + max_choice - 1) * 2],
-				   items[(scroll + max_choice - 1) * 2 + 1],
-				   max_choice - 1, TRUE, DREF(ditems, scroll + max_choice - 1), menu_width, tag_x, item_x);
-			wnoutrefresh(menu);
-			print_arrows(dialog, scroll, menu_height, item_no, box_x, box_y, tag_x, cur_x, cur_y);
-			wrefresh(dialog);
-		    }
-		    continue;    /* wait for another key press */
-		}
-		else
-		    i = choice + 1;
-	    }
-	    
-	    if (i != choice) {
-		/* De-highlight current item */
-		getyx(dialog, cur_y, cur_x);    /* Save cursor position */
-		print_item(menu, items[(scroll + choice) * 2], items[(scroll + choice) * 2 + 1], choice, FALSE, DREF(ditems, scroll + choice), menu_width, tag_x, item_x);
-		
-		/* Highlight new item */
-		choice = i;
-		print_item(menu, items[(scroll + choice) * 2], items[(scroll + choice) * 2 + 1], choice, TRUE, DREF(ditems, scroll + choice), menu_width, tag_x, item_x);
-		wnoutrefresh(menu);
-		wmove(dialog, cur_y, cur_x);  /* Restore cursor to previous position */
-		wrefresh(dialog);
-	    }
-	    continue;    /* wait for another key press */
-	}
-	
-	switch (key) {
-	case KEY_PPAGE:
-	    if (scroll > height - 4) {	/* can we go up? */
-		scroll -= (height - 4);
-	    } else {
-		scroll = 0;
-	    }
-	    redraw_menu = TRUE;
-	    break;
-	    
-	case KEY_NPAGE:
-	    if (scroll + menu_height >= item_no-1 - menu_height) { /* can we go down a full page? */
-		scroll = item_no - menu_height;
-		if (scroll < 0)
-		    scroll = 0;
-	    } else {
-		scroll += menu_height;
-	    }
-	    redraw_menu = TRUE;
-	    break;
-	    
-	case KEY_HOME:
-	    scroll = 0;
-	    choice = 0;
-	    redraw_menu = TRUE;
-	    break;
-	    
-	case KEY_END:
-	    scroll = item_no - menu_height;
-	    if (scroll < 0)
-		scroll = 0;
-	    choice = max_choice - 1;
-	    redraw_menu = TRUE;
-	    break;
-	    
-	case KEY_BTAB:
-	case TAB:
-	case KEY_LEFT:
-	case KEY_RIGHT:
-	    button = !button;
-	    if (ditems && result) {
-		print_button(dialog, ditems[CANCEL_BUTTON].prompt, y, x + strlen(ditems[OK_BUTTON].prompt) + 5, ditems[CANCEL_BUTTON].checked ? ditems[CANCEL_BUTTON].checked(&ditems[CANCEL_BUTTON]) : button);
-		print_button(dialog, ditems[OK_BUTTON].prompt, y, x, ditems[OK_BUTTON].checked ? ditems[OK_BUTTON].checked(&ditems[OK_BUTTON]) : !button);
-		ok_space = 1;
-		cancel_space = strlen(ditems[OK_BUTTON].prompt) + 6;
-	    }
-	    else {
-		print_button(dialog, "Cancel", y, x + 14, button);
-		print_button(dialog, "  OK  ", y, x, !button);
-		ok_space = 3;
-		cancel_space = 15;
-	    }
-	    if (button)
-		wmove(dialog, y, x+cancel_space);
-	    else
-		wmove(dialog, y, x+ok_space);
-	    wrefresh(dialog);
-	    break;
-	    
-	case ' ':
-	case '\r':
-	case '\n':
-	    if (!button) {
-		/* A fire routine can do just about anything to the screen, so be prepared
-		   to accept some hints as to what to do in the aftermath. */
-		if (ditems) {
-		    if (ditems[scroll + choice].fire) {
-			int status;
-			WINDOW *save;
-
-			save = dupwin(newscr);
-			status = ditems[scroll + choice].fire(&ditems[scroll + choice]);
-			if (status & DITEM_RESTORE) {
-			    touchwin(save);
-			    wrefresh(save);
-			}
-			delwin(save);
-			if (status & DITEM_CONTINUE)
-			    continue;
-			else if (status & DITEM_LEAVE_MENU) {
-			    /* Allow a fire action to take us out of the menu */
-			    key = ESC;
-			    break;
-			}
-			else if (status & DITEM_RECREATE) {
-			    delwin(menu);
-			    delwin(dialog);
-			    dialog_clear();
-			    goto draw;
-			}
-		    }
-		}
-		else if (result)
-		    strcpy(result, items[(scroll+choice)*2]);
-	    }
-	    rval = button;
-	    key = ESC;
-	    break;
-	    
-	case ESC:
-	    rval = -1;
-	    break;
-	    
-	case KEY_F(1):
-	case '?':
-	    display_helpfile();
-	    break;
-	}
-	
-	/* save info about menu item position */
-	if (ch)
-	    *ch = choice;
-	if (sc)
-	    *sc = scroll;
-	
-	if (redraw_menu) {
-	    for (i = 0; i < max_choice; i++) {
-		print_item(menu, items[(scroll + i) * 2], items[(scroll + i) * 2 + 1], i, i == choice, DREF(ditems, scroll + i), menu_width, tag_x, item_x);
-	    }
-	    wnoutrefresh(menu);
-	    getyx(dialog, cur_y, cur_x);    /* Save cursor position */
-	    print_arrows(dialog, scroll, menu_height, item_no, box_x, box_y, tag_x, cur_x, cur_y);
-	    wmove(dialog, cur_y, cur_x);  /* Restore cursor to previous position */
-	    wrefresh(dialog);
-	    redraw_menu = FALSE;
-	}
-    }
-    delwin(menu);
-    delwin(dialog);
-    return rval;
-}
-
-
-/*
- * Print menu item
- */
-static void
-print_item(WINDOW *win, unsigned char *tag, unsigned char *item, int choice, int selected, dialogMenuItem *me, int menu_width, int tag_x, int item_x)
-{
-    int i;
-
-    if (tag == NULL)
-	errx(1, "bad parameter to print_item()\n");
-    
-    /* Clear 'residue' of last item */
-    wattrset(win, menubox_attr);
-    wmove(win, choice, 0);
-    for (i = 0; i < menu_width; i++)
-	waddch(win, ' ');
-    wmove(win, choice, tag_x);
-    wattrset(win, selected ? tag_key_selected_attr : tag_key_attr);
-    waddch(win, tag[0]);
-    wattrset(win, selected ? tag_selected_attr : tag_attr);
-    waddnstr(win, tag + 1, item_x - tag_x - 3);
-    wmove(win, choice, item_x);
-    wattrset(win, selected ? item_selected_attr : item_attr);
-    waddnstr(win, item, menu_width - item_x - 1);
-    /* If have a selection handler for this, call it */
-    if (me && me->selected) {
-	wrefresh(win);
-	me->selected(me, selected);
-    }
-}
-/* End of print_item() */
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/msgbox.c
--- a/head/gnu/lib/libodialog/msgbox.c	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,346 +0,0 @@
-/*
- *  msgbox.c -- implements the message box and info box
- *
- *  AUTHOR: Savio Lam (lam836 at cs.cuhk.hk)
- *
- *  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., 675 Mass Ave, Cambridge, MA 02139, USA.
- */
-
-#include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
-
-#include <dialog.h>
-#include "dialog.priv.h"
-
-
-/* local prototypes */
-static int 	getnlines(unsigned char *buf);
-static void	print_page(WINDOW *win, int height, int width, unsigned char *buf, int startline, int hscroll);
-static void 	print_perc(WINDOW *win, int y, int x, float p);
-
-
-/*
- * Display a message box. Program will pause and display an "OK" button
- * if the parameter 'pause' is non-zero.
- */
-int dialog_msgbox(unsigned char *title, unsigned char *prompt, int height, int width, int pause)
-{
-  int i, j, x, y, key = 0;
-  WINDOW *dialog;
-
-  if (height < 0)
-	height = strheight(prompt)+2+2*(!!pause);
-  if (width < 0) {
-	i = strwidth(prompt);
-	j = ((title != NULL) ? strwidth(title) : 0);
-	width = MAX(i,j)+4;
-  }
-  if (pause)
-	width = MAX(width,10);
-
-  if (width > COLS)
-	width = COLS;
-  if (height > LINES)
-	height = LINES;
-  /* center dialog box on screen */
-  x = DialogX ? DialogX : (COLS - width)/2;
-  y = DialogY ? DialogY : (LINES - height)/2;
-
-#ifdef HAVE_NCURSES
-  if (use_shadow)
-    draw_shadow(stdscr, y, x, height, width);
-#endif
-  dialog = newwin(height, width, y, x);
-  if (dialog == NULL) {
-    endwin();
-    fprintf(stderr, "\nnewwin(%d,%d,%d,%d) failed, maybe wrong dims\n", height,width,y,x);
-    exit(1);
-  }
-  keypad(dialog, TRUE);
-
-  draw_box(dialog, 0, 0, height, width, dialog_attr, border_attr);
-
-  if (title != NULL) {
-    wattrset(dialog, title_attr);
-    wmove(dialog, 0, (width - strlen(title))/2 - 1);
-    waddch(dialog, ' ');
-    waddstr(dialog, title);
-    waddch(dialog, ' ');
-  }
-  wattrset(dialog, dialog_attr);
-  wmove(dialog, 1, 2);
-  print_autowrap(dialog, prompt, height-1, width-2, width, 1, 2, TRUE, FALSE);
-
-  if (pause) {
-    wattrset(dialog, border_attr);
-    wmove(dialog, height-3, 0);
-    waddch(dialog, ACS_LTEE);
-    for (i = 0; i < width-2; i++)
-      waddch(dialog, ACS_HLINE);
-    wattrset(dialog, dialog_attr);
-    waddch(dialog, ACS_RTEE);
-    wmove(dialog, height-2, 1);
-    for (i = 0; i < width-2; i++)
-    waddch(dialog, ' ');
-    display_helpline(dialog, height-1, width);
-    print_button(dialog, "  OK  ", height-2, width/2-6, TRUE);
-    wrefresh(dialog);
-    while (key != ESC && key != '\n' && key != ' ' && key != '\r')
-      key = wgetch(dialog);
-    if (key == '\r')
-      key = '\n';
-  }
-  else {
-    key = '\n';
-    wrefresh(dialog);
-  }
-
-  delwin(dialog);
-  return (key == ESC ? -1 : 0);
-}
-/* End of dialog_msgbox() */
-
-int
-dialog_mesgbox(unsigned char *title, unsigned char *prompt, int height, int width)
-/*
- * Desc: basically the same as dialog_msgbox, but ... can use PGUP, PGDN and
- *	 arrowkeys to move around the text and pause is always enabled
- */
-{
-    int 	i, j, x, y, key=0;
-    int		theight, startline, hscroll, max_lines;
-    WINDOW 	*dialog;
-
-    if (height < 0)
-	height = strheight(prompt)+2+2;
-    if (width < 0) {
-	i = strwidth(prompt);
-	j = ((title != NULL) ? strwidth(title) : 0);
-	width = MAX(i,j)+4;
-    }
-    width = MAX(width,10);
-
-    if (width > COLS)
-	width = COLS;
-    if (height > LINES)
-	height = LINES;
-    /* center dialog box on screen */
-    x = (COLS - width)/2;
-    y = (LINES - height)/2;
-
-#ifdef HAVE_NCURSES
-    if (use_shadow)
-	draw_shadow(stdscr, y, x, height, width);
-#endif
-    dialog = newwin(height, width, y, x);
-    if (dialog == NULL) {
-	endwin();
-	fprintf(stderr, "\nnewwin(%d,%d,%d,%d) failed, maybe wrong dims\n", height,width,y,x);
-	exit(1);
-    }
-    keypad(dialog, TRUE);
-
-    draw_box(dialog, 0, 0, height, width, dialog_attr, border_attr);
-
-    if (title != NULL) {
-	wattrset(dialog, title_attr);
-	wmove(dialog, 0, (width - strlen(title))/2 - 1);
-	waddch(dialog, ' ');
-	waddstr(dialog, title);
-	waddch(dialog, ' ');
-    }
-
-    wattrset(dialog, border_attr);
-    wmove(dialog, height-3, 0);
-    waddch(dialog, ACS_LTEE);
-    for (i = 0; i < width-2; i++)
-      waddch(dialog, ACS_HLINE);
-    wattrset(dialog, dialog_attr);
-    waddch(dialog, ACS_RTEE);
-    wmove(dialog, height-2, 1);
-    for (i = 0; i < width-2; i++)
-    waddch(dialog, ' ');
-    display_helpline(dialog, height-1, width);
-    print_button(dialog, "  OK  ", height-2, width/2-6, TRUE);
-    wattrset(dialog, dialog_attr);
-
-    theight = height - 4;
-    startline = 0;
-    hscroll = 0;
-    max_lines = getnlines(prompt);
-    print_page(dialog, theight, width, prompt, startline, hscroll);
-    print_perc(dialog, height-3, width-9, (float) (startline+theight)/max_lines);
-    wmove(dialog, height-2, width/2-3);
-    wrefresh(dialog);
-    while ((key != ESC) && (key != '\n') && (key != '\r') && (key != ' ')) {
-	key = wgetch(dialog);
-	switch(key) {
-	case KEY_HOME:
-	    startline=0;
-	    hscroll=0;
-	    break;
-	case KEY_END:
-	    startline = max_lines - theight;
-	    if (startline < 0) startline = 0;
-	    break;
-	case '\020':	/* ^P */
-	case KEY_UP:
-	    if (startline > 0) startline--;
-	    break;
-	case '\016':	/* ^N */
-	case KEY_DOWN:
-	    if (startline < max_lines - theight) startline++;
-	    break;
-	case KEY_RIGHT:
-	    hscroll+=5;
-	    break;
-	case KEY_LEFT:
-	    if (hscroll > 0) hscroll-=5;
-	    if (hscroll < 0) hscroll =0;
-	    break;
-	case KEY_PPAGE:
-	    if (startline - height > 0) {
-		startline -= theight;
-	    } else {
-		startline = 0;
-	    }
-	    break;
-	case KEY_NPAGE:
-	    if (startline + theight < max_lines - theight) {
-		startline += theight;
-	    } else {
-		startline = max_lines - theight;
-		if (startline < 0) startline = 0;
-	    }
-	    break;
-	case KEY_F(1):
-	case '?':
-	    display_helpfile();
-	    break;
-	}
-	print_page(dialog, theight, width, prompt, startline, hscroll);
-	print_perc(dialog, height-3, width-9, (float) (startline+theight)/max_lines);
-	wmove(dialog, height-2, width/2-3);
-	wrefresh(dialog);
-    }
-
-    delwin(dialog);
-    return (key == ESC ? -1 : 0);
-
-} /* dialog_mesgbox() */
-
-static void
-print_perc(WINDOW *win, int y, int x, float p)
-/*
- * Desc: print p as a percentage at the coordinates (y,x)
- */
-{
-    char	ps[10];
-
-    if (p>1.0) p=1.0;
-    sprintf(ps, "(%3d%%)", (int) (p*100));
-    wmove(win, y, x);
-    waddstr(win, ps);
-
-    return;
-} /* print_perc() */
-
-static int
-getnlines(unsigned char *buf)
-/*
- * Desc: count the # of lines in <buf>
- */
-{
-    int i = 0;
-
-    if (*buf)
-	i++;
-    while (*buf) {
-	if (*buf == '\n' || *buf == '\r')
-	    i++;
-	buf++;
-    }
-    return(i);
-} /* getlines() */
-
-
-unsigned char *
-getline(unsigned char *buf, int n)
-/*
- * Desc: return a pointer to the n'th line in <buf> or NULL if its
- *	 not there
- */
-{
-    int i;
-
-    if (n<0) {
-	return(NULL);
-    }
-
-    i=0;
-    while (*buf && i<n) {
-	if (*buf == '\n' || *buf == '\r') {
-	    i++;
-	}
-	buf++;
-    }
-    if (i<n) {
-	return(NULL);
-    } else {
-	return(buf);
-    }
-} /* getline() */
-
-static void
-print_page(WINDOW *win, int height, int width, unsigned char *buf, int startline, int hscroll)
-/*
- * Desc: Print a page of text in the current window, starting at line <startline>
- *	 with a <horizontal> scroll of hscroll from buffer <buf>
- */
-{
-    int i, j;
-    unsigned char *b;
-
-    b = getline(buf, startline);
-    for (i=0; i<height; i++) {
-	/* clear line */
-	wmove(win, 1+i, 1);
-	for (j=0; j<width-2; j++) waddnstr(win, " ", 1);
-	wmove(win, 1+i, 1);
-	j = 0;
-	/* scroll to the right */
-	while (*b && (*b != '\n') && (*b != '\r') && (j<hscroll)) {
-	    b++;
-	    j++;
-	}
-	/* print new line */
-	j = 0;
-	while (*b && (*b != '\n') && (*b != '\r') && (j<width-2)) {
-	    waddnstr(win, b, 1);
-	    if (*b != '\t') {	/* check for tabs */
-		j++;
-	    } else {
-		j = ((int) (j+1)/8 + 1) * 8 - 1;
-	    }
-	    b++;
-	}
-	while (*b && (*b != '\n') && (*b != '\r')) b++;
-	if (*b) b++;	/* skip over '\n', if it exists */
-    }
-} /* print_page() */
-
-
-
-
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/notify.c
--- a/head/gnu/lib/libodialog/notify.c	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,53 +0,0 @@
-/*
- * File: 	notify.c
- * Author: 	Marc van Kempen
- * Desc:	display a notify box with a message
- *
- * Copyright (c) 1995, Marc van Kempen
- *
- * All rights reserved.
- *
- * This software may be used, modified, copied, distributed, and
- * sold, in both source and binary form provided that the above
- * copyright and these terms are retained, verbatim, as the first
- * lines of this file.  Under no circumstances is the author
- * responsible for the proper functioning of this software, nor does
- * the author assume any responsibility for damages incurred with
- * its use.
- *
- */
-
-#include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
-
-#include <dialog.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-void
-dialog_notify(char *msg)
-/*
- * Desc: display an error message
- */
-{
-    char *tmphlp;
-    WINDOW *w;
-
-    w = dupwin(newscr);
-    if (w == NULL) {
-	endwin();
-	fprintf(stderr, "\ndupwin(newscr) failed, malloc memory corrupted\n");
-	exit(1);
-    }
-    tmphlp = get_helpline();
-    use_helpline("Press enter or space");
-    dialog_mesgbox("Message", msg, -1, -1);
-    restore_helpline(tmphlp);
-    touchwin(w);
-    wrefresh(w);
-    delwin(w);
-
-    return;
-
-} /* dialog_notify() */
-
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/prgbox.c
--- a/head/gnu/lib/libodialog/prgbox.c	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,152 +0,0 @@
-/*
- *  prgbox.c -- implements the message box and info box
- *
- *  AUTHOR: Savio Lam (lam836 at cs.cuhk.hk)
- *
- *  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., 675 Mass Ave, Cambridge, MA 02139, USA.
- */
-
-#include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
-
-#include <sys/types.h>
-
-#include <dialog.h>
-#include <errno.h>
-#include <sys/wait.h>
-#include "dialog.priv.h"
-
-/*
- * Display a message box. Program will pause and display an "OK" button
- * if the parameter 'pause' is non-zero.
- */
-int dialog_prgbox(unsigned char *title, const unsigned char *line, int height, int width, int pause, int use_shell)
-{
-  int i, x, y, key = 0;
-  WINDOW *dialog;
-  FILE *f;
-  const unsigned char *name;
-  unsigned char *s, buf[MAX_LEN];
-  int status;
-
-  if (height < 0 || width < 0) {
-    endwin();
-    fprintf(stderr, "\nAutosizing is impossible in dialog_prgbox().\n");
-    exit(-1);
-  }
-  width = MAX(width,10);
-
-  if (width > COLS)
-	width = COLS;
-  if (height > LINES)
-	height = LINES;
-  /* center dialog box on screen */
-  x = DialogX ? DialogX : (COLS - width)/2;
-  y = DialogY ? DialogY : (LINES - height)/2;
-
-#ifdef HAVE_NCURSES
-  if (use_shadow)
-    draw_shadow(stdscr, y, x, height, width);
-#endif
-  dialog = newwin(height, width, y, x);
-  if (dialog == NULL) {
-    endwin();
-    fprintf(stderr, "\nnewwin(%d,%d,%d,%d) failed, maybe wrong dims\n", height,width,y,x);
-    exit(1);
-  }
-  keypad(dialog, TRUE);
-
-  draw_box(dialog, 0, 0, height, width, dialog_attr, border_attr);
-
-  if (title != NULL) {
-    wattrset(dialog, title_attr);
-    wmove(dialog, 0, (width - strlen(title))/2 - 1);
-    waddch(dialog, ' ');
-    waddstr(dialog, title);
-    waddch(dialog, ' ');
-  }
-  wattrset(dialog, dialog_attr);
-  wmove(dialog, 1, 2);
-
-  if (!use_shell) {
-    char cmdline[MAX_LEN];
-    char *av[51], **ap = av, *val, *p;
-
-    strcpy(cmdline, line);
-    p = cmdline;
-    while ((val = strsep(&p," \t")) != NULL) {
-      if (*val != '\0')
-	*ap++ = val;
-    }
-    *ap = NULL;
-    f = raw_popen(name = av[0], av, "r");
-  } else
-    f = raw_popen(name = line, NULL, "r");
-
-  status = -1;
-  if (f == NULL) {
-  err:
-      sprintf(buf, "%s: %s\n", name, strerror(errno));
-  prr:
-      print_autowrap(dialog, buf, height-(pause?3:1), width-2, width, 1, 2, FALSE, TRUE);
-      wrefresh(dialog);
-  } else {
-    while (fgets(buf, sizeof(buf), f) != NULL) {
-      i = strlen(buf);
-      if (buf[i-1] == '\n')
-	buf[i-1] = '\0';
-      s = buf;
-      while ((s = strchr(s, '\t')) != NULL)
-	*s++ = ' ';
-      print_autowrap(dialog, buf, height-(pause?3:1), width-2, width, 1, 2, FALSE, TRUE);
-      print_autowrap(dialog, "\n", height-(pause?3:1), width-2, width, 1, 2, FALSE, FALSE);
-      wrefresh(dialog);
-    }
-    if ((status = raw_pclose(f)) == -1)
-      goto err;
-    if (WIFEXITED(status) && WEXITSTATUS(status) == 127) {
-      sprintf(buf, "%s: program not found\n", name);
-      goto prr;
-    }
-  }
-
-  if (pause) {
-    wattrset(dialog, border_attr);
-    wmove(dialog, height-3, 0);
-    waddch(dialog, ACS_LTEE);
-    for (i = 0; i < width-2; i++)
-      waddch(dialog, ACS_HLINE);
-    wattrset(dialog, dialog_attr);
-    waddch(dialog, ACS_RTEE);
-    wmove(dialog, height-2, 1);
-    for (i = 0; i < width-2; i++)
-    waddch(dialog, ' ');
-    display_helpline(dialog, height-1, width);
-    print_button(dialog, "  OK  ", height-2, width/2-6, TRUE);
-    wrefresh(dialog);
-    while (key != ESC && key != '\n' && key != ' ' && key != '\r')
-      key = wgetch(dialog);
-    if (key == '\r')
-      key = '\n';
-  }
-  else {
-    key = '\n';
-    wrefresh(dialog);
-  }
-
-  delwin(dialog);
-  return (status);
-}
-/* End of dialog_msgbox() */
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/radiolist.c
--- a/head/gnu/lib/libodialog/radiolist.c	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,628 +0,0 @@
-/*
- *  radiolist.c -- implements the radiolist box
- *
- *  AUTHOR: Stuart Herbert - S.Herbert at sheffield.ac.uk
- *   (from checklist.c by Savio Lam (lam836 at cs.cuhk.hk))
- *
- *	Substantial rennovation:  12/18/95, Jordan K. Hubbard
- *
- *  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., 675 Mass Ave, Cambridge, MA 02139, USA.
- */
-
-#include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
-
-#include <dialog.h>
-#include "dialog.priv.h"
-
-
-static void print_item(WINDOW *win, char *tag, char *item, int status, int choice, int selected, dialogMenuItem *me);
-
-#define DREF(di, item)		((di) ? &((di)[(item)]) : NULL)
-
-static int list_width, check_x, item_x;
-
-
-/*
- * Display a dialog box with a list of options that can be turned on or off
- */
-int
-dialog_radiolist(unsigned char *title, unsigned char *prompt, int height, int width, int list_height,
-		 int cnt, void *it, unsigned char *result)
-{
-    int i, j, x, y, cur_x, cur_y, old_x, old_y, box_x, box_y, key = 0, button,
-	choice, l, k, scroll, max_choice, *status, item_no = 0, was_on = 0;
-    int redraw_menu = FALSE, cursor_reset = FALSE;
-    int rval = 0, onlist = 1, ok_space, cancel_space;
-    char okButton, cancelButton;
-    WINDOW *dialog, *list;
-    unsigned char **items = NULL;
-    dialogMenuItem *ditems;
-    
-    /* Allocate space for storing item on/off status */
-    if ((status = alloca(sizeof(int) * abs(cnt))) == NULL) {
-	endwin();
-	fprintf(stderr, "\nCan't allocate memory in dialog_radiolist().\n");
-	exit(-1);
-    }
-    
-draw:
-    button = choice = scroll = 0;
-    /* Previous calling syntax, e.g. just a list of strings? */
-    if (cnt >= 0) {
-	items = it;
-	ditems = NULL;
-	item_no = cnt;
-	/* Initializes status */
-	for (i = 0; i < item_no; i++) {
-	    status[i] = !strcasecmp(items[i*3 + 2], "on");
-	    if (status[i]) {
-		if (was_on)
-		    status[i] = FALSE;
-		else
-		    was_on = 1;
-	    }
-	}
-    }
-    /* It's the new specification format - fake the rest of the code out */
-    else {
-	item_no = abs(cnt);
-	ditems = it;
-	if (!items)
-	    items = (unsigned char **)alloca((item_no * 3) * sizeof(unsigned char *));
-	/* Initializes status */
-	for (i = 0; i < item_no; i++) {
-	    status[i] = ditems[i].checked ? ditems[i].checked(&ditems[i]) : FALSE;
-	    if (status[i]) {
-		if (was_on)
-		    status[i] = FALSE;
-		else
-		    was_on = 1;
-	    }
-	    items[i*3] = ditems[i].prompt;
-	    items[i*3 + 1] = ditems[i].title;
-	    items[i*3 + 2] = status[i] ? "on" : "off";
-	}
-    }
-    max_choice = MIN(list_height, item_no);
-    
-    check_x = 0;
-    item_x = 0;
-    /* Find length of longest item in order to center radiolist */
-    for (i = 0; i < item_no; i++) {
-	l = strlen(items[i * 3]);
-	for (j = 0; j < item_no; j++) {
-	    k = strlen(items[j * 3 + 1]);
-	    check_x = MAX(check_x, l + k + 6);
-	}
-	item_x = MAX(item_x, l);
-    }
-    if (height < 0)
-	height = strheight(prompt) + list_height + 4 + 2;
-    if (width < 0) {
-	i = strwidth(prompt);
-	j = ((title != NULL) ? strwidth(title) : 0);
-	width = MAX(i, j);
-	width = MAX(width, check_x + 4) + 4;
-    }
-    width = MAX(width, 24);
-    
-    if (width > COLS)
-	width = COLS;
-    if (height > LINES)
-	height = LINES;
-    /* center dialog box on screen */
-    x = DialogX ? DialogX : (COLS - width) / 2;
-    y = DialogY ? DialogY : (LINES - height) / 2;
-
-#ifdef HAVE_NCURSES
-    if (use_shadow)
-	draw_shadow(stdscr, y, x, height, width);
-#endif
-    dialog = newwin(height, width, y, x);
-    if (dialog == NULL) {
-	endwin();
-	fprintf(stderr, "\nnewwin(%d,%d,%d,%d) failed, maybe wrong dims\n", height, width, y, x);
-	return -1;
-    }
-    keypad(dialog, TRUE);
-    
-    draw_box(dialog, 0, 0, height, width, dialog_attr, border_attr);
-    wattrset(dialog, border_attr);
-    wmove(dialog, height - 3, 0);
-    waddch(dialog, ACS_LTEE);
-    for (i = 0; i < width - 2; i++)
-	waddch(dialog, ACS_HLINE);
-    wattrset(dialog, dialog_attr);
-    waddch(dialog, ACS_RTEE);
-    wmove(dialog, height - 2, 1);
-    for (i = 0; i < width - 2; i++)
-	waddch(dialog, ' ');
-    
-    if (title != NULL) {
-	wattrset(dialog, title_attr);
-	wmove(dialog, 0, (width - strlen(title)) / 2 - 1);
-	waddch(dialog, ' ');
-	waddstr(dialog, title);
-	waddch(dialog, ' ');
-    }
-    wattrset(dialog, dialog_attr);
-    wmove(dialog, 1, 2);
-    print_autowrap(dialog, prompt, height - 1, width - 2, width, 1, 2, TRUE, FALSE);
-    
-    list_width = width - 6;
-    getyx(dialog, cur_y, cur_x);
-    box_y = cur_y + 1;
-    box_x = (width - list_width) / 2 - 1;
-    
-    /* create new window for the list */
-    list = subwin(dialog, list_height, list_width, y + box_y + 1, x + box_x + 1);
-    if (list == NULL) {
-	delwin(dialog);
-	endwin();
-	fprintf(stderr, "\nsubwin(dialog,%d,%d,%d,%d) failed, maybe wrong dims\n", list_height, list_width,
-		y + box_y + 1,x + box_x + 1);
-	return -1;
-    }
-    keypad(list, TRUE);
-    
-    /* draw a box around the list items */
-    draw_box(dialog, box_y, box_x, list_height+2, list_width+2, menubox_border_attr, menubox_attr);
-    
-    check_x = (list_width - check_x) / 2;
-    item_x = check_x + item_x + 6;
-    
-    /* Print the list */
-    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));
-    wnoutrefresh(list);
-    print_arrows(dialog, scroll, list_height, item_no, box_x, box_y, check_x + 4, cur_x, cur_y);
-    
-    display_helpline(dialog, height-1, width);
-    
-    x = width/ 2 - 11;
-    y = height - 2;
-    if (ditems && result) {
-	cancelButton = toupper(ditems[CANCEL_BUTTON].prompt[0]);
-	print_button(dialog, ditems[CANCEL_BUTTON].prompt, y, x + strlen(ditems[OK_BUTTON].prompt) + 5,
-		     ditems[CANCEL_BUTTON].checked ? ditems[CANCEL_BUTTON].checked(&ditems[CANCEL_BUTTON]) : FALSE);
-	okButton = toupper(ditems[OK_BUTTON].prompt[0]);
-	print_button(dialog, ditems[OK_BUTTON].prompt, y, x,
-		     ditems[OK_BUTTON].checked ? ditems[OK_BUTTON].checked(&ditems[OK_BUTTON]) : TRUE);
-    }
-    else {
-	cancelButton = 'C';
-	print_button(dialog, "Cancel", y, x + 14, FALSE);
-	okButton = 'O';
-	print_button(dialog, "  OK  ", y, x, TRUE);
-    }
-    wnoutrefresh(dialog);
-    wmove(list, choice, check_x+1);
-    wrefresh(list);
-
-    while (key != ESC) {
-	key = wgetch(dialog);
-	
-	/* See if its the short-cut to "OK" */
-	if (toupper(key) == okButton) {
-	    if (ditems) {
-		if (result && ditems[OK_BUTTON].fire) {
-		    int st;
-		    WINDOW *save;
-
-		    save = dupwin(newscr);
-		    st = ditems[OK_BUTTON].fire(&ditems[OK_BUTTON]);
-		    if (st & DITEM_RESTORE) {
-			touchwin(save);
-			wrefresh(save);
-		    }
-		    delwin(save);
-		}
-	    }
-	    else if (result) {
-		*result = '\0';
-		for (i = 0; i < item_no; i++) {
-		    if (status[i]) {
-			strcat(result, items[i*3]);
-			break;
-		    }
-		}
-	    }
-	    rval = 0;
-	    key = ESC;
-	    break;
-	}
-
-	/* Shortcut to cancel */
-	if (toupper(key) == cancelButton) {
-	    if (ditems && result && ditems[CANCEL_BUTTON].fire) {
-		int st;
-		WINDOW *save;
-
-		save = dupwin(newscr);
-		st = ditems[CANCEL_BUTTON].fire(&ditems[CANCEL_BUTTON]);
-		if (st & DITEM_RESTORE) {
-		    touchwin(save);
-		    wrefresh(save);
-		}
-		delwin(save);
-	    }
-	    rval = 1;
-	    key = ESC;
-	    break;
-	}
-	
-	/* Check if key pressed matches first character of any item tag in list */
-	for (i = 0; i < max_choice; i++)
-	    if (key != ' ' && toupper(key) == toupper(items[(scroll + i) * 3][0]))
-		break;
-
-	if (i < max_choice || (key >= '1' && key <= MIN('9', '0' + max_choice)) ||
-	    KEY_IS_UP(key) || KEY_IS_DOWN(key) || ((key == ' ' || key == '\r' || key == '\n') && onlist == 1)) {
-
-	    /* if moving from buttons to the list, reset and redraw buttons */
-	    if (!onlist) {
-		onlist = 1;
-		button = 0;
-
-	    	if (ditems && result ) {
-		    print_button(dialog, ditems[CANCEL_BUTTON].prompt, y, x + strlen(ditems[OK_BUTTON].prompt) + 5,
-			ditems[CANCEL_BUTTON].checked ? ditems[CANCEL_BUTTON].checked(&ditems[CANCEL_BUTTON]) : button);
-		    print_button(dialog, ditems[OK_BUTTON].prompt, y, x,
-			ditems[OK_BUTTON].checked ? ditems[OK_BUTTON].checked(&ditems[OK_BUTTON]) : !button);
-		}
-		else {
-		    print_button(dialog, "Cancel", y, x + 14, button);
-		    print_button(dialog, "  OK  ", y, x, !button);
-		}
-	    }
-	    wmove(list, choice, check_x+1);
-	    wnoutrefresh(dialog);
-	    wrefresh(list);
-
-	    if (key >= '1' && key <= MIN('9', '0' + max_choice))
-		i = key - '1';
-	    else if (KEY_IS_UP(key)) {
-		if (!choice) {
-		    if (scroll) {
-			/* Scroll list down */
-			getyx(dialog, cur_y, cur_x);    /* Save cursor position */
-			if (list_height > 1) {
-			    /* De-highlight current first item before scrolling down */
-			    print_item(list, items[scroll*3], items[scroll*3 + 1], status[scroll], 0,
-				       FALSE, DREF(ditems, scroll));
-			    scrollok(list, TRUE);
-			    wscrl(list, -1);
-			    scrollok(list, FALSE);
-			}
-			scroll--;
-			print_item(list, items[scroll*3], items[scroll*3 + 1], status[scroll], 0,
-				   TRUE, DREF(ditems, scroll));
-			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);
-		    }
-		    continue;    /* wait for another key press */
-		}
-		else
-		    i = choice - 1;
-	    }
-	    else if (KEY_IS_DOWN(key)) {
-		if (choice == max_choice - 1) {
-		    if (scroll + choice < item_no - 1) {
-			/* Scroll list up */
-			getyx(dialog, cur_y, cur_x);    /* Save cursor position */
-			if (list_height > 1) {
-			    /* De-highlight current last item before scrolling up */
-			    print_item(list, items[(scroll + max_choice - 1) * 3],
-				       items[(scroll + max_choice - 1) * 3 + 1],
-				       status[scroll + max_choice - 1], max_choice - 1,
-				       FALSE, DREF(ditems, scroll + max_choice - 1));
-			    scrollok(list, TRUE);
-			    scroll(list);
-			    scrollok(list, FALSE);
-			}
-			scroll++;
-			print_item(list, items[(scroll + max_choice - 1) * 3],
-				   items[(scroll + max_choice - 1) * 3 + 1],
-				   status[scroll + max_choice - 1], max_choice - 1,
-				   TRUE, DREF(ditems, scroll + max_choice - 1));
-			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);
-		    }
-		    continue;    /* wait for another key press */
-		}
-		else
-		    i = choice + 1;
-	    }
-	    else if ((key == ' ' || key == '\r' || key == '\n') && onlist) {    /* Toggle item status */
-		getyx(list, old_y, old_x);     /* Save cursor position */
-		if (status[scroll + choice])
-		    continue;
-		else if (ditems) {
-		    if (ditems[scroll + choice].fire) {
-			int st;
-			WINDOW *save;
-
-			save = dupwin(newscr);
-			st = ditems[scroll + choice].fire(&ditems[scroll + choice]);
-			if (st & DITEM_RESTORE) {
-			    touchwin(save);
-			    wrefresh(save);
-			}
-			delwin(save);
-			if (st & DITEM_REDRAW) {
-			    wclear(list);
-			    for (i = 0; i < item_no; i++)
-				status[i] = ditems[i].checked ? ditems[i].checked(&ditems[i]) : FALSE;
-
-			    for (i = 0; i < max_choice; i++) {
-				print_item(list, items[(scroll + i) * 3], items[(scroll + i) * 3 + 1],
-					   status[scroll + i], i, i == choice,
-					   DREF(ditems, scroll + i));
-			    }
-/*			    wmove(list, old_y, old_x);*/  /* Restore cursor to previous position */
-/*			    wrefresh(list); */
-			}
-			if (st & DITEM_LEAVE_MENU) {
-			    /* Allow a fire action to take us out of the menu */
-			    key = ESC;
-			    break;
-			}
-			else if (st & DITEM_RECREATE) {
-			    delwin(list);
-			    delwin(dialog);
-			    dialog_clear();
-			    goto draw;
-			}
-		    }
-		    for (i = 0; i < item_no; i++)
-			status[i] = ditems[i].checked ? ditems[i].checked(&ditems[i]) : FALSE;
-		}
-		else {
-		    for (i = 0; i < item_no; i++)
-			status[i] = 0;
-		    status[scroll + choice] = TRUE;
-		}
-		for (i = 0; i < max_choice; i++)
-		    print_item(list, items[(scroll + i) * 3], items[(scroll + i) * 3 + 1],
-			       status[scroll + i], i, i == choice, DREF(ditems, scroll + i));
-		wmove(list, choice, check_x+1);  /* Restore cursor position */
-		wrefresh(list);
-		continue;    /* wait for another key press */
-	    }
-	    
-	    if (i != choice) {
-		/* De-highlight current item */
-		print_item(list, items[(scroll + choice) * 3], items[(scroll + choice) * 3 +1],
-			   status[scroll + choice], choice, FALSE, DREF(ditems, scroll + choice));
-		/* Highlight new item */
-		choice = i;
-		print_item(list, items[(scroll + choice) * 3], items[(scroll + choice) * 3 + 1],
-			   status[scroll + choice], choice, TRUE, DREF(ditems, scroll + choice));
-		wmove(list, choice, check_x+1);  /* Restore cursor position */
-		wrefresh(list);
-	    }
-	    continue;    /* wait for another key press */
-	}
-	
-	switch (key) {
-	case KEY_PPAGE:
-	    if (scroll > height-4)		/* can we go up? */
-		scroll -= (height-4);
-	    else
-		scroll = 0;
-	    redraw_menu = TRUE;
-	    if (!onlist) {
-		onlist = 1;
-		button = 0;
-	    }
-	    break;
-	    
-	case KEY_NPAGE:
-	    if (scroll + list_height >= item_no-1 - list_height) { /* can we go down a full page? */
-		scroll = item_no - list_height;
-		if (scroll < 0)
-		    scroll = 0;
-	    }
-	    else
-		scroll += list_height;
-	    redraw_menu = TRUE;
-	    if (!onlist) {
-		onlist = 1;
-		button = 0;
-	    }
-	    break;
-	    
-	case KEY_HOME:
-	    scroll = 0;
-	    choice = 0;
-	    redraw_menu = TRUE;
-	    cursor_reset = TRUE;
-	    onlist = 1;
-	    break;
-	    
-	case KEY_END:
-	    scroll = item_no - list_height;
-	    if (scroll < 0)
-		scroll = 0;
-	    choice = max_choice - 1;
-	    redraw_menu = TRUE;
-	    cursor_reset = TRUE;
-	    onlist = 1;
-	    break;
-	    
-	case TAB:
-	case KEY_BTAB:
-	    /* move to next component */
-	    if (onlist) {      /* on list, next is ok button */
-		onlist = 0;
-		if (ditems && result)
-		    ok_space = 1;
-		else
-		    ok_space = 3;
-		wmove(dialog, y, x + ok_space);
-		wrefresh(dialog);
-		break;
-	    }
-	    else if (button) {      /* on cancel button, next is list */
-		button = 0;
-		onlist = 1;
-		redraw_menu = TRUE;
-		break;
-	    }
-	    /* on ok button, next is cancel button, same as left/right case */
-
-	case KEY_LEFT:
-	case KEY_RIGHT:
-	    onlist = 0;
-	    button = !button;
-	    if (ditems && result) {
-		print_button(dialog, ditems[CANCEL_BUTTON].prompt, y, x + strlen(ditems[OK_BUTTON].prompt) + 5,
-			     ditems[CANCEL_BUTTON].checked ? ditems[CANCEL_BUTTON].checked(&ditems[CANCEL_BUTTON]) : button);
-		print_button(dialog, ditems[OK_BUTTON].prompt, y, x,
-			     ditems[OK_BUTTON].checked ? ditems[OK_BUTTON].checked(&ditems[OK_BUTTON]) : !button);
-		ok_space = 1;
-		cancel_space = strlen(ditems[OK_BUTTON].prompt) + 6;
-	    }
-	    else {
-		print_button(dialog, "Cancel", y, x + 14, button);
-		print_button(dialog, "  OK  ", y, x, !button);
-		ok_space = 3;
-		cancel_space = 15;
-	    }
-	    if (button)
-		wmove(dialog, y, x + cancel_space);
-	    else
-		wmove(dialog, y, x + ok_space);
-	    wrefresh(dialog);
-	    break;
-
-	case ' ':	    
-	case '\r':
-	case '\n':
-	    if (!onlist) {
-		if (ditems) {
-		    if (result && ditems[button ? CANCEL_BUTTON : OK_BUTTON].fire) {
-			int st;
-			WINDOW *save;
-
-			save = dupwin(newscr);
-			st = ditems[button ? CANCEL_BUTTON : OK_BUTTON].fire(&ditems[button ? CANCEL_BUTTON : OK_BUTTON]);
-			if (st & DITEM_RESTORE) {
-			    touchwin(save);
-			    wrefresh(save);
-			}
-			delwin(save);
-		    }
-		}
-		else if (result) {
-		    *result = '\0';
-		    for (i = 0; i < item_no; i++) {
-			if (status[i]) {
-			    strcpy(result, items[i*3]);
-			    break;
-			}
-		    }
-		}
-		rval = button;
-		key = ESC;
-		break;
-	    }
-	    
-	case ESC:
-	    rval = -1;
-	    break;
-	    
-	case KEY_F(1):
-	case '?':
-	    display_helpfile();
-	    break;
-	}
-	
-	if (redraw_menu) {
-	    getyx(list, old_y, old_x);
-	    wclear(list);
-	    for (i = 0; i < max_choice; i++)
-		print_item(list, items[(scroll + i) * 3], items[(scroll + i) * 3 + 1], status[scroll + i],
-			   i, i == choice, DREF(ditems, scroll + i));
-	    print_arrows(dialog, scroll, list_height, item_no, box_x, box_y, check_x + 4, cur_x, cur_y);
-
-	    /* redraw buttons to fix highlighting */
-	    if (ditems && result) {
-		print_button(dialog, ditems[CANCEL_BUTTON].prompt, y, x + strlen(ditems[OK_BUTTON].prompt) + 5,
-			ditems[CANCEL_BUTTON].checked ? ditems[CANCEL_BUTTON].checked(&ditems[CANCEL_BUTTON]) : button);
-		print_button(dialog, ditems[OK_BUTTON].prompt, y, x,
-			ditems[OK_BUTTON].checked ? ditems[OK_BUTTON].checked(&ditems[OK_BUTTON]) : !button);
-	    }
-	    else {
-		print_button(dialog, "Cancel", y, x + 14, button);
-		print_button(dialog, "  OK  ", y, x, !button);
-	    }
-	    wnoutrefresh(dialog);
-	    if (cursor_reset) {
-		wmove(list, choice, check_x+1);
-		cursor_reset = FALSE;
-	    }
-	    else {
-		wmove(list, old_y, old_x);
-	    }
-	    wrefresh(list);
-	    redraw_menu = FALSE;
-	}
-    }
-    
-    delwin(list);
-    delwin(dialog);
-    return rval;    /* ESC pressed */
-}
-
-/*
- * Print list item
- */
-static void
-print_item(WINDOW *win, char *tag, char *item, int status, int choice, int selected, dialogMenuItem *me)
-{
-    int i;
-    
-    /* Clear 'residue' of last item */
-    wattrset(win, menubox_attr);
-    wmove(win, choice, 0);
-    for (i = 0; i < list_width; i++)
-	waddch(win, ' ');
-    wmove(win, choice, check_x);
-    wattrset(win, selected ? check_selected_attr : check_attr);
-    wprintw(win, "%c%c%c", me && me->lbra ? me->lbra : '(',
-	    status ? me && me->mark ? me->mark : '*' : ' ',
-	    me && me->rbra ? me->rbra : ')');
-    wattrset(win, menubox_attr);
-    waddch(win, ' ');
-    wattrset(win, selected ? tag_key_selected_attr : tag_key_attr);
-    waddch(win, tag[0]);
-    wattrset(win, selected ? tag_selected_attr : tag_attr);
-    waddstr(win, tag + 1);
-    wmove(win, choice, item_x);
-    wattrset(win, selected ? item_selected_attr : item_attr);
-    waddstr(win, item);
-    /* If have a selection handler for this, call it */
-    if (me && me->selected) {
-	wrefresh(win);
-	me->selected(me, selected);
-    }
-}
-/* End of print_item() */
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/raw_popen.c
--- a/head/gnu/lib/libodialog/raw_popen.c	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,161 +0,0 @@
-/*
- * Copyright (c) 1988, 1993
- *	The Regents of the University of California.  All rights reserved.
- *
- * This code is derived from software written by Ken Arnold and
- * published in UNIX Review, Vol. 6, No. 8.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 3. All advertising materials mentioning features or use of this software
- *    must display the following acknowledgement:
- *	This product includes software developed by the University of
- *	California, Berkeley and its contributors.
- * 4. Neither the name of the University nor the names of its contributors
- *    may be used to endorse or promote products derived from this software
- *    without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#if defined(LIBC_SCCS) && !defined(lint)
-static char sccsid[] = "@(#)popen.c	8.1 (Berkeley) 6/4/93";
-#endif /* LIBC_SCCS and not lint */
-#include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
-
-#include <sys/param.h>
-#include <sys/wait.h>
-
-#include <signal.h>
-#include <errno.h>
-#include <unistd.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <paths.h>
-
-static struct pid {
-	struct pid *next;
-	FILE *fp;
-	pid_t pid;
-} *pidlist;
-
-FILE *
-raw_popen(const char *program, char * const *argv, const char *type)
-{
-	struct pid *cur;
-	FILE *iop;
-	int pdes[2], pid;
-
-	if ((*type != 'r' && *type != 'w') || type[1])
-		return (NULL);
-
-	if ((cur = malloc(sizeof(struct pid))) == NULL)
-		return (NULL);
-
-	if (pipe(pdes) < 0) {
-		(void)free(cur);
-		return (NULL);
-	}
-
-	switch (pid = vfork()) {
-	case -1:			/* Error. */
-		(void)close(pdes[0]);
-		(void)close(pdes[1]);
-		(void)free(cur);
-		return (NULL);
-		/* NOTREACHED */
-	case 0:				/* Child. */
-		if (*type == 'r') {
-			if (pdes[1] != STDOUT_FILENO) {
-				(void)dup2(pdes[1], STDOUT_FILENO);
-				(void)close(pdes[1]);
-			}
-			(void) close(pdes[0]);
-		} else {
-			if (pdes[0] != STDIN_FILENO) {
-				(void)dup2(pdes[0], STDIN_FILENO);
-				(void)close(pdes[0]);
-			}
-			(void)close(pdes[1]);
-		}
-		if (argv == NULL)
-			execl(_PATH_BSHELL, "sh", "-c", program, (char *)NULL);
-		else
-			execvp(program, argv);
-		_exit(127);
-		/* NOTREACHED */
-	}
-
-	/* Parent; assume fdopen can't fail. */
-	if (*type == 'r') {
-		iop = fdopen(pdes[0], type);
-		(void)close(pdes[1]);
-	} else {
-		iop = fdopen(pdes[1], type);
-		(void)close(pdes[0]);
-	}
-
-	/* Link into list of file descriptors. */
-	cur->fp = iop;
-	cur->pid =  pid;
-	cur->next = pidlist;
-	pidlist = cur;
-
-	return (iop);
-}
-
-/*
- * pclose --
- *	Pclose returns -1 if stream is not associated with a `popened' command,
- *	if already `pclosed', or waitpid returns an error.
- */
-int
-raw_pclose(FILE *iop)
-{
-	register struct pid *cur, *last;
-	int omask, pstat;
-	pid_t pid;
-
-	(void)fclose(iop);
-
-	/* Find the appropriate file pointer. */
-	for (last = NULL, cur = pidlist; cur; last = cur, cur = cur->next)
-		if (cur->fp == iop)
-			break;
-	if (cur == NULL)
-		return (-1);
-
-	/* Get the status of the process. */
-	omask = sigblock(sigmask(SIGINT)|sigmask(SIGQUIT)|sigmask(SIGHUP));
-	do {
-		pid = waitpid(cur->pid, (int *) &pstat, 0);
-	} while (pid == -1 && errno == EINTR);
-	(void)sigsetmask(omask);
-
-	/* Remove the entry from the linked list. */
-	if (last == NULL)
-		pidlist = cur->next;
-	else
-		last->next = cur->next;
-	free(cur);
-
-	return (pid == -1 ? -1 : pstat);
-}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/rc.c
--- a/head/gnu/lib/libodialog/rc.c	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,375 +0,0 @@
-/*
- *  rc.c -- routines for processing the configuration file
- *
- *  AUTHOR: Savio Lam (lam836 at cs.cuhk.hk)
- *
- *  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., 675 Mass Ave, Cambridge, MA 02139, USA.
- */
-
-#include <dialog.h>
-#include "dialog.priv.h"
-#include "colors.h"
-#include "rc.h"
-
-
-static unsigned char *attr_to_str(int fg, int bg, int hl);
-static int str_to_attr(unsigned char *str, int *fg, int *bg, int *hl);
-static int parse_line(unsigned char *line, unsigned char **var, unsigned char **value);
-
-
-/*
- * Create the configuration file
- */
-void dialog_create_rc(unsigned char *filename)
-{
-  int i;
-  FILE *rc_file;
-
-  if ((rc_file = fopen(filename, "wt")) == NULL) {
-    fprintf(stderr, "\nError opening file for writing in create_rc().\n");
-    exit(-1);
-  }
-
-  fprintf(rc_file, "#\
-\n# Run-time configuration file for dialog\
-\n#\
-\n# Automatically generated by \"dialog --create-rc <file>\"\
-\n#\
-\n#\
-\n# Types of values:\
-\n#\
-\n# Number     -  <number>\
-\n# String     -  \"string\"\
-\n# Boolean    -  <ON|OFF>\
-\n# Attribute  -  (foreground,background,highlight?)\
-\n#\n\n");
-
-  /* Print an entry for each configuration variable */
-  for (i = 0; i < VAR_COUNT; i++) {
-    fprintf(rc_file, "\n# %s\n", vars[i].comment);    /* print comment */
-    switch (vars[i].type) {
-      case VAL_INT:
-        fprintf(rc_file, "%s = %d\n", vars[i].name, *((int *) vars[i].var));
-        break;
-      case VAL_STR:
-        fprintf(rc_file, "%s = \"%s\"\n", vars[i].name, (unsigned char *) vars[i].var);
-        break;
-      case VAL_BOOL:
-        fprintf(rc_file, "%s = %s\n", vars[i].name, *((bool *) vars[i].var) ? "ON" : "OFF");
-        break;
-      case VAL_ATTR:
-        fprintf(rc_file, "%s = %s\n", vars[i].name, attr_to_str(((int *) vars[i].var)[0], ((int *) vars[i].var)[1], ((int *) vars[i].var)[2]));
-        break;
-    }
-  }
-
-  fclose(rc_file);
-}
-/* End of create_rc() */
-
-
-/*
- * Parse the configuration file and set up variables
- */
-int parse_rc(void)
-{
-  int i, l = 1, parse, fg, bg, hl;
-  unsigned char str[MAX_LEN+1], *var, *value, *tempptr;
-  FILE *rc_file;
-
-  /*
-   *
-   *  At start, 'dialog' determines the settings to use as follows:
-   *
-   *  a) if environment variable DIALOGRC is set, it's value determines the
-   *     name of the configuration file.
-   *
-   *  b) if the file in (a) can't be found, use the file $HOME/.dialogrc
-   *     as the configuration file.
-   *
-   *  c) if the file in (b) can't be found, use compiled in defaults.
-   *
-   */
-
-  if ((tempptr = getenv("DIALOGRC")) != NULL)
-    rc_file = fopen(tempptr, "rt");
-
-  if (tempptr == NULL || rc_file == NULL) {    /* step (a) failed? */
-    /* try step (b) */
-    if ((tempptr = getenv("HOME")) == NULL)
-      return 0;    /* step (b) failed, use default values */
-
-    if (tempptr[0] == '\0' || lastch(tempptr) == '/')
-      sprintf(str, "%s%s", tempptr, DIALOGRC);
-    else
-      sprintf(str, "%s/%s", tempptr, DIALOGRC);
-
-    if ((rc_file = fopen(str, "rt")) == NULL)
-      return 0;    /* step (b) failed, use default values */
-  }
-
-  /* Scan each line and set variables */
-  while (fgets(str, MAX_LEN, rc_file) != NULL) {
-    if (lastch(str) != '\n') {    /* ignore rest of file if line too long */
-      fprintf(stderr, "\nParse error: line %d of configuration file too long.\n", l);
-      fclose(rc_file);
-      return -1;    /* parse aborted */
-    }
-    else {
-      lastch(str) = '\0';
-      parse = parse_line(str, &var, &value);    /* parse current line */
-
-      switch (parse) {
-	case LINE_BLANK:    /* ignore blank lines and comments */
-        case LINE_COMMENT:
-          break;
-        case LINE_OK:
-          /* search table for matching config variable name */
-          for (i = 0; i < VAR_COUNT && strcmp(vars[i].name, var); i++);
-
-          if (i == VAR_COUNT) {    /* no match */
-            fprintf(stderr, "\nParse error: unknown variable at line %d of configuration file.\n", l);
-            return -1;    /* parse aborted */
-          }
-          else {    /* variable found in table, set run time variables */
-            switch (vars[i].type) {
-              case VAL_INT:
-                *((int *) vars[i].var) = atoi(value);
-                break;
-              case VAL_STR:
-                if (!isquote(value[0]) || !isquote(lastch(value)) || strlen(value) < 2) {
-                  fprintf(stderr, "\nParse error: string value expected at line %d of configuration file.\n", l);
-                  return -1;    /* parse aborted */
-                }
-                else {
-                  /* remove the (") quotes */
-                  value++;
-                  lastch(value) = '\0';
-                  strcpy((unsigned char *) vars[i].var, value);
-		}
-                break;
-              case VAL_BOOL:
-                if (!strcasecmp(value, "ON"))
-                  *((bool *) vars[i].var) = TRUE;
-                else if (!strcasecmp(value, "OFF"))
-                  *((bool *) vars[i].var) = FALSE;
-                else {
-                  fprintf(stderr, "\nParse error: boolean value expected at line %d of configuration file.\n", l);
-                  return -1;    /* parse aborted */
-                }
-                break;
-              case VAL_ATTR:
-                if (str_to_attr(value, &fg, &bg, &hl) == -1) {
-                  fprintf(stderr, "\nParse error: attribute value expected at line %d of configuration file.\n", l);
-                  return -1;    /* parse aborted */
-                }
-                ((int *) vars[i].var)[0] = fg;
-                ((int *) vars[i].var)[1] = bg;
-                ((int *) vars[i].var)[2] = hl;
-                break;
-            }
-          }
-          break;
-        case LINE_ERROR:
-          fprintf(stderr, "\nParse error: syntax error at line %d of configuration file.\n", l);
-          return -1;    /* parse aborted */
-      }
-    }
-
-    l++;    /* next line */
-  }
-
-  fclose(rc_file);
-  return 0;    /* parse successful */
-}
-/* End of parse_rc() */
-
-
-/*
- * Convert an attribute to a string representation like this:
- *
- * "(foreground,background,highlight)"
- */
-static unsigned char *attr_to_str(int fg, int bg, int hl)
-{
-  int i;
-  static unsigned char str[MAX_LEN+1];
-
-  strcpy(str, "(");
-  /* foreground */
-  for (i = 0; fg != color_names[i].value; i++);
-  strcat(str, color_names[i].name);
-  strcat(str, ",");
-
-  /* background */
-  for (i = 0; bg != color_names[i].value; i++);
-  strcat(str, color_names[i].name);
-
-  /* highlight */
-  strcat(str, hl ? ",ON)" : ",OFF)");
-
-  return str;
-}
-/* End of attr_to_str() */
-
-
-/*
- * Extract the foreground, background and highlight values from an attribute
- * represented as a string in this form:
- *
- * "(foreground,background,highlight)"
- */
-static int str_to_attr(unsigned char *str, int *fg, int *bg, int *hl)
-{
-  int i = 0, j, get_fg = 1;
-  unsigned char tempstr[MAX_LEN+1], *part;
-
-  if (str[0] != '(' || lastch(str) != ')')
-    return -1;    /* invalid representation */
-
-  /* remove the parenthesis */
-  strcpy(tempstr, str + 1);
-  lastch(tempstr) = '\0';
-
-
-  /* get foreground and background */
-
-  while (1) {
-    /* skip white space before fg/bg string */
-    while (whitespace(tempstr[i]) && tempstr[i] != '\0') i++;
-    if (tempstr[i] == '\0')
-      return -1;    /* invalid representation */
-    part = tempstr + i;    /* set 'part' to start of fg/bg string */
-
-    /* find end of fg/bg string */
-    while(!whitespace(tempstr[i]) && tempstr[i] != ',' && tempstr[i] != '\0') i++;
-
-    if (tempstr[i] == '\0')
-      return -1;    /* invalid representation */
-    else if (whitespace(tempstr[i])) {   /* not yet ',' */
-      tempstr[i++] = '\0';
-
-      /* skip white space before ',' */
-      while(whitespace(tempstr[i]) && tempstr[i] != '\0') i++;
-
-      if (tempstr[i] != ',')
-        return -1;    /* invalid representation */
-    }
-
-    tempstr[i++] = '\0';    /* skip the ',' */
-    for (j = 0; j < COLOR_COUNT && strcasecmp(part, color_names[j].name); j++);
-    if (j == COLOR_COUNT)    /* invalid color name */
-      return -1;
-    if (get_fg) {
-      *fg = color_names[j].value;
-      get_fg = 0;    /* next we have to get the background */
-    }
-    else {
-      *bg = color_names[j].value;
-      break;
-    }
-  }   /* got foreground and background */
-
-
-  /* get highlight */
-
-  /* skip white space before highlight string */
-  while (whitespace(tempstr[i]) && tempstr[i] != '\0') i++;
-  if (tempstr[i] == '\0')
-    return -1;    /* invalid representation */
-  part = tempstr + i;    /* set 'part' to start of highlight string */
-
-  /* trim trailing white space from highlight string */
-  i = strlen(part) - 1;
-  while(whitespace(part[i])) i--;
-  part[i+1] = '\0';
-
-  if (!strcasecmp(part, "ON"))
-    *hl = TRUE;
-  else if (!strcasecmp(part, "OFF"))
-    *hl = FALSE;
-  else
-    return -1;    /* invalid highlight value */
-
-  return 0;
-}
-/* End of str_to_attr() */
-
-
-/*
- * Parse a line in the configuration file
- *
- * Each line is of the form:  "variable = value". On exit, 'var' will contain
- * the variable name, and 'value' will contain the value string.
- *
- * Return values:
- *
- * LINE_BLANK   - line is blank
- * LINE_COMMENT - line is comment
- * LINE_OK      - line is ok
- * LINE_ERROR   - syntax error in line
- */
-static int parse_line(unsigned char *line, unsigned char **var, unsigned char **value)
-{
-  int i = 0;
-
-  /* ignore white space at beginning of line */
-  while(whitespace(line[i]) && line[i] != '\0') i++;
-
-  if (line[i] == '\0')    /* line is blank */
-    return LINE_BLANK;
-  else if (line[i] == '#')    /* line is comment */
-    return LINE_COMMENT;
-  else if (line[i] == '=')    /* variables names can't strart with a '=' */
-    return LINE_ERROR;
-
-  /* set 'var' to variable name */
-  *var = line + i++;    /* skip to next character */
-
-  /* find end of variable name */
-  while(!whitespace(line[i]) && line[i] != '=' && line[i] != '\0') i++;
-
-  if (line[i] == '\0')    /* syntax error */
-    return LINE_ERROR;
-  else if (line[i] == '=')
-    line[i++] = '\0';
-  else {
-    line[i++] = '\0';
-
-    /* skip white space before '=' */
-    while(whitespace(line[i]) && line[i] != '\0') i++;
-
-    if (line[i] != '=')    /* syntax error */
-      return LINE_ERROR;
-    else
-      i++;    /* skip the '=' */
-  }
-
-  /* skip white space after '=' */
-  while(whitespace(line[i]) && line[i] != '\0') i++;
-
-  if (line[i] == '\0')
-    return LINE_ERROR;
-  else
-    *value = line + i;    /* set 'value' to value string */
-
-  /* trim trailing white space from 'value' */
-  i = strlen(*value) - 1;
-  while(whitespace((*value)[i])) i--;
-  (*value)[i+1] = '\0';
-
-  return LINE_OK;    /* no syntax error in line */
-}
-/* End of parse_line() */
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/rc.h
--- a/head/gnu/lib/libodialog/rc.h	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,222 +0,0 @@
-/*
- *  rc.h -- declarations for configuration file processing
- *
- *  AUTHOR: Savio Lam (lam836 at cs.cuhk.hk)
- *
- *  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., 675 Mass Ave, Cambridge, MA 02139, USA.
- */
-
-
-#define DIALOGRC ".dialogrc"
-#define VAR_LEN 30
-#define COMMENT_LEN 70
-
-/* Types of values */
-#define VAL_INT  0
-#define VAL_STR  1
-#define VAL_BOOL 2
-#define VAL_ATTR 3
-
-/* Type of line in configuration file */
-#define LINE_BLANK    2
-#define LINE_COMMENT  1
-#define LINE_OK       0
-#define LINE_ERROR   -1
-
-/* number of configuration variables */
-#define VAR_COUNT        (sizeof(vars) / sizeof(vars_st))
-
-/* check if character is white space */
-#define whitespace(c)    (c == ' ' || c == '\t')
-
-/* check if character is string quoting characters */
-#define isquote(c)       (c == '"' || c == '\'')
-
-/* get last character of string */
-#define lastch(str)      str[strlen(str)-1]
-
-/*
- * Configuration variables
- */
-typedef struct {
-  unsigned char      name[VAR_LEN];  /* name of configuration variable as in DIALOGRC */
-  void     *var;            /* address of actually variable to change */
-  int       type;           /* type of value */
-  unsigned char      comment[COMMENT_LEN];    /* comment to put in "rc" file */
-} vars_st;
-
-vars_st vars[] = {
-  {  "use_shadow",
-     &use_shadow,
-     VAL_BOOL,
-     "Shadow dialog boxes? This also turns on color."                        },
-
-  {  "use_colors",
-     &use_colors,
-     VAL_BOOL,
-     "Turn color support ON or OFF"                                          },
-
-  {  "screen_color",
-     color_table[0],
-     VAL_ATTR,
-     "Screen color"                                                          },
-
-  {  "shadow_color",
-     color_table[1],
-     VAL_ATTR,
-     "Shadow color"                                                          },
-
-  {  "dialog_color",
-     color_table[2],
-     VAL_ATTR,
-     "Dialog box color"                                                      },
-
-  {  "title_color",
-     color_table[3],
-     VAL_ATTR,
-     "Dialog box title color"                                                },
-
-  {  "border_color",
-     color_table[4],
-     VAL_ATTR,
-     "Dialog box border color"                                               },
-
-  {  "button_active_color",
-     color_table[5],
-     VAL_ATTR,
-     "Active button color"                                                   },
-
-  {  "button_inactive_color",
-     color_table[6],
-     VAL_ATTR,
-     "Inactive button color"                                                 },
-
-  {  "button_key_active_color",
-     color_table[7],
-     VAL_ATTR,
-     "Active button key color"                                               },
-
-  {  "button_key_inactive_color",
-     color_table[8],
-     VAL_ATTR,
-     "Inactive button key color"                                             },
-
-  {  "button_label_active_color",
-     color_table[9],
-     VAL_ATTR,
-     "Active button label color"                                             },
-
-  {  "button_label_inactive_color",
-     color_table[10],
-     VAL_ATTR,
-     "Inactive button label color"                                           },
-
-  {  "inputbox_color",
-     color_table[11],
-     VAL_ATTR,
-     "Input box color"                                                       },
-
-  {  "inputbox_border_color",
-     color_table[12],
-     VAL_ATTR,
-     "Input box border color"                                                },
-
-  {  "searchbox_color",
-     color_table[13],
-     VAL_ATTR,
-     "Search box color"                                                      },
-
-  {  "searchbox_title_color",
-     color_table[14],
-     VAL_ATTR,
-     "Search box title color"                                                },
-
-  {  "searchbox_border_color",
-     color_table[15],
-     VAL_ATTR,
-     "Search box border color"                                               },
-
-  {  "position_indicator_color",
-     color_table[16],
-     VAL_ATTR,
-     "File position indicator color"                                         },
-
-  {  "menubox_color",
-     color_table[17],
-     VAL_ATTR,
-     "Menu box color"                                                        },
-
-  {  "menubox_border_color",
-     color_table[18],
-     VAL_ATTR,
-     "Menu box border color"                                                 },
-
-  {  "item_color",
-     color_table[19],
-     VAL_ATTR,
-     "Item color"                                                            },
-
-  {  "item_selected_color",
-     color_table[20],
-     VAL_ATTR,
-     "Selected item color"                                                   },
-
-  {  "tag_color",
-     color_table[21],
-     VAL_ATTR,
-     "Tag color"                                                             },
-
-  {  "tag_selected_color",
-     color_table[22],
-     VAL_ATTR,
-     "Selected tag color"                                                    },
-
-  {  "tag_key_color",
-     color_table[23],
-     VAL_ATTR,
-     "Tag key color"                                                         },
-
-  {  "tag_key_selected_color",
-     color_table[24],
-     VAL_ATTR,
-     "Selected tag key color"                                                },
-
-  {  "check_color",
-     color_table[25],
-     VAL_ATTR,
-     "Check box color"                                                       },
-
-  {  "check_selected_color",
-     color_table[26],
-     VAL_ATTR,
-     "Selected check box color"                                              },
-
-  {  "uarrow_color",
-     color_table[27],
-     VAL_ATTR,
-     "Up arrow color"                                                        },
-
-  {  "darrow_color",
-     color_table[28],
-     VAL_ATTR,
-     "Down arrow color"                                                      }
-};    /* vars */
-
-
-
-/*
- * Routines to process configuration file
- */
-int parse_rc(void);
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/textbox.c
--- a/head/gnu/lib/libodialog/textbox.c	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,699 +0,0 @@
-/*
- *  textbox.c -- implements the text box
- *
- *  AUTHOR: Savio Lam (lam836 at cs.cuhk.hk)
- *
- *  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., 675 Mass Ave, Cambridge, MA 02139, USA.
- */
-
-#include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
-
-#include <dialog.h>
-#include "dialog.priv.h"
-
-
-static void back_lines(int n);
-static void print_page(WINDOW *win, int height, int width);
-static void print_line(WINDOW *win, int row, int width);
-static unsigned char *get_line(void);
-static int get_search_term(WINDOW *win, unsigned char *search_term, int height, int width);
-static void print_position(WINDOW *win, int height, int width);
-
-
-static int hscroll = 0, fd, file_size, bytes_read, begin_reached = 1,
-           end_reached = 0, page_length;
-static unsigned char *buf, *page;
-
-
-/*
- * Display text from a file in a dialog box.
- */
-int dialog_textbox(unsigned char *title, unsigned char *file, int height, int width)
-{
-  int i, x, y, cur_x, cur_y, fpos, key = 0, dir, temp, temp1;
-#ifdef HAVE_NCURSES
-  int passed_end;
-#endif
-  unsigned char search_term[MAX_LEN+1], *tempptr, *found;
-  WINDOW *dialog, *text;
-
-  if (height < 0 || width < 0) {
-    fprintf(stderr, "\nAutosizing is impossible in dialog_textbox().\n");
-    return(-1);
-  }
-
-  search_term[0] = '\0';    /* no search term entered yet */
-
-  /* Open input file for reading */
-  if ((fd = open(file, O_RDONLY)) == -1) {
-    fprintf(stderr, "\nCan't open input file <%s>in dialog_textbox().\n", file);
-    return(-1);
-  }
-  /* Get file size. Actually, 'file_size' is the real file size - 1,
-     since it's only the last byte offset from the beginning */
-  if ((file_size = lseek(fd, 0, SEEK_END)) == -1) {
-    fprintf(stderr, "\nError getting file size in dialog_textbox().\n");
-    return(-1);
-  }
-  /* Restore file pointer to beginning of file after getting file size */
-  if (lseek(fd, 0, SEEK_SET) == -1) {
-    fprintf(stderr, "\nError moving file pointer in dialog_textbox().\n");
-    return(-1);
-  }
-  /* Allocate space for read buffer */
-  if ((buf = malloc(BUF_SIZE+1)) == NULL) {
-    endwin();
-    fprintf(stderr, "\nCan't allocate memory in dialog_textbox().\n");
-    exit(-1);
-  }
-  if ((bytes_read = read(fd, buf, BUF_SIZE)) == -1) {
-    fprintf(stderr, "\nError reading file in dialog_textbox().\n");
-    return(-1);
-  }
-  buf[bytes_read] = '\0';    /* mark end of valid data */
-  page = buf;    /* page is pointer to start of page to be displayed */
-
-  if (width > COLS)
-	width = COLS;
-  if (height > LINES)
-	height = LINES;
-  /* center dialog box on screen */
-  x = DialogX ? DialogX : (COLS - width)/2;
-  y = DialogY ? DialogY : (LINES - height)/2;
-
-#ifdef HAVE_NCURSES
-  if (use_shadow)
-    draw_shadow(stdscr, y, x, height, width);
-#endif
-  dialog = newwin(height, width, y, x);
-  if (dialog == NULL) {
-    endwin();
-    fprintf(stderr, "\nnewwin(%d,%d,%d,%d) failed, maybe wrong dims\n", height,width,y,x);
-    exit(1);
-  }
-  keypad(dialog, TRUE);
-
-  /* Create window for text region, used for scrolling text */
-/*  text = newwin(height-4, width-2, y+1, x+1); */
-  text = subwin(dialog, height-4, width-2, y+1, x+1);
-  if (text == NULL) {
-    endwin();
-    fprintf(stderr, "\nsubwin(dialog,%d,%d,%d,%d) failed, maybe wrong dims\n", height-4,width-2,y+1,x+1);
-    exit(1);
-  }
-  keypad(text, TRUE);
-
-  draw_box(dialog, 0, 0, height, width, dialog_attr, border_attr);
-
-  wattrset(dialog, border_attr);
-  wmove(dialog, height-3, 0);
-  waddch(dialog, ACS_LTEE);
-  for (i = 0; i < width-2; i++)
-    waddch(dialog, ACS_HLINE);
-  wattrset(dialog, dialog_attr);
-  waddch(dialog, ACS_RTEE);
-  wmove(dialog, height-2, 1);
-  for (i = 0; i < width-2; i++)
-    waddch(dialog, ' ');
-
-  if (title != NULL) {
-    wattrset(dialog, title_attr);
-    wmove(dialog, 0, (width - strlen(title))/2 - 1);
-    waddch(dialog, ' ');
-    waddstr(dialog, title);
-    waddch(dialog, ' ');
-  }
-  display_helpline(dialog, height-1, width);
-
-  print_button(dialog, "  OK  ", height-2, width/2-6, TRUE);
-  wnoutrefresh(dialog);
-  getyx(dialog, cur_y, cur_x);    /* Save cursor position */
-
-  /* Print first page of text */
-  attr_clear(text, height-4, width-2, dialog_attr);
-  print_page(text, height-4, width-2);
-  print_position(dialog, height, width);
-  wmove(dialog, cur_y, cur_x);    /* Restore cursor position */
-  wrefresh(dialog);
-
-  while ((key != ESC) && (key != '\n') && (key != '\r') && (key != ' ')) {
-    key = wgetch(dialog);
-    switch (key) {
-      case 'E':    /* Exit */
-      case 'e':
-        delwin(dialog);
-        free(buf);
-        close(fd);
-        return 0;
-      case 'g':    /* First page */
-      case KEY_HOME:
-        if (!begin_reached) {
-          begin_reached = 1;
-          /* First page not in buffer? */
-          if ((fpos = lseek(fd, 0, SEEK_CUR)) == -1) {
-            endwin();
-            fprintf(stderr, "\nError moving file pointer in dialog_textbox().\n");
-            exit(-1);
-          }
-          if (fpos > bytes_read) {    /* Yes, we have to read it in */
-            if (lseek(fd, 0, SEEK_SET) == -1) {
-              endwin();
-              fprintf(stderr, "\nError moving file pointer in dialog_textbox().\n");
-              exit(-1);
-            }
-            if ((bytes_read = read(fd, buf, BUF_SIZE)) == -1) {
-              endwin();
-              fprintf(stderr, "\nError reading file in dialog_textbox().\n");
-              exit(-1);
-            }
-            buf[bytes_read] = '\0';
-          }
-          page = buf;
-          print_page(text, height-4, width-2);
-          print_position(dialog, height, width);
-          wmove(dialog, cur_y, cur_x);    /* Restore cursor position */
-          wrefresh(dialog);
-        }
-        break;
-      case 'G':    /* Last page */
-#ifdef HAVE_NCURSES
-      case KEY_END:
-#endif
-        end_reached = 1;
-        /* Last page not in buffer? */
-        if ((fpos = lseek(fd, 0, SEEK_CUR)) == -1) {
-          endwin();
-          fprintf(stderr, "\nError moving file pointer in dialog_textbox().\n");
-          exit(-1);
-        }
-        if (fpos < file_size) {    /* Yes, we have to read it in */
-          if (lseek(fd, -BUF_SIZE, SEEK_END) == -1) {
-            endwin();
-            fprintf(stderr, "\nError moving file pointer in dialog_textbox().\n");
-            exit(-1);
-          }
-          if ((bytes_read = read(fd, buf, BUF_SIZE)) == -1) {
-            endwin();
-            fprintf(stderr, "\nError reading file in dialog_textbox().\n");
-            exit(-1);
-          }
-          buf[bytes_read] = '\0';
-        }
-        page = buf + bytes_read;
-        back_lines(height-4);
-        print_page(text, height-4, width-2);
-        print_position(dialog, height, width);
-        wmove(dialog, cur_y, cur_x);    /* Restore cursor position */
-        wrefresh(dialog);
-        break;
-      case 'K':    /* Previous line */
-      case 'k':
-      case '\020':	/* ^P */
-      case KEY_UP:
-        if (!begin_reached) {
-          back_lines(page_length+1);
-#ifdef HAVE_NCURSES
-          /* We don't call print_page() here but use scrolling to ensure
-             faster screen update. However, 'end_reached' and 'page_length'
-             should still be updated, and 'page' should point to start of
-             next page. This is done by calling get_line() in the following
-             'for' loop. */
-          scrollok(text, TRUE);
-          wscrl(text, -1);    /* Scroll text region down one line */
-          scrollok(text, FALSE);
-          page_length = 0;
-          passed_end = 0;
-          for (i = 0; i < height-4; i++) {
-            if (!i) {
-              print_line(text, 0, width-2);    /* print first line of page */
-              wnoutrefresh(text);
-            }
-            else
-              get_line();    /* Called to update 'end_reached' and 'page' */
-            if (!passed_end)
-              page_length++;
-            if (end_reached && !passed_end)
-              passed_end = 1;
-          }
-#else
-          print_page(text, height-4, width-2);
-#endif
-          print_position(dialog, height, width);
-          wmove(dialog, cur_y, cur_x);    /* Restore cursor position */
-          wrefresh(dialog);
-        }
-        break;
-      case 'B':    /* Previous page */
-      case 'b':
-      case KEY_PPAGE:
-        if (!begin_reached) {
-          back_lines(page_length + height-4);
-          print_page(text, height-4, width-2);
-          print_position(dialog, height, width);
-          wmove(dialog, cur_y, cur_x);    /* Restore cursor position */
-          wrefresh(dialog);
-        }
-        break;
-      case 'J':    /* Next line */
-      case 'j':
-      case '\016':	/* ^N */
-      case KEY_DOWN:
-        if (!end_reached) {
-          begin_reached = 0;
-          scrollok(text, TRUE);
-          scroll(text);    /* Scroll text region up one line */
-          scrollok(text, FALSE);
-          print_line(text, height-5, width-2);
-#ifndef HAVE_NCURSES
-          wmove(text, height-5, 0);
-          waddch(text, ' ');
-          wmove(text, height-5, width-3);
-          waddch(text, ' ');
-#endif
-          wnoutrefresh(text);
-          print_position(dialog, height, width);
-          wmove(dialog, cur_y, cur_x);    /* Restore cursor position */
-          wrefresh(dialog);
-        }
-        break;
-      case 'F':    /* Next page */
-      case 'f':
-      case KEY_NPAGE:
-        if (!end_reached) {
-          begin_reached = 0;
-          print_page(text, height-4, width-2);
-          print_position(dialog, height, width);
-          wmove(dialog, cur_y, cur_x);    /* Restore cursor position */
-          wrefresh(dialog);
-        }
-        break;
-      case '0':    /* Beginning of line */
-      case 'H':    /* Scroll left */
-      case 'h':
-      case KEY_LEFT:
-        if (hscroll > 0) {
-          if (key == '0')
-            hscroll = 0;
-          else
-            hscroll--;
-          /* Reprint current page to scroll horizontally */
-          back_lines(page_length);
-          print_page(text, height-4, width-2);
-          wmove(dialog, cur_y, cur_x);    /* Restore cursor position */
-          wrefresh(dialog);
-        }
-        break;
-      case 'L':    /* Scroll right */
-      case 'l':
-      case KEY_RIGHT:
-        if (hscroll < MAX_LEN) {
-          hscroll++;
-          /* Reprint current page to scroll horizontally */
-          back_lines(page_length);
-          print_page(text, height-4, width-2);
-          wmove(dialog, cur_y, cur_x);    /* Restore cursor position */
-          wrefresh(dialog);
-        }
-        break;
-      case '/':    /* Forward search */
-      case 'n':    /* Repeat forward search */
-      case '?':    /* Backward search */
-      case 'N':    /* Repeat backward search */
-        /* set search direction */
-        dir = (key == '/' || key == 'n') ? 1 : 0;
-        if (dir ? !end_reached : !begin_reached) {
-          if (key == 'n' || key == 'N') {
-            if (search_term[0] == '\0') {    /* No search term yet */
-              fprintf(stderr, "\a");    /* beep */
-              break;
-            }
-	  }
-          else    /* Get search term from user */
-            if (get_search_term(text, search_term, height-4, width-2) == -1) {
-              /* ESC pressed in get_search_term(). Reprint page to clear box */
-              wattrset(text, dialog_attr);
-              back_lines(page_length);
-              print_page(text, height-4, width-2);
-              wmove(dialog, cur_y, cur_x);    /* Restore cursor position */
-              wrefresh(dialog);
-              break;
-            }
-          /* Save variables for restoring in case search term can't be found */
-          tempptr = page;
-          temp = begin_reached;
-          temp1 = end_reached;
-          if ((fpos = lseek(fd, 0, SEEK_CUR)) == -1) {
-            endwin();
-            fprintf(stderr, "\nError moving file pointer in dialog_textbox().\n");
-            exit(-1);
-          }
-          fpos -= bytes_read;
-          /* update 'page' to point to next (previous) line before
-             forward (backward) searching */
-          back_lines(dir ? page_length-1 : page_length+1);
-          found = NULL;
-          if (dir)    /* Forward search */
-            while((found = strstr(get_line(), search_term)) == NULL) {
-              if (end_reached)
-                break;
-	    }
-          else    /* Backward search */
-            while((found = strstr(get_line(), search_term)) == NULL) {
-              if (begin_reached)
-                break;
-              back_lines(2);
-            }
-          if (found == NULL) {    /* not found */
-            fprintf(stderr, "\a");    /* beep */
-            /* Restore program state to that before searching */
-            if (lseek(fd, fpos, SEEK_SET) == -1) {
-              endwin();
-              fprintf(stderr, "\nError moving file pointer in dialog_textbox().\n");
-              exit(-1);
-            }
-            if ((bytes_read = read(fd, buf, BUF_SIZE)) == -1) {
-              endwin();
-              fprintf(stderr, "\nError reading file in dialog_textbox().\n");
-              exit(-1);
-            }
-            buf[bytes_read] = '\0';
-            page = tempptr;
-            begin_reached = temp;
-            end_reached = temp1;
-            /* move 'page' to point to start of current page in order to
-               re-print current page. Note that 'page' always points to
-               start of next page, so this is necessary */
-            back_lines(page_length);
-          }
-          else    /* Search term found */
-            back_lines(1);
-          /* Reprint page */
-          wattrset(text, dialog_attr);
-          print_page(text, height-4, width-2);
-          if (found != NULL)
-            print_position(dialog, height, width);
-          wmove(dialog, cur_y, cur_x);    /* Restore cursor position */
-          wrefresh(dialog);
-        }
-        else    /* no need to find */
-          fprintf(stderr, "\a");    /* beep */
-        break;
-      case ESC:
-        break;
-    case KEY_F(1):
-	display_helpfile();
-	break;
-    }
-  }
-
-  delwin(dialog);
-  free(buf);
-  close(fd);
-  return (key == ESC ? -1 : 0);
-}
-/* End of dialog_textbox() */
-
-
-/*
- * Go back 'n' lines in text file. Called by dialog_textbox().
- * 'page' will be updated to point to the desired line in 'buf'.
- */
-static void back_lines(int n)
-{
-  int i, fpos;
-
-  begin_reached = 0;
-  /* We have to distinguish between end_reached and !end_reached since at end
-     of file, the line is not ended by a '\n'. The code inside 'if' basically
-     does a '--page' to move one character backward so as to skip '\n' of the
-     previous line */
-  if (!end_reached) {
-    /* Either beginning of buffer or beginning of file reached? */
-    if (page == buf) {
-      if ((fpos = lseek(fd, 0, SEEK_CUR)) == -1) {
-        endwin();
-        fprintf(stderr, "\nError moving file pointer in back_lines().\n");
-        exit(-1);
-      }
-      if (fpos > bytes_read) {    /* Not beginning of file yet */
-        /* We've reached beginning of buffer, but not beginning of file yet,
-           so read previous part of file into buffer. Note that we only
-           move backward for BUF_SIZE/2 bytes, but not BUF_SIZE bytes to
-           avoid re-reading again in print_page() later */
-        /* Really possible to move backward BUF_SIZE/2 bytes? */
-        if (fpos < BUF_SIZE/2 + bytes_read) {
-          /* No, move less then */
-          if (lseek(fd, 0, SEEK_SET) == -1) {
-            endwin();
-            fprintf(stderr, "\nError moving file pointer in back_lines().\n");
-            exit(-1);
-          }
-          page = buf + fpos - bytes_read;
-        }
-        else {    /* Move backward BUF_SIZE/2 bytes */
-          if (lseek(fd, -(BUF_SIZE/2 + bytes_read), SEEK_CUR) == -1) {
-            endwin();
-            fprintf(stderr, "\nError moving file pointer in back_lines().\n");
-            exit(-1);
-          }
-          page = buf + BUF_SIZE/2;
-        }
-        if ((bytes_read = read(fd, buf, BUF_SIZE)) == -1) {
-          endwin();
-          fprintf(stderr, "\nError reading file in back_lines().\n");
-          exit(-1);
-        }
-        buf[bytes_read] = '\0';
-      }
-      else {    /* Beginning of file reached */
-        begin_reached = 1;
-        return;
-      }
-    }
-    if (*(--page) != '\n') {    /* '--page' here */
-      /* Something's wrong... */
-      endwin();
-      fprintf(stderr, "\nInternal error in back_lines().\n");
-      exit(-1);
-    }
-  }
-
-  /* Go back 'n' lines */
-  for (i = 0; i < n; i++)
-    do {
-      if (page == buf) {
-        if ((fpos = lseek(fd, 0, SEEK_CUR)) == -1) {
-          endwin();
-          fprintf(stderr, "\nError moving file pointer in back_lines().\n");
-          exit(-1);
-        }
-        if (fpos > bytes_read) {
-          /* Really possible to move backward BUF_SIZE/2 bytes? */
-          if (fpos < BUF_SIZE/2 + bytes_read) {
-            /* No, move less then */
-            if (lseek(fd, 0, SEEK_SET) == -1) {
-              endwin();
-              fprintf(stderr, "\nError moving file pointer in back_lines().\n");
-              exit(-1);
-            }
-            page = buf + fpos - bytes_read;
-          }
-          else {    /* Move backward BUF_SIZE/2 bytes */
-            if (lseek(fd, -(BUF_SIZE/2 + bytes_read), SEEK_CUR) == -1) {
-              endwin();
-              fprintf(stderr, "\nError moving file pointer in back_lines().\n");
-              exit(-1);
-            }
-            page = buf + BUF_SIZE/2;
-          }
-          if ((bytes_read = read(fd, buf, BUF_SIZE)) == -1) {
-            endwin();
-            fprintf(stderr, "\nError reading file in back_lines().\n");
-            exit(-1);
-          }
-          buf[bytes_read] = '\0';
-        }
-        else {    /* Beginning of file reached */
-          begin_reached = 1;
-          return;
-        }
-      }
-    } while (*(--page) != '\n');
-  page++;
-}
-/* End of back_lines() */
-
-
-/*
- * Print a new page of text. Called by dialog_textbox().
- */
-static void print_page(WINDOW *win, int height, int width)
-{
-  int i, passed_end = 0;
-
-  page_length = 0;
-  for (i = 0; i < height; i++) {
-    print_line(win, i, width);
-    if (!passed_end)
-      page_length++;
-    if (end_reached && !passed_end)
-      passed_end = 1;
-  }
-  wnoutrefresh(win);
-}
-/* End of print_page() */
-
-
-/*
- * Print a new line of text. Called by dialog_textbox() and print_page().
- */
-static void print_line(WINDOW *win, int row, int width)
-{
-  int i, y, x;
-  unsigned char *line;
-
-  line = get_line();
-  line += MIN(strlen(line),hscroll);    /* Scroll horizontally */
-  wmove(win, row, 0);    /* move cursor to correct line */
-  waddch(win,' ');
-#ifdef HAVE_NCURSES
-  waddnstr(win, line, MIN(strlen(line),width-2));
-#else
-  line[MIN(strlen(line),width-2)] = '\0';
-  waddstr(win, line);
-#endif
-
-  getyx(win, y, x);
-  /* Clear 'residue' of previous line */
-  for (i = 0; i < width-x; i++)
-    waddch(win, ' ');
-}
-/* End of print_line() */
-
-
-/*
- * Return current line of text. Called by dialog_textbox() and print_line().
- * 'page' should point to start of current line before calling, and will be
- * updated to point to start of next line.
- */
-static unsigned char *get_line(void)
-{
-  int i = 0, fpos;
-  static unsigned char line[MAX_LEN+1];
-
-  end_reached = 0;
-  while (*page != '\n') {
-    if (*page == '\0') {    /* Either end of file or end of buffer reached */
-      if ((fpos = lseek(fd, 0, SEEK_CUR)) == -1) {
-        endwin();
-        fprintf(stderr, "\nError moving file pointer in get_line().\n");
-        exit(-1);
-      }
-      if (fpos < file_size) {    /* Not end of file yet */
-        /* We've reached end of buffer, but not end of file yet, so read next
-           part of file into buffer */
-        if ((bytes_read = read(fd, buf, BUF_SIZE)) == -1) {
-          endwin();
-          fprintf(stderr, "\nError reading file in get_line().\n");
-          exit(-1);
-        }
-        buf[bytes_read] = '\0';
-        page = buf;
-      }
-      else {
-        if (!end_reached)
-          end_reached = 1;
-        break;
-      }
-    }
-    else
-      if (i < MAX_LEN)
-        line[i++] = *(page++);
-      else {
-        if (i == MAX_LEN)  /* Truncate lines longer than MAX_LEN characters */
-          line[i++] = '\0';
-        page++;
-      }
-  }
-  if (i <= MAX_LEN)
-    line[i] = '\0';
-  if (!end_reached)
-    page++;    /* move pass '\n' */
-
-  return line;
-}
-/* End of get_line() */
-
-
-/*
- * Display a dialog box and get the search term from user
- */
-static int get_search_term(WINDOW *win, unsigned char *search_term, int height, int width)
-{
-  int x, y, key = 0, first,
-      box_height = 3, box_width = 30;
-
-  x = (width - box_width)/2;
-  y = (height - box_height)/2;
-#ifdef HAVE_NCURSES
-  if (use_shadow)
-    draw_shadow(win, y, x, box_height, box_width);
-#endif
-  draw_box(win, y, x, box_height, box_width, dialog_attr, searchbox_border_attr);
-  wattrset(win, searchbox_title_attr);
-  wmove(win, y, x+box_width/2-4);
-  waddstr(win, " Search ");
-  wattrset(win, dialog_attr);
-
-  search_term[0] = '\0';
-
-  first = 1;
-  while (key != ESC) {
-    key = line_edit(win, y+1, x+1, -1, box_width-2, searchbox_attr, first, search_term, 0);
-    first = 0;
-    switch (key) {
-      case '\n':
-        if (search_term[0] != '\0')
-          return 0;
-        break;
-      case ESC:
-	break;
-    }
-  }
-
-  return -1;    /* ESC pressed */
-}
-/* End of get_search_term() */
-
-
-/*
- * Print current position
- */
-static void print_position(WINDOW *win, int height, int width)
-{
-  int fpos, percent;
-
-  if ((fpos = lseek(fd, 0, SEEK_CUR)) == -1) {
-    endwin();
-    fprintf(stderr, "\nError moving file pointer in print_position().\n");
-    exit(-1);
-  }
-  wattrset(win, position_indicator_attr);
-  percent = !file_size ? 100 : ((fpos-bytes_read+page-buf)*100)/file_size;
-  wmove(win, height-3, width-9);
-  wprintw(win, "(%3d%%)", percent);
-}
-/* End of print_position() */
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/tree.c
--- a/head/gnu/lib/libodialog/tree.c	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,1133 +0,0 @@
-/*
- * tree.c -- implements the 'tree' interface element for libdialog
- *
- * Author: Anatoly A. Orehovsky (tolik at mpeks.tomsk.su)
- *
- * Copyright (c) 1997, Anatoly A. Orehovsky
- * 09/28/98 - patched by Anatoly A. Orehovsky (smart_tree())
- *
- */
-
-#include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
-
-#include <stdlib.h>
-#include <strings.h>
-#include <stdio.h>
-#include <dialog.h>
-#include "dialog.priv.h"
-#include <ncurses.h>
-
-/* static utils for make tree */
-struct leaf {
-	unsigned char *name;		/* name of leaf */
-	unsigned char *branches;	/* branches that going by leaf */
-	unsigned char slip;		/* slip of leaf*/
-	int shift;			/* shift relative root of tree */
-};
-
-static int	mk_slip(struct leaf array[], int arr_size, 
-			int number, int shift);
-
-/* make tree from file
- *
- * filename	- name of file with like find(1) output
- * p_names	- pointer to array of strings
- * p_size	- pointer to size of array
- * FS		- fields separator
- * p_array	- pointer to array of leafs
- *
- * return values:
- * 0		- ok and names by p_names, size by p_size, array by p_array set
- * -1		- memory allocation error (errno set)
- */  
-
-static int	mk_ftree(char *filename, 
-		unsigned char ***p_names, int *p_size, unsigned char FS, 
-			struct leaf **p_array);
-		
-/* make tree from array
- *
- * names	- array of strings
- * size		- size of array
- * FS		- fields separator
- * p_array	- pointer to array of leafs
- *
- * return values:
- * 0		- ok and array by p_array set
- * -1		- memory allocation error (errno set)
- */  
- 
-static int	mk_tree(unsigned char **names, int size, unsigned char FS, 
-			struct leaf **p_array);
-
-/* free memory from tree (leafs)
- *
- * return values:
- * nothing
- */
-
-static void	free_leafs(struct leaf *array, int size);
-
-/* free memory from source data for tree (names)
- *
- * return values:
- * if 0 <= choice <= size - pointer to name from names, 
- *	and memory for name not released (must be freed later)
- * else - NULL (recomended choice -1 for it)
- */
-
-static unsigned char	*free_names(unsigned char **names, 
-					int size, int choice);
-
-/* end of static utils for make tree */
-
-/* static utils for ftree */
-
-/* control struct for queue */
-struct queue {
-	int size;			/* size of queue */
-	struct m_queue *first;		/* begin of queue */
-	struct m_queue *last;		/* end of queue */
-};
-
-/* queue member */
-struct m_queue {
-	void *pointer;			/* queue member */
-	struct m_queue *next;		/* next queue member */
-};
-
-/* init struct queue by zeros */
-static void	init_queue(struct queue *queue);
-
-/* add pointer to queue */
-/* return - pointer or NULL if error */
-static void	*p2_queue(struct queue *queue, void *pointer);
-
-/* get first from queue */
-/* return - pointer or NULL if queue is empty */
-static void	*first_queue(struct queue *queue);
-
-/* make zero terminated array from queue */
-/* return - pointer to array or NULL if error */
-static void	**q2arr(struct queue *queue, int depth);
-
-/* smart_tree (for like find(1) with -d flag output compliance) */
-/* return - not NULL or NULL if malloc error */
-static unsigned char	*smart_tree(struct queue *queue, unsigned char FS,
-					unsigned char *current,
-					unsigned char *prev);
-
-/* end of static utils for ftree */
-
-/* static utils for saved_tree */
-
-/* saved values for unique tree */
-struct saved_tree {
-	unsigned char **names;	/* names + */ 
-	int size;		/* size + */
-	unsigned char FS;	/* FS + */
-	int height;		/* height + */
-	int width;		/* width + */
-	int menu_height;	/* menu_height - unique for treebox ? */
-	int ch;			/* saved ch - choice */
-	int sc;			/* saved sc - scroll */
-};
-
-/* search saved tree within queue */
-/* return - struct saved_tree * or NULL if not found */
-static struct saved_tree *search_saved_tree(struct queue *queue, 
-					unsigned char **names,
-					int size,
-					unsigned char FS,
-					int height,
-					int width,
-					int menu_height);
-
-/* end of static utils for saved_tree */
-
-static void print_item(WINDOW *win, struct leaf item, int choice, int selected);
-
-static void print_position(WINDOW *win, int x, int y,
-				int cur_pos, int size);
-
-static int menu_width, item_x;
-
-static int dialog_treemenu(unsigned char *title, unsigned char *prompt, 
-			int height, int width, int menu_height, 
-				int item_no, struct leaf items[], 
-					int *result, 
-						int *ch, int *sc);
-
-/*
- * Display a menu for choosing among a number of options
- */
-static
-int dialog_treemenu(unsigned char *title, unsigned char *prompt, 
-			int height, int width, int menu_height, 
-				int item_no, struct leaf items[], 
-					int *result, 
-						int *ch, int *sc)
-{
-  int i, j, x, y, cur_x, cur_y, box_x, box_y, key = 0, button = 0, choice = 0,
-      l, scroll = 0, max_choice, redraw_menu = FALSE;
-  WINDOW *dialog, *menu;
-
-  if (ch)  /* restore menu item info */
-      choice = *ch;
-  if (sc)
-      scroll = *sc;
-
-  max_choice = MIN(menu_height, item_no);
-
-  item_x = 0;
-  /* Find length of longest item in order to center menu */
-  for (i = 0; i < item_no; i++) {
-    l = strlen(items[i].name) + strlen(items[i].branches) * 4 + 4;
-    item_x = MAX(item_x, l);
-  }
-  
-  if (height < 0)
-	height = strheight(prompt)+menu_height+4+2;
-  if (width < 0) {
-	i = strwidth(prompt);
-	j = ((title != NULL) ? strwidth(title) : 0);
-	width = MAX(i,j);
-	width = MAX(width,item_x+4)+4;
-  }
-  width = MAX(width,24);
-
-  if (width > COLS)
-	width = COLS;
-  if (height > LINES)
-	height = LINES;
-  /* center dialog box on screen */
-  x = (COLS - width)/2;
-  y = (LINES - height)/2;
-
-#ifdef HAVE_NCURSES
-  if (use_shadow)
-    draw_shadow(stdscr, y, x, height, width);
-#endif
-  dialog = newwin(height, width, y, x);
-  if (dialog == NULL) {
-    endwin();
-    fprintf(stderr, "\nnewwin(%d,%d,%d,%d) failed, maybe wrong dims\n", height,width,y,x);
-    exit(1);
-  }
-  keypad(dialog, TRUE);
-
-  draw_box(dialog, 0, 0, height, width, dialog_attr, border_attr);
-  wattrset(dialog, border_attr);
-  wmove(dialog, height-3, 0);
-  waddch(dialog, ACS_LTEE);
-  for (i = 0; i < width-2; i++)
-    waddch(dialog, ACS_HLINE);
-  wattrset(dialog, dialog_attr);
-  waddch(dialog, ACS_RTEE);
-  wmove(dialog, height-2, 1);
-  for (i = 0; i < width-2; i++)
-    waddch(dialog, ' ');
-
-  if (title != NULL) {
-    wattrset(dialog, title_attr);
-    wmove(dialog, 0, (width - strlen(title))/2 - 1);
-    waddch(dialog, ' ');
-    waddstr(dialog, title);
-    waddch(dialog, ' ');
-  }
-  wattrset(dialog, dialog_attr);
-  wmove(dialog, 1, 2);
-  print_autowrap(dialog, prompt, height-1, width-2, width, 1, 2, TRUE, FALSE);
-
-  menu_width = width-6;
-  getyx(dialog, cur_y, cur_x);
-  box_y = cur_y + 1;
-  box_x = (width - menu_width)/2 - 1;
-
-  /* create new window for the menu */
-  menu = subwin(dialog, menu_height, menu_width, y + box_y + 1, x + box_x + 1);
-  if (menu == NULL) {
-    endwin();
-    fprintf(stderr, "\nsubwin(dialog,%d,%d,%d,%d) failed, maybe wrong dims\n", menu_height,menu_width,y+box_y+1,x+box_x+1);
-    exit(1);
-  }
-  keypad(menu, TRUE);
-
-  /* draw a box around the menu items */
-  draw_box(dialog, box_y, box_x, menu_height+2, menu_width+2, menubox_border_attr, menubox_attr);
-
-  item_x = 1;
-
-  /* Print the menu */
-  for (i = 0; i < max_choice; i++)
-    print_item(menu, items[(scroll+i)], i, i == choice);
-  wnoutrefresh(menu);
-  print_arrows(dialog, scroll, menu_height, item_no, box_x, box_y, item_x, cur_x, cur_y);
-  print_position(dialog, box_x+menu_width, box_y+menu_height, scroll+choice, item_no);
-
-  display_helpline(dialog, height-1, width);
-
-  x = width/2-11;
-  y = height-2;
-  print_button(dialog, "Cancel", y, x+14, FALSE);
-  print_button(dialog, "  OK  ", y, x, TRUE);
-
-  wrefresh(dialog);
-
-  while (key != ESC) {
-    key = wgetch(dialog);
-    /* Check if key pressed matches first character of any item tag in menu */
-
-    if (key == KEY_UP || key == KEY_DOWN || key == '-' || key == '+') {
-     if (key == KEY_UP || key == '-') {
-        if (!choice) {
-          if (scroll) {
-#ifdef BROKEN_WSCRL
-    /* wscrl() in ncurses 1.8.1 seems to be broken, causing a segmentation
-       violation when scrolling windows of height = 4, so scrolling is not
-       used for now */
-            scroll--;
-            getyx(dialog, cur_y, cur_x);    /* Save cursor position */
-            /* Reprint menu to scroll down */
-            for (i = 0; i < max_choice; i++)
-              print_item(menu, items[(scroll+i)], i, i == choice);
-
-#else
-
-            /* Scroll menu down */
-            getyx(dialog, cur_y, cur_x);    /* Save cursor position */
-            if (menu_height > 1) {
-              /* De-highlight current first item before scrolling down */
-              print_item(menu, items[scroll], 0, FALSE);
-              scrollok(menu, TRUE);
-              wscrl(menu, -1);
-              scrollok(menu, FALSE);
-            }
-            scroll--;
-            print_item(menu, items[scroll], 0, TRUE);
-#endif
-            wnoutrefresh(menu);
-	    print_arrows(dialog, scroll, menu_height, item_no, box_x, box_y, item_x, cur_x, cur_y);
-  	    print_position(dialog, box_x+menu_width, box_y+menu_height, scroll+choice, item_no);	    
-  	    wmove(dialog, cur_y, cur_x);  /* Restore cursor to previous position */        
-            wrefresh(dialog);
-          }
-          continue;    /* wait for another key press */
-        }
-        else
-          i = choice - 1;
-      }
-      else if (key == KEY_DOWN || key == '+') {
-        if (choice == max_choice - 1) {
-          if (scroll+choice < item_no-1) {
-#ifdef BROKEN_WSCRL
-    /* wscrl() in ncurses 1.8.1 seems to be broken, causing a segmentation
-       violation when scrolling windows of height = 4, so scrolling is not
-       used for now */
-            scroll++;
-            getyx(dialog, cur_y, cur_x);    /* Save cursor position */
-            /* Reprint menu to scroll up */
-            for (i = 0; i < max_choice; i++)
-              print_item(menu, items[(scroll+i)], i, i == choice);
-
-#else
-
-            /* Scroll menu up */
-            getyx(dialog, cur_y, cur_x);    /* Save cursor position */
-            if (menu_height > 1) {
-              /* De-highlight current last item before scrolling up */
-              print_item(menu, items[(scroll+max_choice-1)], max_choice-1, FALSE);
-              scrollok(menu, TRUE);
-              scroll(menu);
-              scrollok(menu, FALSE);
-            }
-            scroll++;
-              print_item(menu, items[(scroll+max_choice-1)], max_choice-1, TRUE);
-#endif
-            wnoutrefresh(menu);
-	    print_arrows(dialog, scroll, menu_height, item_no, box_x, box_y, item_x, cur_x, cur_y);
-  	    print_position(dialog, box_x+menu_width, box_y+menu_height, scroll+choice, item_no);	    
-  	    wmove(dialog, cur_y, cur_x);  /* Restore cursor to previous position */        
-            wrefresh(dialog);
-          }
-          continue;    /* wait for another key press */
-        }
-        else
-          i = choice + 1;
-      }
-
-      if (i != choice) {
-        /* De-highlight current item */
-        getyx(dialog, cur_y, cur_x);    /* Save cursor position */
-        print_item(menu, items[(scroll+choice)], choice, FALSE);
-
-        /* Highlight new item */
-        choice = i;
-        print_item(menu, items[(scroll+choice)], choice, TRUE);
-        wnoutrefresh(menu);
-        print_position(dialog, box_x+menu_width, box_y+menu_height, scroll+choice, item_no);
-        wmove(dialog, cur_y, cur_x);  /* Restore cursor to previous position */        
-        wrefresh(dialog);
-      }
-      continue;    /* wait for another key press */
-    }
-
-    /* save info about menu item position */
-    if (ch)
-	*ch = choice;
-    if (sc)
-	*sc = scroll;
-
-    switch (key) {
-    case KEY_PPAGE:
-    case 'B' :
-    case 'b' :
-	if (scroll > menu_height) {	/* can we go up? */
-	    scroll -= (menu_height);
-	} else {
-	    scroll = 0;
-	}
-	redraw_menu = TRUE;
-	break;
-    case KEY_NPAGE:
-    case 'F' :
-    case 'f' :
-	if (scroll + menu_height >= item_no-1 - menu_height) { /* can we go down a full page? */
-	    scroll = item_no - menu_height;
-	    if (scroll < 0) scroll = 0;
-	} else {
-	    scroll += menu_height;
-	}
-	redraw_menu = TRUE;
-	break;
-    case KEY_HOME:
-    case 'g' :
-	scroll = 0;
-	choice = 0;
-	redraw_menu = TRUE;
-	break;
-    case KEY_END:
-    case 'G' :
-	scroll = item_no - menu_height;
-	if (scroll < 0) scroll = 0;
-	choice = max_choice - 1;
-	redraw_menu = TRUE;
-	break;
-    case 'O':
-    case 'o':
-        delwin(dialog);
-	*result = scroll+choice;
-        return 0;
-    case 'C':
-    case 'c':
-        delwin(dialog);
-        return 1;
-    case KEY_BTAB:
-    case TAB:
-    case KEY_LEFT:
-    case KEY_RIGHT:
-        if (!button) {
-          button = 1;    /* Indicates "Cancel" button is selected */
-          print_button(dialog, "  OK  ", y, x, FALSE);
-          print_button(dialog, "Cancel", y, x+14, TRUE);
-        }
-        else {
-          button = 0;    /* Indicates "OK" button is selected */
-          print_button(dialog, "Cancel", y, x+14, FALSE);
-          print_button(dialog, "  OK  ", y, x, TRUE);
-        }
-        wrefresh(dialog);
-        break;
-    case ' ':
-    case '\r':
-    case '\n':
-        delwin(dialog);
-        if (!button)
-	  *result = scroll+choice;
-        return button;
-    case ESC:
-        break;
-    case KEY_F(1):
-    case '?':
-	display_helpfile();
-	break;
-    }
-    if (redraw_menu) {
-	for (i = 0; i < max_choice; i++) {
-	    print_item(menu, items[(scroll+i)],
-		       i, i == choice);
-	}
-	wnoutrefresh(menu);
-        getyx(dialog, cur_y, cur_x);    /* Save cursor position */	
-	print_arrows(dialog, scroll, menu_height, item_no, box_x, box_y, item_x, cur_x, cur_y);
-  	print_position(dialog, box_x+menu_width, box_y+menu_height, scroll+choice, item_no);	
-  	wmove(dialog, cur_y, cur_x);  /* Restore cursor to previous position */        
-	wrefresh(dialog);
-	redraw_menu = FALSE;
-    }
-  }
-
-  delwin(dialog);
-  return -1;    /* ESC pressed */
-}
-/* End of dialog_treemenu() */
-
-
-/*
- * Print menu item
- */
-static void print_item(WINDOW *win, struct leaf item, int choice, int selected)
-{
-  int i, j = menu_width - 2;
-  char *branches = item.branches;
-
-  /* Clear 'residue' of last item */
-  wattrset(win, menubox_attr);
-  wmove(win, choice, 0);
-  for (i = 0; i < menu_width; i++)
-    waddch(win, ' ');
-  wmove(win, choice, item_x);
-
-  while(*branches && j)
-  {
-  	switch (*branches++) {
-  	case ' ' : waddch(win, ' ');
-  		break;
-  	case '|' : waddch(win, ACS_VLINE);
-  	}
-  	
-  	j--;
-  	i = 3;
-  	while(i-- && j)
-  	{
-	  	waddch(win, ' ');
-	  	j--;
-	}
-  }	
-  
-  if (j)
-  {
-	  switch (item.slip) {
-	  case '+' : waddch(win, ACS_LTEE);
-  		break;
-	  case '`' : waddch(win, ACS_LLCORNER);
-	  }
-	  j--;
-  }
-
-  i = 3;
-  while(i-- && j)
-  {
-  	waddch(win, ACS_HLINE);
-  	j--;
-  }
-  
-  wattrset(win, selected ? item_selected_attr : item_attr);
-  if (j)
-	  waddnstr(win, item.name, j);
-}
-/* End of print_item() */
-
-/*
- * Print current position
- */
-static void print_position(WINDOW *win, int x, int y, 
-					int cur_pos, int size)
-{
-  int percent;
-
-  wattrset(win, position_indicator_attr);
-  percent = cur_pos == size - 1 ? 100 : (cur_pos * 100)/(size - 1);
-  wmove(win, y + 1, x - 6);
-  wprintw(win, "(%3d%%)", percent);
-}
-/* End of print_position() */
-
-/*
- * Display a tree menu from file
- *
- * filename	- file with like find(1) output
- * FS		- fields separator
- * title	- title of dialog box
- * prompt	- prompt text into dialog box
- * height	- height of dialog box
- * width	- width of dialog box
- * menu_height	- height of menu box
- * result	- pointer to char array
- *
- * return values:
- * -1		- ESC pressed
- * 0		- Ok, result set (must be freed later)
- * 1		- Cancel
- */
-
-int dialog_ftree(unsigned char *filename, unsigned char FS,
-		unsigned char *title, unsigned char *prompt, 
-			int height, int width, int menu_height, 
-					unsigned char **result)
-{
-	int retcode, choice, size;
-	struct leaf *items;
-	unsigned char **names;
-	
-	if (mk_ftree(filename, &names, &size, FS, &items))
-	{
-		perror("dialog_ftree");
-		end_dialog();
-		exit(-1);
-	}
-	
-	if (!size)
-	{
-		fprintf(stderr, "\ndialog_ftree: file %s is empty\n", filename);
-		end_dialog();
-		exit(-1);
-	}
-	
-	retcode = dialog_treemenu(title, prompt, height, width, menu_height,
-					size, items, &choice, NULL, NULL);
-					
-	free_leafs(items, size);
-	
-	if (!retcode)
-		*result = free_names(names, size, choice);
-	else
-		(void)free_names(names, size, -1);	
-					
-	return retcode;
-}
-/* End of dialog_ftree() */
-
-/*
- * Display a tree menu from array
- *
- * names	- array with like find(1) output
- * size		- size of array
- * FS		- fields separator
- * title	- title of dialog box
- * prompt	- prompt text into dialog box
- * height	- height of dialog box
- * width	- width of dialog box
- * menu_height	- height of menu box
- * result	- pointer to char array
- *
- * return values:
- * -1		- ESC pressed
- * 0		- Ok, result set
- * 1		- Cancel
- */
-
-int dialog_tree(unsigned char **names, int size, unsigned char FS,
-		unsigned char *title, unsigned char *prompt, 
-			int height, int width, int menu_height, 
-					unsigned char **result)
-{
-	int retcode, choice;
-	struct leaf *items;
-	struct saved_tree *st;
-	static struct queue *q_saved_tree = NULL;
-	
-	if (!size)
-	{
-		fprintf(stderr, "\ndialog_tree: source array is empty\n");
-		end_dialog();
-		exit(-1);
-	}	
-	
-	if (mk_tree(names, size, FS, &items))
-	{
-		perror("dialog_tree");
-		end_dialog();
-		exit(-1);
-	}
-
-/* is tree saved ? */
-	if (!(st = search_saved_tree(q_saved_tree, names, 
-					size, FS,
-					height, width, menu_height))) {
-		if (!q_saved_tree) {
-			if (!(q_saved_tree = 
-				calloc(sizeof (struct queue), 1))) {
-				perror("dialog_tree");
-				end_dialog();
-				exit(-1);
-			}
-		}
-
-		if (!(st = calloc(sizeof (struct saved_tree), 1))) {
-			perror("dialog_tree");
-			end_dialog();
-			exit(-1);
-		}
-		
-		st->names = names;
-		st->size = size;
-		st->FS = FS;
-		st->height = height;
-		st->width = width;
-		st->menu_height = menu_height;
-		
-		if (!p2_queue(q_saved_tree, st)) {
-			perror("dialog_tree");
-			end_dialog();
-			exit(-1);
-		}
-	}
-	
-	retcode = dialog_treemenu(title, prompt, height, width, menu_height,
-					size, items, &choice, 
-					&(st->ch), &(st->sc));
-		
-	free_leafs(items, size);
-				
-	if (!retcode)
-		*result = names[choice];
-		
-	return retcode;
-}
-/* End of dialog_tree() */
-
-/* utils for ftree */
-
-/* init struct queue by zeros */
-static void
-init_queue(struct queue *queue)
-{
-	bzero((void *)queue, sizeof(struct queue));
-}
-
-/* add pointer to queue */
-/* return - pointer or NULL if error */
-static void	*
-p2_queue(struct queue *queue, void *pointer)
-{
-	if (!queue)
-		return NULL;
-
-	if (!queue->first)
-	{
-		if (!(queue->first = queue->last = 
-			calloc(1, sizeof(struct m_queue))))
-				return NULL;
-
-	}
-	else 
-	{
-	if (!(queue->last->next = 
-			calloc(1, sizeof(struct m_queue))))
-				return NULL;	
-	
-	queue->last = queue->last->next;
-	}
-		
-	queue->size++;
-	return queue->last->pointer = pointer;		
-}
-
-/* get first from queue */
-/* return - pointer or NULL if queue is empty */
-static void	*
-first_queue(struct queue *queue)
-{
-	void *retval;
-	struct m_queue *new_first;
-	
-	if (!queue ||
-		!queue->first ||
-			!queue->size)
-				return NULL;
-	
-	retval = queue->first->pointer;
-	new_first = queue->first->next;
-	free(queue->first);
-	queue->first = new_first;
-	queue->size--;
-	
-	return retval;
-		
-}
-
-/* make zero terminated array from queue */
-/* return - pointer to array or NULL if error */
-static void	**
-q2arr(struct queue *queue, int depth)
-{
-	void **mono, **end;
-
-	if (!queue ||
-		!queue->first ||
-			!queue->size)
-			return NULL;
-
-	/* memory allocation for array */
-	if (!(mono = end = malloc(depth * sizeof(void *) + 1)))
-		return NULL;
-	
-	while(depth--)
-	{
-		if (!(*end++ = first_queue(queue)))
-			break;
-	}
-	
-	*end = NULL;
-	
-	return mono;
-	
-}
-
-/*
- * smart_tree (for like find(1) with -d flag output compliance)
- *
- * return values:
- * NULL - malloc error
- * not NULL - ok
- *
- */
-static
-unsigned char *
-smart_tree(struct queue *queue,
-		unsigned char FS, 
-		unsigned char *current, 
-		unsigned char *prev) {
-	unsigned char *pcurrent = current, *pprev = prev, *toqueue;
-	register char break_flag = 0;
-	
-	while(*pcurrent && *pprev) {
-		if (*pcurrent == *pprev) {
-			pcurrent++;
-			pprev++;
-		}
-		else {
-			break_flag = 1;
-			break;
-		}
-	}
-
-	if (!*pprev || break_flag) {
-		if (*pcurrent == FS) {
-			pcurrent++;
-			
-			if ((!*prev) && (*pcurrent)) {
-				unsigned char tchar = *pcurrent;
-			
-				*pcurrent = '\0';
-				if (!(toqueue = strdup(current))) {
-					*pcurrent = tchar;
-					return NULL;
-				}
-				if (!p2_queue(queue, toqueue)) {
-					*pcurrent = tchar;
-					return NULL;
-				}
-				*pcurrent = tchar;			
-			}
-		}
-
-		while(*pcurrent) {
-			if (*pcurrent == FS) {
-				*pcurrent = '\0';
-				if (!(toqueue = strdup(current))) {
-					*pcurrent = FS;
-					return NULL;
-				}
-				if (!p2_queue(queue, toqueue)) {
-					*pcurrent = FS;
-					return NULL;
-				}
-				*pcurrent = FS;
-			}
-			pcurrent++;
-		}
-		if (!p2_queue(queue, current))
-			return NULL;	
-	} 
-	return current;
-}
-
-/* end of utils for ftree */
-
-/* utils for make tree */
-
-/* if error - return -1 */
-static
-int
-mk_slip(struct leaf array[], int arr_size, int number, int shift)
-{
-	int t_number;
-	int t_shift;
-	
-	if (number > arr_size - 1)
-		return number - 1;
-	
-	t_shift = shift;
-	
-	if (!(array[number].branches = calloc(1, t_shift + 1)))
-			return -1;
-			
-	(void)memset(array[number].branches, ' ', t_shift);
-	
-	t_number = number;
-	
-	while (array[number].shift < array[t_number + 1].shift)
-	{
-		t_number = mk_slip(array, arr_size, t_number + 1, t_shift + 1);
-		if (t_number < 0) 
-				return -1;
-		if (t_number == arr_size - 1) 
-				break;
-	}
-	
-	if (array[number].shift == array[t_number + 1].shift)
-		array[number].slip = '+';
-	
-	if ((array[number].shift > array[t_number + 1].shift) || 
-				t_number == arr_size - 1)
-		array[number].slip = '`';
-	
-	return t_number;
-
-} /* mk_slip() */
-
-/* make tree from file
- *
- * filename	- name of file with like find(1) output
- * p_names	- pointer to array of strings
- * p_size	- pointer to size of array
- * FS		- fields separator
- * p_array	- pointer to array of leafs
- *
- * return values:
- * 0		- ok and names by p_names, size by p_size, array by p_array set
- * -1		- memory allocation error (errno set)
- */  
-
-static
-int
-mk_ftree(char *filename, 
-	unsigned char ***p_names, int *p_size, unsigned char FS, 
-		struct leaf **p_array)
-{
-	int NR;	/* number of input records */	
-	struct queue queue;
-	unsigned char *string, *sstring = "";
-	unsigned char **names;
-	
-	FILE *input_file;
-	
-	if (!(input_file = fopen(filename, "r")))
-				return -1;
-
-	init_queue(&queue);	
-	
-	if (!(string = malloc(BUFSIZ)))
-			return -1;
-	
-	/* read input file into queue */
-	while(fgets(string, BUFSIZ, input_file))
-	{
-		if (strchr(string, '\n'))
-			*strchr(string, '\n') = '\0';
-	
-		if (!(string = realloc(string, strlen(string) + 1)))
-				return -1;
-				
-		if (!smart_tree(&queue, FS, string, sstring))
-				return -1;
-		sstring = string;
-				
-		if (!(string = malloc(BUFSIZ)))
-				return -1;
-	} /* read input file into queue */	
-	
-	if (fclose(input_file) == EOF)
-			return -1;
-	
-	if (!(NR = queue.size))
-	{
-		*p_size = 0;
-		return 0;
-	}	
-
-	/* make array from queue */
-	if (!(names = (unsigned char **)q2arr(&queue, NR)))
-			return -1;
-			
-	*p_names = names;
-	*p_size = NR;
-	
-	/* make tree from array */
-	return mk_tree(names, NR, FS, p_array);
-	
-} /* mk_ftree */
-
-/* make tree from array
- *
- * names	- array of strings
- * size		- size of array
- * FS		- fields separator
- * p_array	- pointer to array of leafs
- *
- * return values:
- * 0		- ok and array by p_array set
- * -1		- memory allocation error (errno set)
- */  
- 
-static
-int
-mk_tree(unsigned char **names, int size, unsigned char FS, 
-		struct leaf **p_array)
-{
-	int i;
-	struct leaf *array;
-
-	/* make array of leafs */
-	if (!(array = calloc(size, sizeof(struct leaf))))
-			return -1;
-	
-	/* init leafs */
-	for (i = 0; i < size; i++)
-	{
-		unsigned char *in_string, *name;
-		int shift = 0;
-	
-		in_string = name = names[i];
-		while(*in_string)
-		{
-			if (*in_string == FS) {
-				if (!i && !*(in_string + 1))
-					name = in_string;
-				else
-				{
-					shift++;
-					name = in_string + 1;
-				}
-			}
-			in_string++;
-		}
-		array[i].name = name;
-		array[i].shift = shift;
-		array[i].slip = '\0';
-		array[i].branches = NULL;
-	} /* init leafs */
-	
-	/* make slips */
-	for (i = 0;i < size; i++)
-	{
-		i = mk_slip(array, size, i, 0);
-		if (i < 0) 
-			return -1;
-	} /* make slips */
-
-	/* make branches */
-	for (i = 1;i < size; i++)
-	{
-		unsigned char *src = array[i - 1].branches;
-		unsigned char *dst = array[i].branches;
-	
-		while(*src && *dst)
-			*dst++ = *src++;
-		
-		if (*dst)
-			switch (array[i - 1].slip) {
-			case '+' : *dst = '|'; 
-				break;
-			case '`' : *dst = ' ';
-			}
-	} /* make branches */
-	
-	*p_array = array;
-	return 0;
-
-} /* mk_tree() */
-
-/* free memory from tree (leafs)
- *
- * return values:
- * nothing
- */
-
-static
-void
-free_leafs(struct leaf *array, int size)
-{
-	struct leaf *p_array = array;
-	
-	while (size--)
-		free(array++->branches);
-
-	free(p_array);
-} /* free_leafs() */
-
-/* free memory from source data for tree (names)
- *
- * return values:
- * if 0 <= choice <= size - pointer to name from names, 
- *	and memory for name not released (must be freed later)
- * else - NULL (recomended choice -1 for it)
- */
-
-static
-unsigned char *
-free_names(unsigned char **names, int size, int choice)
-{
-	unsigned char *retval = NULL;
-	unsigned char **p_names = names;
-	
-	while (size--)
-	{
-		if (!choice--)
-			retval = *names++;
-		else	
-			free(*names++);
-	}
-	free(p_names);
-	return retval;
-} /* free_names() */
-
-/* end of utils for make tree */
-
-/* static utils for saved_tree */
-
-/* search saved tree within queue */
-/* return - struct *saved_tree or NULL if not found */
-static 
-struct saved_tree *
-search_saved_tree(struct queue *queue, unsigned char **names, int size,
-					unsigned char FS,
-					int height, int width, 
-					int menu_height) 
-{
-	struct m_queue *member;
-	struct saved_tree *retval;
-	
-	if (!queue || !names || !FS || 
-		!height || !width || !menu_height)
-		return NULL;
-	
-	if (!(member = queue->first))
-		return NULL;
-
-	while (member->next) {
-		retval = member->pointer;
-		if ((names == retval->names) &&
-			(size == retval->size) &&
-			(FS == retval->FS) &&
-			(height == retval->height) &&
-			(width == retval->width) &&
-			(menu_height == retval->menu_height))
-			return retval;
-		member = member->next;
-	}
-	retval = member->pointer;
-	if ((names == retval->names) &&
-		(size == retval->size) &&
-		(FS == retval->FS) &&
-		(height == retval->height) &&
-		(width == retval->width) &&
-		(menu_height == retval->menu_height))
-		return retval;
-	return NULL;	
-}
-
-/* end of static utils for saved_tree */
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/ui_objects.c
--- a/head/gnu/lib/libodialog/ui_objects.c	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,829 +0,0 @@
-/*
- * Program:	objects.c
- * Author:	Marc van Kempen
- * Desc:	Implementation of UI-objects:
- *		- String input fields
- *		- List selection
- *		- Buttons
- *
- * Copyright (c) 1995, Marc van Kempen
- *
- * All rights reserved.
- *
- * This software may be used, modified, copied, distributed, and
- * sold, in both source and binary form provided that the above
- * copyright and these terms are retained, verbatim, as the first
- * lines of this file.  Under no circumstances is the author
- * responsible for the proper functioning of this software, nor does
- * the author assume any responsibility for damages incurred with
- * its use.
- *
- */
-
-#include <stdlib.h>
-#include <sys/param.h>
-#include <ncurses.h>
-#include <dialog.h>
-#include "dialog.priv.h"
-#include "ui_objects.h"
-
-#define ESC 27
-
-/***********************************************************************
- *
- * Obj routines
- *
- ***********************************************************************/
-
-void
-AddObj(ComposeObj **Obj, int objtype, void *obj)
-/*
- * Desc: Add the object <obj> to the list of objects <Obj>
- */
-{
-    if (*Obj == NULL) {
-	/* Create the root object */
-	*Obj = (ComposeObj *) malloc( sizeof(ComposeObj) );
-	if (!Obj) {
-	    printf("AddObj: Error malloc'ing ComposeObj\n");
-	    exit(-1);
-	}
-	(*Obj)->objtype = objtype;
-	(*Obj)->obj = obj;
-	(*Obj)->next = NULL;
-	(*Obj)->prev = NULL;
-    } else {
-	ComposeObj	*o = *Obj;
-
-	/* create the next object */
-	while (o->next) o = (ComposeObj *) o->next;
-	o->next = (struct ComposeObj *) malloc( sizeof(ComposeObj) );
-	if (!o->next) {
-	    printf("AddObj: Error malloc'ing o->next\n");
-	    exit(-1);
-	}
-	o->next->objtype = objtype;
-	o->next->obj = obj;
-	o->next->next = NULL;
-	o->next->prev = o;
-    }
-
-    return;
-} /* AddObj() */
-
-void
-FreeObj(ComposeObj *Obj)
-/*
- * Desc: free the memory occupied by *Obj
- */
-{
-    ComposeObj	*o = Obj;
-
-    o = Obj;
-    while (o) {
-	o = Obj->next;
-	free(Obj);
-	Obj = o;
-    }
-
-    return;
-} /* FreeObj() */
-
-
-int
-ReadObj(ComposeObj *Obj)
-/*
- * Desc: navigate through the different objects calling their
- *	 respective navigation routines as necessary
- * Pre:  Obj != NULL
- */
-{
-    ComposeObj		*o;
-    ComposeObj		*last;	 /* the last object in the list */
-    int			ret;	 /* the return value from the selection routine */
-
-    /* find the last object in the list */
-    last = Obj;
-    while (last->next) last = last->next;
-
-    ret = 0;
-    o = Obj;
-    while ((ret != SEL_BUTTON) && (ret != SEL_ESC)) {
-	switch(o->objtype) {
-	case STRINGOBJ:
-	    ret = SelectStringObj((StringObj *) o->obj);
-	    break;
-	case LISTOBJ:
-	    ret = SelectListObj((ListObj *) o->obj);
-	    break;
-	case BUTTONOBJ:
-	    ret = SelectButtonObj((ButtonObj *) o->obj);
-	    break;
-	}
-	switch(ret) {
-	case KEY_DOWN:
-	case SEL_CR:
-	case SEL_TAB:	/* move to the next object in the list */
-	    if (o->next != NULL) {
-		o = o->next;	/* next object */
-	    } else {
-		o = Obj;	/* beginning of the list */
-	    }
-	    break;
-
-	case KEY_UP:
-	case SEL_BACKTAB: /* move to the previous object in the list */
-	    if (o->prev != NULL) {
-		o = o->prev;	/* previous object */
-	    } else {
-		o = last;	/* end of the list */
-	    }
-	    break;
-
-	case KEY_F(1): /* display help_file */
-	case '?':
-	    display_helpfile();
-	    break;
-	}
-    }
-
-    return(ret);
-
-} /* ReadObj() */
-
-
-int
-PollObj(ComposeObj **Obj)
-{
-    ComposeObj		*last;	 /* the last object in the list */
-    ComposeObj		*first;  /* the first object in the list */
-    int			ret;	 /* the return value from the selection routine */
-
-    /* find the last object in the list */
-    last = *Obj;
-    while (last->next) last = last->next;
-
-    /* find the first object in the list */
-    first = *Obj;
-    while (first->prev) first = first->prev;
-
-    ret = 0;
-    switch((*Obj)->objtype) {
-    case STRINGOBJ:
-	ret = SelectStringObj((StringObj *) (*Obj)->obj);
-	break;
-    case LISTOBJ:
-	ret = SelectListObj((ListObj *) (*Obj)->obj);
-	break;
-    case BUTTONOBJ:
-	ret = SelectButtonObj((ButtonObj *) (*Obj)->obj);
-	break;
-    }
-    switch(ret) {
-    case KEY_DOWN:
-    case SEL_CR:
-    case SEL_TAB:		     /* move to the next object in the list */
-	if ((*Obj)->next != NULL) {
-	    *Obj = (*Obj)->next;     /* next object */
-	} else {
-	    *Obj = first;	     /* beginning of the list */
-	}
-	break;
-
-    case KEY_UP:
-    case SEL_BACKTAB: 		     /* move to the previous object in the list */
-	if ((*Obj)->prev != NULL) {
-	    *Obj = (*Obj)->prev;     /* previous object */
-	} else {
-	    *Obj = last;	     /* end of the list */
-	}
-	break;
-    }
-
-    return(ret);
-
-} /* PollObj() */
-
-
-void
-DelObj(ComposeObj *Obj)
-/*
- * Desc: Free all objects
- */
-{
-    ComposeObj	*o;
-
-    o = Obj;
-    while (Obj != NULL) {
-	switch(Obj->objtype) {
-	case STRINGOBJ:
-	    DelStringObj((StringObj *) Obj->obj);
-	    break;
-	case LISTOBJ:
-	    DelListObj((ListObj *) Obj->obj);
-	    break;
-	case BUTTONOBJ:
-	    DelButtonObj((ButtonObj *) Obj->obj);
-	    break;
-	}
-	Obj = Obj->next;
-    }
-
-    FreeObj(o);
-} /* DelObj() */
-
-/***********************************************************************
- *
- * StringObj routines
- *
- ***********************************************************************/
-
-static void
-outstr(WINDOW *win, char *str, int attrs)
-{
-    if (attrs & DITEM_NO_ECHO) {
-	char *cpy;
-	int n = strlen(str);
-
-	cpy = alloca(n + 1);
-	memset(cpy, '*', n);
-	cpy[n] = '\0';
-	waddstr(win, cpy);
-    }
-    else
-	waddstr(win, str);
-}
-
-void
-RefreshStringObj(StringObj *so)
-/*
- * Desc: redraw the object
- */
-{
-    char tmp[512];
-
-    wmove(so->win, so->y, so->x+1);
-    wattrset(so->win, dialog_attr);
-    waddstr(so->win, so->title);
-
-    draw_box(so->win, so->y+1, so->x, 3, so->w, dialog_attr, border_attr);
-    wattrset(so->win, item_attr);
-    wmove(so->win, so->y+2, so->x+1);
-    if (strlen(so->s) > so->w-2) {
-	strncpy(tmp, (char *) so->s + strlen(so->s) - so->w + 2, so->w - 1);
-	outstr(so->win, tmp, so->attr_mask);
-    } else {
-	outstr(so->win, so->s, so->attr_mask);
-    }
-
-    return;
-} /* RefreshStringObj() */
-
-StringObj *
-NewStringObj(WINDOW *win, char *title, char *s, int y, int x, int w, int len)
-/*
- * Desc: Initialize a new stringobj and return a pointer to it.
- *	 Draw the object on the screen at the specified coordinates
- */
-{
-    StringObj	*so;
-
-    /* Initialize a new object */
-    so = (StringObj *) malloc( sizeof(StringObj) );
-    if (!so) {
-	printf("NewStringObj: Error malloc'ing StringObj\n");
-	exit(-1);
-    }
-    so->title = (char *) malloc( strlen(title) + 1);
-    if (!so->title) {
-	printf("NewStringObj: Error malloc'ing so->title\n");
-	exit(-1);
-    }
-    strcpy(so->title, title);
-    so->s = s;
-    strcpy(so->s, s);
-    so->x = x;
-    so->y = y;
-    so->w = w;
-    so->len = len;
-    so->win = win;
-    so->attr_mask = DialogInputAttrs;	/* Grossly use a global to avoid changing API */
-
-    /* Draw it on the screen */
-    RefreshStringObj(so);
-
-    return(so);
-} /* NewStringObj() */
-
-int
-SelectStringObj(StringObj *so)
-/*
- * Desc: get input using the info in <so>
- */
-{
-    int     	key;
-    char	tmp[so->len+1];
-
-    strcpy(tmp, so->s);
-    key = line_edit(so->win, so->y+2, so->x+1,
-		    so->len, so->w-2, inputbox_attr, TRUE, tmp, so->attr_mask);
-    if ((key == '\n') || (key == '\r') || (key == '\t') || key == (KEY_BTAB) ) {
-	strcpy(so->s, tmp);
-    }
-    RefreshStringObj(so);
-    if (key == ESC) {
-	return(SEL_ESC);
-    }
-    if (key == '\t') {
-	return(SEL_TAB);
-    }
-    if ( (key == KEY_BTAB) || (key == KEY_F(2)) ) {
-	return(SEL_BACKTAB);
-    }
-    if ((key == '\n') || (key == '\r')) {
-	return(SEL_CR);
-    }
-    return(key);
-} /* SelectStringObj() */
-
-
-void
-DelStringObj(StringObj *so)
-/*
- * Desc: Free the space occupied by <so>
- */
-{
-   free(so->title);
-   free(so);
-
-   return;
-}
-
-/***********************************************************************
- *
- * ListObj routines
- *
- ***********************************************************************/
-
-void
-DrawNames(ListObj *lo)
-/*
- * Desc: Just refresh the names, not the surrounding box and title
- */
-{
-    int 	i, j, h, x, y;
-    char	tmp[MAXPATHLEN];
-
-    x = lo->x + 1;
-    y = lo->y + 2;
-    h = lo->h - 2;
-    for (i=lo->scroll; i<lo->n && i<lo->scroll+h; i++) {
-	wmove(lo->win, y+i-lo->scroll, x);
-	if (lo->seld[i]) {
-	    wattrset(lo->win, A_BOLD);
-	} else {
-	    wattrset(lo->win, item_attr);
-	}
-	if (strlen(lo->name[i]) > lo->w-2) {
-	    strncpy(tmp, lo->name[i], lo->w-2);
-	    tmp[lo->w - 2] = 0;
-	    waddstr(lo->win, tmp);
-	} else {
-	    waddstr(lo->win, lo->name[i]);
-	    for (j=strlen(lo->name[i]); j<lo->w-2; j++) waddstr(lo->win, " ");
-	}
-    }
-    wattrset(lo->win, item_attr);
-    while (i<lo->scroll+h) {
-	wmove(lo->win, y+i-lo->scroll, x);
-	for (j=0; j<lo->w-2; j++) waddstr(lo->win, " ");
-	i++;
-    }
-
-    return;
-} /* DrawNames() */
-
-void
-RefreshListObj(ListObj *lo)
-/*
- * Desc: redraw the list object
- */
-{
-    char 	perc[7];
-
-    /* setup the box */
-    wmove(lo->win, lo->y, lo->x+1);
-    wattrset(lo->win, dialog_attr);
-    waddstr(lo->win, lo->title);
-    draw_box(lo->win, lo->y+1, lo->x, lo->h, lo->w, dialog_attr, border_attr);
-
-    /* draw the names */
-    DrawNames(lo);
-
-    /* Draw % indication */
-    sprintf(perc, "(%3d%%)", MIN(100, (int) (100 * (lo->sel+lo->h-2) / MAX(1, lo->n))));
-    wmove(lo->win, lo->y + lo->h, lo->x + lo->w - 8);
-    wattrset(lo->win, dialog_attr);
-    waddstr(lo->win, perc);
-
-
-    return;
-} /* RefreshListObj() */
-
-ListObj *
-NewListObj(WINDOW *win, char *title, char **list, char *listelt, int y, int x,
-	   int h, int w, int n)
-/*
- * Desc: create a listobj, draw it on the screen and return a pointer to it.
- */
-{
-    ListObj	*lo;
-    int		i;
-
-    /* Initialize a new object */
-    lo = (ListObj *) malloc( sizeof(ListObj) );
-    if (!lo) {
-	fprintf(stderr, "NewListObj: Error malloc'ing ListObj\n");
-	exit(-1);
-    }
-    lo->title = (char *) malloc( strlen(title) + 1);
-    if (!lo->title) {
-	fprintf(stderr, "NewListObj: Error malloc'ing lo->title\n");
-	exit(-1);
-    }
-    strcpy(lo->title, title);
-    lo->name = list;
-    if (n>0) {
-        lo->seld = (int *) malloc( n * sizeof(int) );
-        if (!lo->seld) {
-            fprintf(stderr, "NewListObj: Error malloc'ing lo->seld\n");
-            exit(-1);
-        }
-        for (i=0; i<n; i++) {
-            lo->seld[i] = FALSE;
-        }
-    } else {
-        lo->seld = NULL;
-    }
-    lo->y = y;
-    lo->x = x;
-    lo->w = w;
-    lo->h = h;
-    lo->n = n;
-    lo->scroll = 0;
-    lo->sel = 0;
-    lo->elt = listelt;
-    lo->win = win;
-
-    /* Draw the object on the screen */
-    RefreshListObj(lo);
-
-    return(lo);
-} /* NewListObj() */
-
-void
-UpdateListObj(ListObj *lo, char **list, int n)
-/*
- * Desc: Update the list in the listobject with the provided list
- * Pre:  lo->name "has been freed"
- *	 "(A i: 0<=i<lo->n: "lo->name[i] has been freed")"
- */
-{
-    int i;
-
-    if (lo->seld) {
-	free(lo->seld);
-    }
-
-    /* Rewrite the list in the object */
-    lo->name = list;
-    if (n>0) {
-	lo->seld = (int *) malloc( n * sizeof(int) );
-	if (!lo->seld) {
-	    fprintf(stderr, "UpdateListObj: Error malloc'ing lo->seld\n");
-	    exit(-1);
-	}
-	for (i=0; i<n; i++) {
-	    lo->seld[i] = FALSE;
-	}
-    } else {
-        lo->seld = NULL;
-    }
-    lo->n = n;
-    lo->scroll = 0;
-    lo->sel = 0;
-
-    /* Draw the object on the screen */
-    RefreshListObj(lo);
-
-    return;
-} /* UpdateListObj() */
-
-int
-SelectListObj(ListObj *lo)
-/*
- * Desc: get a listname (or listnames), TAB to move on, or ESC ESC to exit
- * Pre:	 lo->n >= 1
- */
-{
-    int 	key, sel_x, sel_y, quit;
-    char	tmp[MAXPATHLEN];
-    char	perc[4];
-
-    sel_x = lo->x+1;
-    sel_y = lo->y + 2 + lo->sel - lo->scroll;
-
-    if (lo->n == 0) return(SEL_TAB);
-
-    keypad(lo->win, TRUE);
-
-    /* Draw current selection in inverse video */
-    wmove(lo->win, sel_y, sel_x);
-    wattrset(lo->win, item_selected_attr);
-    waddstr(lo->win, lo->name[lo->sel]);
-
-    key = wgetch(lo->win);
-    quit = FALSE;
-    while ((key != '\t') && (key != '\n') && (key != '\r')
-	   && (key != ESC) && (key != KEY_F(1)) && (key != '?') && !quit) {
-	/* first draw current item in normal video */
-	wmove(lo->win, sel_y, sel_x);
-	if (lo->seld[lo->sel]) {
-	    wattrset(lo->win, A_BOLD);
-	} else {
-	    wattrset(lo->win, item_attr);
-	}
-	if (strlen(lo->name[lo->sel]) > lo->w - 2) {
-	    strncpy(tmp, lo->name[lo->sel], lo->w - 2);
-	    tmp[lo->w - 2] = 0;
-	    waddstr(lo->win, tmp);
-	} else {
-	    waddstr(lo->win, lo->name[lo->sel]);
-	}
-
-	switch (key) {
-	case KEY_DOWN:
-	case ctrl('n'):
-	    if (sel_y < lo->y + lo->h-1) {
-		if (lo->sel < lo->n-1) {
-		    sel_y++;
-		    lo->sel++;
-		}
-	    } else {
-		if (lo->sel < lo->n-1) {
-		    lo->sel++;
-		    lo->scroll++;
-		    DrawNames(lo);
-		    wrefresh(lo->win);
-		}
-	    }
-	    break;
-	case KEY_UP:
-	case ctrl('p'):
-	    if (sel_y > lo->y+2) {
-		if (lo->sel > 0) {
-		    sel_y--;
-		    lo->sel--;
-		}
-	    } else {
-		if (lo->sel > 0) {
-		    lo->sel--;
-		    lo->scroll--;
-		    DrawNames(lo);
-		    wrefresh(lo->win);
-		}
-	    }
-	    break;
-	case KEY_HOME:
-	case ctrl('a'):
-	    lo->sel = 0;
-	    lo->scroll = 0;
-	    sel_y = lo->y + 2;
-	    DrawNames(lo);
-	    wrefresh(lo->win);
-	    break;
-	case KEY_END:
-	case ctrl('e'):
-	    if (lo->n < lo->h - 3) {
-		lo->sel = lo->n-1;
-		lo->scroll = 0;
-		sel_y = lo->y + 2 + lo->sel - lo->scroll;
-	    } else {
-		/* more than one page of list */
-		lo->sel = lo->n-1;
-		lo->scroll = lo->n-1 - (lo->h-3);
-		sel_y = lo->y + 2 + lo->sel - lo->scroll;
-		DrawNames(lo);
-		wrefresh(lo->win);
-	    }
-	    break;
-	case KEY_NPAGE:
-	case ctrl('f'):
-	    lo->sel += lo->h - 2;
-	    if (lo->sel >= lo->n) lo->sel = lo->n - 1;
-	    lo->scroll += lo->h - 2;
-	    if (lo->scroll >= lo->n - 1) lo->scroll = lo->n - 1;
-	    if (lo->scroll < 0) lo->scroll = 0;
-	    sel_y = lo->y + 2 + lo->sel - lo->scroll;
-	    DrawNames(lo);
-	    wrefresh(lo->win);
-	    break;
-	case KEY_PPAGE:
-	case ctrl('b'):
-	    lo->sel -= lo->h - 2;
-	    if (lo->sel < 0) lo->sel = 0;
-	    lo->scroll -= lo->h - 2;
-	    if (lo->scroll < 0) lo->scroll = 0;
-	    sel_y = lo->y + 2 + lo->sel - lo->scroll;
-	    DrawNames(lo);
-	    wrefresh(lo->win);
-	    break;
-	default:
-	    quit = TRUE;
-	    break;
-	}
-	/* Draw % indication */
-	sprintf(perc, "(%3d%%)", MIN(100, (int)
-				     (100 * (lo->sel+lo->h - 2) / MAX(1, lo->n))));
-	wmove(lo->win, lo->y + lo->h, lo->x + lo->w - 8);
-	wattrset(lo->win, dialog_attr);
-	waddstr(lo->win, perc);
-
-	/* draw current item in inverse */
-	wmove(lo->win, sel_y, sel_x);
-	wattrset(lo->win, item_selected_attr);
-	if (strlen(lo->name[lo->sel]) > lo->w - 2) {
-	    /* when printing in inverse video show the last characters in the */
-	    /* name that will fit in the window */
-	    strncpy(tmp,
-		    lo->name[lo->sel] + strlen(lo->name[lo->sel]) - (lo->w - 2),
-		    lo->w - 2);
-	    tmp[lo->w - 2] = 0;
-	    waddstr(lo->win, tmp);
-	} else {
-	    waddstr(lo->win, lo->name[lo->sel]);
-	}
-	if (!quit) key = wgetch(lo->win);
-    }
-
-    if (key == ESC) {
-	return(SEL_ESC);
-    }
-    if (key == '\t') {
-	return(SEL_TAB);
-    }
-    if ((key == KEY_BTAB) || (key == ctrl('b'))) {
-	return(SEL_BACKTAB);
-    }
-    if ((key == '\n') || (key == '\r')) {
-	strcpy(lo->elt, lo->name[lo->sel]);
-	return(SEL_CR);
-    }
-    return(key);
-} /* SelectListObj() */
-
-void
-DelListObj(ListObj *lo)
-/*
- * Desc: Free the space occupied by the listobject
- */
-{
-    free(lo->title);
-    if (lo->seld != NULL) free(lo->seld);
-    free(lo);
-
-    return;
-} /* DelListObj() */
-
-void
-MarkCurrentListObj(ListObj *lo)
-/*
- * Desc: mark the current item for the selection list
- */
-{
-    lo->seld[lo->sel] = !(lo->seld[lo->sel]);
-    DrawNames(lo);
-
-    return;
-} /* MarkCurrentListObj() */
-
-void
-MarkAllListObj(ListObj *lo)
-/*
- * Desc: mark all items
- */
-{
-    int i;
-
-    for (i=0; i<lo->n; i++) {
-        lo->seld[i] = TRUE;
-    }
-    DrawNames(lo);
-
-    return;
-} /* MarkAllListObj() */
-
-void
-UnMarkAllListObj(ListObj *lo)
-/*
- * Desc: unmark all items
- */
-{
-    int i;
-
-    for (i=0; i<lo->n; i++) {
-        lo->seld[i] = FALSE;
-    }
-    DrawNames(lo);
-
-    return;
-} /* UnMarkAllListObj() */
-
-
-/***********************************************************************
- *
- * ButtonObj routines
- *
- ***********************************************************************/
-
-
-void
-RefreshButtonObj(ButtonObj *bo)
-/*
- * Desc: redraw the button
- */
-{
-    draw_box(bo->win, bo->y, bo->x, 3, bo->w, dialog_attr, border_attr);
-    print_button(bo->win, bo->title, bo->y+1, bo->x+2, FALSE);
-
-    return;
-} /* RefreshButtonObj() */
-
-ButtonObj *
-NewButtonObj(WINDOW *win, char *title, int *pushed, int y, int x)
-/*
- * Desc: Create a new button object
- */
-{
-    ButtonObj	*bo;
-
-    bo = (ButtonObj *) malloc( sizeof(ButtonObj) );
-
-    bo->win = win;
-    bo->title = (char *) malloc( strlen(title) + 1);
-    strcpy(bo->title, title);
-    bo->x = x;
-    bo->y = y;
-    bo->w = strlen(title) + 6;
-    bo->h = 3;
-    bo->pushed = pushed;
-
-    RefreshButtonObj(bo);
-
-    return(bo);
-} /* NewButtonObj() */
-
-int
-SelectButtonObj(ButtonObj *bo)
-/*
- * Desc: Wait for buttonpresses or TAB's to move on, or ESC ESC
- */
-{
-    int	key;
-
-    print_button(bo->win, bo->title, bo->y+1, bo->x+2, TRUE);
-    wmove(bo->win, bo->y+1, bo->x+(bo->w/2)-1);
-    key = wgetch(bo->win);
-    print_button(bo->win, bo->title, bo->y+1, bo->x+2, FALSE);
-    switch(key) {
-    case '\t':
-	return(SEL_TAB);
-	break;
-    case KEY_BTAB:
-    case ctrl('b'):
-	return(SEL_BACKTAB);
-    case '\n':
-    case '\r':
-	*(bo->pushed) = TRUE;
-	return(SEL_BUTTON);
-	break;
-    case ESC:
-	return(SEL_ESC);
-	break;
-    default:
-	return(key);
-	break;
-    }
-} /* SelectButtonObj() */
-
-void
-DelButtonObj(ButtonObj *bo)
-/*
- * Desc: Free the space occupied by <bo>
- */
-{
-    free(bo->title);
-    free(bo);
-
-    return;
-} /* DelButtonObj() */
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/ui_objects.h
--- a/head/gnu/lib/libodialog/ui_objects.h	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,114 +0,0 @@
-/*
- * Author: Marc van Kempen
- * Desc:   include file for UI-objects
- *
- * Copyright (c) 1995, Marc van Kempen
- *
- * All rights reserved.
- *
- * This software may be used, modified, copied, distributed, and
- * sold, in both source and binary form provided that the above
- * copyright and these terms are retained, verbatim, as the first
- * lines of this file.  Under no circumstances is the author
- * responsible for the proper functioning of this software, nor does
- * the author assume any responsibility for damages incurred with
- * its use.
- *
- */
-
-#include "dialog.h"
-#include <ncurses.h>
-
-/***********************************************************************
- *
- * Defines
- *
- ***********************************************************************/
-
-#define ctrl(a)		((a) - 'a' + 1)
-
-/* the Object types */
-#define STRINGOBJ	1
-#define LISTOBJ		2
-#define BUTTONOBJ	3
-
-/* the return signals from the selection routines */
-/* 1000 and higher should avoid conflicts with keys pressed */
-#define SEL_CR		1001	/* return was pressed */
-#define SEL_ESC		1002	/* ESC pressed */
-#define SEL_TAB		1003	/* TAB pressed */
-#define SEL_BACKTAB	1004	/* SHIFT-TAB pressed */
-#define SEL_BUTTON	1005	/* a button was pressed */
-
-/***********************************************************************
- *
- * Typedefs
- *
- ***********************************************************************/
-
-typedef struct {
-    WINDOW	*win;		/* the window it's contained in */
-    char	*title;		/* the prompt for the input field */
-    char 	*s;		/* initial value of the input field */
-    int		x, y, w, len;	/* the (y, x) position of the upperleft */
-				/* corner and the width <w> of the display */
-				/* and length <len> of the field */
-    int		attr_mask;	/* special attributes */
-} StringObj;
-
-typedef struct {
-    WINDOW	*win;		/* the windows it's contained in */
-    char	*title;		/* the title of the list */
-    char 	**name;		/* the names of the list */
-    int		*seld;		/* the currently selected names */
-    char	*elt;		/* the current element in the list list[sel] */
-    int		x, y, w, h, n;	/* dimensions of list and # of elements (n) */
-    int		scroll, sel;	/* current position in the list */
-} ListObj;
-
-typedef struct {
-    WINDOW	*win;		/* the window it's contained in */
-    char	*title;		/* title for the button */
-    int		x, y, w, h; 	/* its dimensions */
-    int		*pushed;	/* boolean that determines wether button was pushed */
-} ButtonObj;
-
-typedef struct ComposeObj {
-    int			objtype;
-    void		*obj;
-    struct ComposeObj	*next, *prev;
-} ComposeObj;
-
-/**********************************************************************
- *
- * Prototypes
- *
- **********************************************************************/
-
-void		RefreshStringObj(StringObj *so);
-StringObj 	*NewStringObj(WINDOW *win, char *title, char *s,
-			      int y, int x, int w, int len);
-int		SelectStringObj(StringObj *so);
-void		DelStringObj(StringObj *so);
-
-void		RefreshListObj(ListObj *lo);
-ListObj 	*NewListObj(WINDOW *win, char *title, char **list,
-			    char *listelt, int y, int x, int h, int w, int n);
-void		UpdateListObj(ListObj *lo, char **list, int n);
-int		SelectListObj(ListObj *lo);
-void		DelListObj(ListObj *obj);
-void            MarkCurrentListObj(ListObj *lo);
-void            MarkAllListObj(ListObj *lo);
-void            UnMarkAllListObj(ListObj *lo);
-
-void		RefreshButtonObj(ButtonObj *bo);
-ButtonObj 	*NewButtonObj(WINDOW *win, char *title, int *pushed,
-			      int y, int x);
-int		SelectButtonObj(ButtonObj *bo);
-void		DelButtonObj(ButtonObj *bo);
-void		AddObj(ComposeObj **Obj, int objtype, void *obj);
-void		FreeObj(ComposeObj *Obj);
-int		ReadObj(ComposeObj *Obj);
-int		PollObj(ComposeObj **Obj);
-void		DelObj(ComposeObj *Obj);
-
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/lib/libodialog/yesno.c
--- a/head/gnu/lib/libodialog/yesno.c	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,169 +0,0 @@
-/*
- *  yesno.c -- implements the yes/no box
- *
- *  AUTHOR: Savio Lam (lam836 at cs.cuhk.hk)
- *
- *  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., 675 Mass Ave, Cambridge, MA 02139, USA.
- */
-
-#include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
-
-#include <dialog.h>
-#include "dialog.priv.h"
-
-/* Actual work function */
-static int dialog_yesno_proc(unsigned char *title, unsigned char *prompt,
-			     int height, int width, int yesdefault);
-
-/*
- * Display a dialog box with two buttons - Yes and No
- */
-int
-dialog_yesno(unsigned char *title, unsigned char *prompt, int height, int width)
-{
-  return dialog_yesno_proc(title, prompt, height, width, TRUE);
-}
-
-/*
- * Display a dialog box with two buttons - No and Yes
- */
-int
-dialog_noyes(unsigned char *title, unsigned char *prompt, int height, int width)
-{
-  return dialog_yesno_proc(title, prompt, height, width, FALSE);
-}
-
-static int
-dialog_yesno_proc(unsigned char *title, unsigned char *prompt, int height, int width, int yesdefault)
-{
-  int i, j, x, y, key, button;
-  WINDOW *dialog;
-  char *tmphlp;
-
-  /* disable helpline */
-  tmphlp = get_helpline();
-  use_helpline(NULL);
-
-  if (height < 0)
-	height = strheight(prompt)+4;
-  if (width < 0) {
-	i = strwidth(prompt);
-	j = ((title != NULL) ? strwidth(title) : 0);
-	width = MAX(i,j)+4;
-  }
-  width = MAX(width,23);
-
-  if (width > COLS)
-	width = COLS;
-  if (height > LINES)
-	height = LINES;
-  /* center dialog box on screen */
-  x = DialogX ? DialogX : (COLS - width)/2;
-  y = DialogY ? DialogY : (LINES - height)/2;
-
-#ifdef HAVE_NCURSES
-  if (use_shadow)
-    draw_shadow(stdscr, y, x, height, width);
-#endif
-  dialog = newwin(height, width, y, x);
-  if (dialog == NULL) {
-    endwin();
-    fprintf(stderr, "\nnewwin(%d,%d,%d,%d) failed, maybe wrong dims\n", height,width,y,x);
-    exit(1);
-  }
-  keypad(dialog, TRUE);
-
-  draw_box(dialog, 0, 0, height, width, dialog_attr, border_attr);
-  wattrset(dialog, border_attr);
-  wmove(dialog, height-3, 0);
-  waddch(dialog, ACS_LTEE);
-  for (i = 0; i < width-2; i++)
-    waddch(dialog, ACS_HLINE);
-  wattrset(dialog, dialog_attr);
-  waddch(dialog, ACS_RTEE);
-  wmove(dialog, height-2, 1);
-  for (i = 0; i < width-2; i++)
-    waddch(dialog, ' ');
-
-  if (title != NULL) {
-    wattrset(dialog, title_attr);
-    wmove(dialog, 0, (width - strlen(title))/2 - 1);
-    waddch(dialog, ' ');
-    waddstr(dialog, title);
-    waddch(dialog, ' ');
-  }
-  wattrset(dialog, dialog_attr);
-  wmove(dialog, 1, 2);
-  print_autowrap(dialog, prompt, height-1, width-2, width, 1, 2, TRUE, FALSE);
-
-  display_helpline(dialog, height-1, width);
-
-  x = width/2-10;
-  y = height-2;
-
-  /* preset button 0 or 1 for YES or NO as the default */
-  key = 0;
-  button = !yesdefault;
-  while (key != ESC) {
-    print_button(dialog, "  No  ", y, x+13, button);
-    print_button(dialog, " Yes " , y, x, !button);
-    if (button)
-	wmove(dialog, y, x+16);
-    else
-	wmove(dialog, y, x+2);
-    wrefresh(dialog);
-
-    key = wgetch(dialog);
-    switch (key) {
-      case 'Y':
-      case 'y':
-        delwin(dialog);
-	restore_helpline(tmphlp);
-        return 0;
-      case 'N':
-      case 'n':
-        delwin(dialog);
-	restore_helpline(tmphlp);
-        return 1;
-      case KEY_BTAB:
-      case TAB:
-      case KEY_UP:
-      case KEY_DOWN:
-      case KEY_LEFT:
-      case KEY_RIGHT:
-        button = !button;
-        /* redrawn at the loop's entry */
-        break;
-      case ' ':
-      case '\r':
-      case '\n':
-        delwin(dialog);
-	restore_helpline(tmphlp);
-        return button;
-      case ESC:
-        break;
-    case KEY_F(1):
-    case '?':
-	display_helpfile();
-	break;
-    }
-  }
-
-  delwin(dialog);
-  restore_helpline(tmphlp);
-  return -1;    /* ESC pressed */
-}
-/* End of dialog_yesno() */
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/usr.bin/dialog/Makefile
--- a/head/gnu/usr.bin/dialog/Makefile	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/gnu/usr.bin/dialog/Makefile	Tue Dec 06 20:26:16 2011 +0200
@@ -1,9 +1,9 @@
-# $FreeBSD$
+# $FreeBSD: head/gnu/usr.bin/dialog/Makefile 227936 2011-11-24 14:17:04Z fjoe $
 
 DIALOG=	${.CURDIR}/../../../contrib/dialog
 PROG=   dialog
 
-DPADD=	$(LIBDIALOG) $(LIBNCURSES) $(LIBM)
+DPADD=	${LIBDIALOG} ${LIBNCURSES} ${LIBM}
 LDADD=	-ldialog -lncursesw -lm
 CFLAGS+= -I${.CURDIR} -I${DIALOG}
 .PATH:	${DIALOG}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/usr.bin/gperf/Makefile
--- a/head/gnu/usr.bin/gperf/Makefile	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/gnu/usr.bin/gperf/Makefile	Tue Dec 06 20:26:16 2011 +0200
@@ -1,17 +1,18 @@
-# $FreeBSD$
+# $FreeBSD: head/gnu/usr.bin/gperf/Makefile 228060 2011-11-28 12:29:16Z bapt $
 
-GPROFDIR=	${.CURDIR}/../../../contrib/gperf
+.include <bsd.own.mk>
+GPERFDIR=	${.CURDIR}/../../../contrib/gperf
 
-.PATH: ${GPROFDIR}/src ${GPROFDIR}/lib ${GPROFDIR}/doc
+.PATH: ${GPERFDIR}/src ${GPERFDIR}/lib ${GPERFDIR}/doc
 
 SUBDIR=	doc
 
 PROG_CXX=	gperf
-SRCS=	bool-array.cc gen-perf.cc hash-table.cc iterator.cc key-list.cc \
-	list-node.cc main.cc new.cc options.cc read-line.cc trace.cc \
-	vectors.cc version.cc
-SRCS+=  hash.cc
+SRCS=	bool-array.cc hash-table.cc input.cc keyword-list.cc keyword.cc \
+	main.cc options.cc output.cc positions.cc search.cc version.cc \
+	getline.cc hash.cc
+WARNS=	1
 
-CXXFLAGS+=	-I${GPROFDIR}/lib -I${.CURDIR}
+CXXFLAGS+=	-I${GPERFDIR}/lib -I${.CURDIR}
 
 .include <bsd.prog.mk>
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/gnu/usr.bin/gperf/config.h
--- a/head/gnu/usr.bin/gperf/config.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/gnu/usr.bin/gperf/config.h	Tue Dec 06 20:26:16 2011 +0200
@@ -1,21 +1,22 @@
-/* $FreeBSD$ */
-/* config.h.  Generated automatically by configure.  */
-/* config.h.in.  Generated automatically from configure.in by autoheader.  */
+/* config.h.  Generated from config.h.in by configure.  */
+/* config.h.in.  Generated from configure.ac by autoheader.  */
+/* $FreeBSD: head/gnu/usr.bin/gperf/config.h 228060 2011-11-28 12:29:16Z bapt $ */
 
-/* Define if the C++ compiler supports "throw ()" declarations.  */
-#define HAVE_THROW_DECL 1
+/* Define if the C++ compiler supports stack-allocated variable-size arrays.
+   */
+#define HAVE_DYNAMIC_ARRAY 1
 
-/* Define if you have the getrlimit function.  */
-#define HAVE_GETRLIMIT 1
+/* Define to the address where bug reports for this package should be sent. */
+#define PACKAGE_BUGREPORT ""
 
-/* Define if you have the setrlimit function.  */
-#define HAVE_SETRLIMIT 1
+/* Define to the full name of this package. */
+#define PACKAGE_NAME ""
 
-/* Define if you have the <sys/resource.h> header file.  */
-#define HAVE_SYS_RESOURCE_H 1
+/* Define to the full name and version of this package. */
+#define PACKAGE_STRING ""
 
-/* Define if you have the <sys/time.h> header file.  */
-#define HAVE_SYS_TIME_H 1
+/* Define to the one symbol short name of this package. */
+#define PACKAGE_TARNAME ""
 
-/* Define if you have the <unistd.h> header file.  */
-#define HAVE_UNISTD_H 1
+/* Define to the version of this package. */
+#define PACKAGE_VERSION ""
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/kerberos5/Makefile.inc
--- a/head/kerberos5/Makefile.inc	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/kerberos5/Makefile.inc	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-# $FreeBSD$
+# $FreeBSD: head/kerberos5/Makefile.inc 228308 2011-12-06 12:03:01Z ume $
 
 NO_LINT=
 
@@ -6,11 +6,11 @@
 
 CFLAGS+=	-DHAVE_CONFIG_H -I${.CURDIR}/../../include
 
-.if defined(WITH_OPENLDAP)
+.if defined(WITH_OPENLDAP) && !defined(COMPAT_32BIT)
 OPENLDAPBASE?=	/usr/local
 LDAPLDADD=	-lldap -llber
 LDAPDPADD=	${LDAPLDADD:C;^-l(.*)$;${OPENLDAPBASE}/lib/lib\1.a;}
-LDAPCFLAGS=	-I${OPENLDAPBASE}/include -DOPENLDAP=1
+LDAPCFLAGS=	-I${OPENLDAPBASE}/include -DOPENLDAP=1 -DLDAP_DEPRECATED=1
 LDAPLDFLAGS=	-L${OPENLDAPBASE}/lib -Wl,-rpath,${OPENLDAPBASE}/lib
 .endif
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/kerberos5/lib/libhdb/Makefile
--- a/head/kerberos5/lib/libhdb/Makefile	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/kerberos5/lib/libhdb/Makefile	Tue Dec 06 20:26:16 2011 +0200
@@ -1,9 +1,9 @@
-# $FreeBSD: head/kerberos5/lib/libhdb/Makefile 225778 2011-09-27 07:14:12Z stas $
+# $FreeBSD: head/kerberos5/lib/libhdb/Makefile 228284 2011-12-05 16:38:52Z ume $
 
 LIB=	hdb
-LDFLAGS=	-Wl,--no-undefined
-LDADD=	-lasn1 -lcom_err -lkrb5 -lroken
-DPADD=	${LIBASN1} ${LIBCOM_ERR} ${LIBKRB5} ${LIBROKEN}
+LDFLAGS=	-Wl,--no-undefined ${LDAPLDFLAGS}
+LDADD=	-lasn1 -lcom_err -lkrb5 -lroken ${LDAPLDADD}
+DPADD=	${LIBASN1} ${LIBCOM_ERR} ${LIBKRB5} ${LIBROKEN} ${LDAPDPADD}
 
 INCS=	hdb-private.h \
 	hdb-protos.h \
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/kerberos5/usr.bin/kadmin/Makefile
--- a/head/kerberos5/usr.bin/kadmin/Makefile	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/kerberos5/usr.bin/kadmin/Makefile	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-# $FreeBSD$
+# $FreeBSD: head/kerberos5/usr.bin/kadmin/Makefile 228113 2011-11-29 03:49:03Z fjoe $
 
 PROG=	kadmin
 MAN=	kadmin.8
@@ -29,11 +29,11 @@
 DPADD=	${LIBKADM5CLNT} ${LIBKADM5SRV} ${LIBHDB} ${LIBKRB5} ${LIBHX509} \
 	${LIBSL} ${LIBROKEN} ${LIBVERS} ${LIBASN1} \
 	${LIBCRYPTO} ${LIBCRYPT} ${LIBCOM_ERR} \
-	${LIBREADLINE} ${LIBNCURSES} ${LDAPDPADD}
+	${LIBEDIT} ${LIBNCURSES} ${LDAPDPADD}
 LDADD=	-lkadm5clnt -lkadm5srv -lhdb -lkrb5 -lhx509 \
 	${LIBSL} -lroken ${LIBVERS} -lasn1 \
 	-lcrypto -lcrypt -lcom_err \
-	-lreadline -lncurses ${LDAPLDADD}
+	-ledit -lncurses ${LDAPLDADD}
 LDFLAGS=${LDAPLDFLAGS}
 
 .include <bsd.prog.mk>
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/kerberos5/usr.sbin/ktutil/Makefile
--- a/head/kerberos5/usr.sbin/ktutil/Makefile	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/kerberos5/usr.sbin/ktutil/Makefile	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-# $FreeBSD$
+# $FreeBSD: head/kerberos5/usr.sbin/ktutil/Makefile 228113 2011-11-29 03:49:03Z fjoe $
 
 PROG=	ktutil
 MAN=	ktutil.8
@@ -18,10 +18,10 @@
 CFLAGS+=-I${KRB5DIR}/lib/roken -I${KRB5DIR}/lib/sl -I.
 DPADD=	${LIBKADM5CLNT} ${LIBKRB5} ${LIBHX509} ${LIBSL} ${LIBROKEN} ${LIBVERS} \
 	${LIBASN1} ${LIBCRYPTO} ${LIBCRYPT} ${LIBCOM_ERR} \
-	${LIBREADLINE} ${LIBNCURSES}
+	${LIBEDIT} ${LIBNCURSES}
 LDADD=	-lkadm5clnt -lkrb5 -lhx509 ${LIBSL} -lroken ${LIBVERS} \
 	-lasn1 -lcrypto -lcrypt -lcom_err \
-	-lreadline -lncurses
+	-ledit -lncurses
 
 .include <bsd.prog.mk>
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/lib/Makefile
--- a/head/lib/Makefile	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/lib/Makefile	Tue Dec 06 20:26:16 2011 +0200
@@ -1,5 +1,5 @@
 #	@(#)Makefile	8.1 (Berkeley) 6/4/93
-# $FreeBSD: head/lib/Makefile 225952 2011-10-03 20:49:02Z nwhitehorn $
+# $FreeBSD: head/lib/Makefile 227987 2011-11-26 03:26:06Z dim $
 
 .include <bsd.own.mk>
 
@@ -48,7 +48,9 @@
 	libsbuf \
 	libtacplus \
 	libutil \
-	${_libypclnt}
+	${_libypclnt} \
+	${_libcxxrt} \
+	${_libcplusplus}
 
 SUBDIR=	${SUBDIR_ORDERED} \
 	libalias \
@@ -203,6 +205,11 @@
 _libmp=		libmp
 .endif
 
+.if ${MK_LIBCPLUSPLUS} != "no"
+_libcxxrt=	libcxxrt
+_libcplusplus=	libc++
+.endif
+
 .if ${MK_PMC} != "no"
 _libpmc=	libpmc
 .endif
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/lib/libc++/Makefile
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/lib/libc++/Makefile	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,155 @@
+# $FreeBSD: head/lib/libc++/Makefile 227983 2011-11-25 20:59:04Z theraven $
+
+LIBCXXRTDIR=    ${.CURDIR}/../../contrib/libcxxrt
+HDRDIR=         ${.CURDIR}/../../contrib/libc++/include
+SRCDIR=         ${.CURDIR}/../../contrib/libc++/src
+CXXINCLUDEDIR=  ${INCLUDEDIR}/c++/v${SHLIB_MAJOR}
+
+.PATH: ${SRCDIR}
+
+LIB=            c++
+SHLIB_MAJOR=    1
+
+SRCS+=          algorithm.cpp\
+                bind.cpp\
+                chrono.cpp\
+                condition_variable.cpp\
+                debug.cpp\
+                exception.cpp\
+                future.cpp\
+                hash.cpp\
+                ios.cpp\
+                iostream.cpp\
+                locale.cpp\
+                memory.cpp\
+                mutex.cpp\
+                new.cpp\
+                random.cpp\
+                regex.cpp\
+                stdexcept.cpp\
+                string.cpp\
+                strstream.cpp\
+                system_error.cpp\
+                thread.cpp\
+                typeinfo.cpp\
+                utility.cpp\
+                valarray.cpp
+
+WARNS=          0
+CXXFLAGS+=      -I${HDRDIR} -I${LIBCXXRTDIR} -std=c++0x -nostdlib -DLIBCXXRT
+
+DPADD=          ${LIBCXXRT}
+LDADD=          -L${.OBJDIR}/../libcxxrt/ -lcxxrt
+LDFLAGS+=       --verbose
+INCSGROUPS=     STD EXT
+
+STD_HEADERS=    __bit_reference\
+                __config\
+                __debug\
+                __functional_03\
+                __functional_base\
+                __functional_base_03\
+                __hash_table\
+                __locale\
+                __mutex_base\
+                __split_buffer\
+                __sso_allocator\
+                __std_stream\
+                __tree\
+                __tuple\
+                __tuple_03\
+                algorithm\
+                array\
+                atomic\
+                bitset\
+                cassert\
+                ccomplex\
+                cctype\
+                cerrno\
+                cfenv\
+                cfloat\
+                chrono\
+                cinttypes\
+                ciso646\
+                climits\
+                clocale\
+                cmath\
+                codecvt\
+                complex\
+                complex.h\
+                condition_variable\
+                csetjmp\
+                csignal\
+                cstdarg\
+                cstdbool\
+                cstddef\
+                cstdint\
+                cstdio\
+                cstdlib\
+                cstring\
+                ctgmath\
+                ctime\
+                cwchar\
+                cwctype\
+                deque\
+                exception\
+                forward_list\
+                fstream\
+                functional\
+                future\
+                initializer_list\
+                iomanip\
+                ios\
+                iosfwd\
+                iostream\
+                istream\
+                iterator\
+                limits\
+                list\
+                locale\
+                map\
+                memory\
+                mutex\
+                new\
+                numeric\
+                ostream\
+                queue\
+                random\
+                ratio\
+                regex\
+                scoped_allocator\
+                set\
+                sstream\
+                stack\
+                stdexcept\
+                streambuf\
+                string\
+                strstream\
+                system_error\
+                tgmath.h\
+                thread\
+                tuple\
+                type_traits\
+                typeindex\
+                typeinfo\
+                unordered_map\
+                unordered_set\
+                utility\
+                valarray\
+                vector
+
+.for hdr in ${STD_HEADERS}
+STD+=           ${HDRDIR}/${hdr}
+.endfor
+STDDIR=         ${CXXINCLUDEDIR}
+
+EXT_HEADERS=    __hash\
+                hash_map\
+                hash_set
+
+.for hdr in ${EXT_HEADERS}
+EXT+=           ${HDRDIR}/ext/${hdr}
+.endfor
+EXTDIR=         ${CXXINCLUDEDIR}/ext
+
+.include <bsd.lib.mk>
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/lib/libc/gen/_pthread_stubs.c
--- a/head/lib/libc/gen/_pthread_stubs.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/lib/libc/gen/_pthread_stubs.c	Tue Dec 06 20:26:16 2011 +0200
@@ -25,11 +25,12 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/lib/libc/gen/_pthread_stubs.c 228002 2011-11-26 16:49:25Z theraven $");
 
 #include <signal.h>
 #include <pthread.h>
 #include <stdlib.h>
+#include <errno.h>
 
 #include "libc_private.h"
 
@@ -53,6 +54,7 @@
 static void 		*stub_null(void);
 static struct pthread	*stub_self(void);
 static int		stub_zero(void);
+static int		stub_fail(void);
 static int		stub_true(void);
 static void		stub_exit(void);
 
@@ -93,7 +95,7 @@
 	{PJT_DUAL_ENTRY(stub_exit)},    /* PJT_EXIT */
 	{PJT_DUAL_ENTRY(stub_null)},    /* PJT_GETSPECIFIC */
 	{PJT_DUAL_ENTRY(stub_zero)},    /* PJT_JOIN */
-	{PJT_DUAL_ENTRY(stub_zero)},    /* PJT_KEY_CREATE */
+	{PJT_DUAL_ENTRY(stub_fail)},    /* PJT_KEY_CREATE */
 	{PJT_DUAL_ENTRY(stub_zero)},    /* PJT_KEY_DELETE */
 	{PJT_DUAL_ENTRY(stub_zero)},    /* PJT_KILL */
 	{PJT_DUAL_ENTRY(stub_main)},    /* PJT_MAIN_NP */
@@ -105,7 +107,7 @@
 	{PJT_DUAL_ENTRY(stub_zero)},    /* PJT_MUTEX_LOCK */
 	{PJT_DUAL_ENTRY(stub_zero)},    /* PJT_MUTEX_TRYLOCK */
 	{PJT_DUAL_ENTRY(stub_zero)},    /* PJT_MUTEX_UNLOCK */
-	{PJT_DUAL_ENTRY(stub_zero)},    /* PJT_ONCE */
+	{PJT_DUAL_ENTRY(stub_fail)},    /* PJT_ONCE */
 	{PJT_DUAL_ENTRY(stub_zero)},    /* PJT_RWLOCK_DESTROY */
 	{PJT_DUAL_ENTRY(stub_zero)},    /* PJT_RWLOCK_INIT */
 	{PJT_DUAL_ENTRY(stub_zero)},    /* PJT_RWLOCK_RDLOCK */
@@ -293,6 +295,12 @@
 }
 
 static int
+stub_fail(void)
+{
+	return (ENOSYS);
+}
+
+static int
 stub_main(void)
 {
 	return (-1);
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/lib/libc/gen/syslog.c
--- a/head/lib/libc/gen/syslog.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/lib/libc/gen/syslog.c	Tue Dec 06 20:26:16 2011 +0200
@@ -31,7 +31,7 @@
 static char sccsid[] = "@(#)syslog.c	8.5 (Berkeley) 4/29/95";
 #endif /* LIBC_SCCS and not lint */
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/lib/libc/gen/syslog.c 220157 2011-03-30 14:15:18Z pluknet $");
+__FBSDID("$FreeBSD: head/lib/libc/gen/syslog.c 228193 2011-12-02 01:06:33Z obrien $");
 
 #include "namespace.h"
 #include <sys/types.h>
@@ -265,7 +265,7 @@
 	 *  1) syslogd was restarted
 	 *  2) /var/run/log is out of socket buffer space, which
 	 *     in most cases means local DoS.
-	 * We attempt to reconnect to /var/run/log to take care of
+	 * We attempt to reconnect to /var/run/log[priv] to take care of
 	 * case #1 and keep send()ing data to cover case #2
 	 * to give syslogd a chance to empty its socket buffer.
 	 *
@@ -281,13 +281,13 @@
 			connectlog();
 		}
 		do {
+			if (status == CONNPRIV)
+				break;
 			_usleep(1);
 			if (send(LogFile, tbuf, cnt, 0) >= 0) {
 				THREAD_UNLOCK();
 				return;
 			}
-			if (status == CONNPRIV)
-				break;
 		} while (errno == ENOBUFS);
 	} else {
 		THREAD_UNLOCK();
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/lib/libc/locale/duplocale.3
--- a/head/lib/libc/locale/duplocale.3	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/lib/libc/locale/duplocale.3	Tue Dec 06 20:26:16 2011 +0200
@@ -25,7 +25,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/lib/libc/locale/duplocale.3 227753 2011-11-20 14:45:42Z theraven $
+.\" $FreeBSD: head/lib/libc/locale/duplocale.3 228199 2011-12-02 11:55:09Z obrien $
 .\"
 .Dd September 17 2011
 .Dt DUPLOCALE 3
@@ -36,25 +36,26 @@
 .Sh LIBRARY
 .Lb libc
 .Sh SYNOPSIS
-.In xlocale.h 
-.Ft locale_t 
+.In xlocale.h
+.Ft locale_t
 .Fn duplocale "locale_t locale"
 .Sh DESCRIPTION
 Duplicates an existing
 .Fa locale_t
-returning a new 
+returning a new
 .Fa locale_t
 that refers to the same locale values but has independent internal state.
 Various functions, such as
 .Xr mblen 3
-require presistent state.  These functions formerly used static variables and
-calls to them from multiple threads had undefined behavior.  They now use
-fields in the
+require presistent state.
+These functions formerly used static variables and calls to them from multiple
+threads had undefined behavior.
+They now use fields in the
 .Fa locale_t
 associated with the current thread by
 .Xr uselocale 3 .
 These calls are therefore only thread safe on threads with a unique per-thread
-locale.  
+locale.
 .Pt
 The locale returned by this call must be freed with
 .Xr freelocale 3 .
@@ -63,8 +64,9 @@
 .Xr uselocale 3
 should make a copy of the
 .Fa locale_t
-implicitly to ensure thread safety, and a copy of the global locale should be
-installed lazily on each thread.  The FreeBSD implementation does not do this,
+implicitly to ensure thread safety,
+and a copy of the global locale should be installed lazily on each thread.
+The FreeBSD implementation does not do this,
 for compatibility with Darwin.
 .Sh SEE ALSO
 .Xr freelocale 3 ,
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/lib/libc/locale/freelocale.3
--- a/head/lib/libc/locale/freelocale.3	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/lib/libc/locale/freelocale.3	Tue Dec 06 20:26:16 2011 +0200
@@ -25,7 +25,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/lib/libc/locale/freelocale.3 227753 2011-11-20 14:45:42Z theraven $
+.\" $FreeBSD: head/lib/libc/locale/freelocale.3 228199 2011-12-02 11:55:09Z obrien $
 .Dd September 17 2011
 .Dt FREELOCALE 3
 .Os
@@ -33,22 +33,22 @@
 .Nm freelocale
 .Nd Frees a locale created with
 .Xr duplocale 3
-or 
+or
 .Xr newlocale 3 .
 .Sh LIBRARY
 .Lb libc
 .Sh SYNOPSIS
-.In xlocale.h 
+.In xlocale.h
 .Ft int
 .Fn freelocale "locale_t locale"
 .Sh DESCRIPTION
 Frees a
 .Fa locale_t .
-This relinquishes any resources held exclusively by this locale.  Note that
-locales share reference-counted components, so a call to this function is not
-guaranteed to free all of the components.
+This relinquishes any resources held exclusively by this locale.
+Note that locales share reference-counted components,
+so a call to this function is not guaranteed to free all of the components.
 .Sh RETURN VALUES
-Returns 0 on success or -1 on error.  
+Returns 0 on success or -1 on error.
 .Sh SEE ALSO
 .Xr duplocale 3 ,
 .Xr localeconv 3 ,
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/lib/libc/locale/localeconv.3
--- a/head/lib/libc/locale/localeconv.3	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/lib/libc/locale/localeconv.3	Tue Dec 06 20:26:16 2011 +0200
@@ -30,7 +30,7 @@
 .\"
 .\" From @(#)setlocale.3	8.1 (Berkeley) 6/9/93
 .\" From FreeBSD: src/lib/libc/locale/setlocale.3,v 1.28 2003/11/15 02:26:04 tjr Exp
-.\" $FreeBSD: head/lib/libc/locale/localeconv.3 227753 2011-11-20 14:45:42Z theraven $
+.\" $FreeBSD: head/lib/libc/locale/localeconv.3 228199 2011-12-02 11:55:09Z obrien $
 .\"
 .Dd November 21, 2003
 .Dt LOCALECONV 3
@@ -203,7 +203,7 @@
 The
 .Fn localeconv_l
 function takes an explicit locale parameter.  For more information, see
-.Xr xlocale 3 .  
+.Xr xlocale 3 .
 .Sh RETURN VALUES
 The
 .Fn localeconv
@@ -212,9 +212,10 @@
 .Xr setlocale 3
 or
 .Fn localeconv .
-The return value for 
+The return value for
 .Fn localeconv_l
-is stored with the locale.  It will remain valid until a subsequent call to
+is stored with the locale.
+It will remain valid until a subsequent call to
 .Xr freelocale 3 .
 If a thread-local locale is in effect then the return value from
 .Fn localeconv
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/lib/libc/locale/newlocale.3
--- a/head/lib/libc/locale/newlocale.3	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/lib/libc/locale/newlocale.3	Tue Dec 06 20:26:16 2011 +0200
@@ -25,46 +25,50 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/lib/libc/locale/newlocale.3 227753 2011-11-20 14:45:42Z theraven $
+.\" $FreeBSD: head/lib/libc/locale/newlocale.3 228199 2011-12-02 11:55:09Z obrien $
 .Dd September 17 2011
 .Dt newlocale 3
 .Os
 .Sh NAME
 .Nm newlocale
-.Nd Creates a new locale 
+.Nd Creates a new locale
 .Sh LIBRARY
 .Lb libc
 .Sh SYNOPSIS
 .In xlocale
-.Ft 
+.Ft
 .Fn newlocale "int mask" "const char * locale" "locale_t base"
 .Sh DESCRIPTION
-Creates a new locale, inheriting some properties from an existing locale.  The
-.Fa mask 
+Creates a new locale, inheriting some properties from an existing locale.
+The
+.Fa mask
 defines the components that the new locale will have set to the locale with the
-name specified in the 
+name specified in the
 .Fa locale
-parameter.  Any other components will be inherited from
+parameter.
+Any other components will be inherited from
 .Fa base .
 .Pt
 The
 .Fa mask
 is either
 .Fa LC_ALL_MASK,
-indicating all possible locale components, or the logical OR of some
-combination of the following:
+indicating all possible locale components,
+or the logical OR of some combination of the following:
 .Bl -tag -width "LC_MESSAGES_MASK" -offset indent
 .It LC_COLLATE_MASK
-The locale for string collation routines.  This controls alphabetic ordering in
+The locale for string collation routines.
+This controls alphabetic ordering in
 .Xr strcoll 3
- and 
+ and
 .Xr strxfrm 3 .
 .It LC_CTYPE_MASK
 The locale for the
 .Xr ctype 3
 and
 .Xr multibyte 3
-functions.  This controls recognition of upper and lower case, alpha- betic or
+functions.
+This controls recognition of upper and lower case, alphabetic or
 non-alphabetic characters, and so on.
 .It LC_MESSAGES_MASK
 Set a locale for message catalogs, see
@@ -76,8 +80,8 @@
 .Xr localeconv 3
 function.
 .It LC_NUMERIC_MASK
-Set a locale for formatting numbers.  This controls the for-
-matting of decimal points in input and output of floating
+Set a locale for formatting numbers.
+This controls the formatting of decimal points in input and output of floating
 point numbers in functions such as
 .Xr printf 3
 and
@@ -95,7 +99,8 @@
 .Sh RETURN VALUES
 Returns a new, valid,
 .Fa locale_t
-or NULL if an error occurs.  You must free the returned locale with
+or NULL if an error occurs.
+You must free the returned locale with
 .Xr freelocale 3 .
 .Sh SEE ALSO
 .Xr duplocale 3 ,
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/lib/libc/locale/querylocale.3
--- a/head/lib/libc/locale/querylocale.3	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/lib/libc/locale/querylocale.3	Tue Dec 06 20:26:16 2011 +0200
@@ -25,7 +25,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/lib/libc/locale/querylocale.3 227753 2011-11-20 14:45:42Z theraven $
+.\" $FreeBSD: head/lib/libc/locale/querylocale.3 228199 2011-12-02 11:55:09Z obrien $
 .\"
 .Dd September 17 2011
 .Dt QUERYLOCALE 3
@@ -36,15 +36,15 @@
 .Sh LIBRARY
 .Lb libc
 .Sh SYNOPSIS
-.In xlocale.h 
+.In xlocale.h
 .Ft const char *
 .Fn querylocale "int mask" "locale_t locale"
 .Sh DESCRIPTION
 Returns the name of the locale for the category specified by
 .Fa mask.
 This possible values for the mask are the same as those in
-.Xr newlocale 3 .  If more than one bit in the mask is set, the returned value
-is undefined.
+.Xr newlocale 3 .
+If more than one bit in the mask is set, the returned value is undefined.
 .Sh SEE ALSO
 .Xr duplocale 3 ,
 .Xr freelocale 3 ,
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/lib/libc/locale/uselocale.3
--- a/head/lib/libc/locale/uselocale.3	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/lib/libc/locale/uselocale.3	Tue Dec 06 20:26:16 2011 +0200
@@ -25,7 +25,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/lib/libc/locale/uselocale.3 227753 2011-11-20 14:45:42Z theraven $
+.\" $FreeBSD: head/lib/libc/locale/uselocale.3 228199 2011-12-02 11:55:09Z obrien $
 .\"
 .Dd September 17 2011
 .Dt USELOCALE 3
@@ -36,17 +36,18 @@
 .Sh LIBRARY
 .Lb libc
 .Sh SYNOPSIS
-.In xlocale.h 
+.In xlocale.h
 .Ft locale_t
 .Fn uselocale "locale_t locale"
 .Sh DESCRIPTION
-Specifies the locale for this thread to use.  Specifying
+Specifies the locale for this thread to use.
+Specifying
 .Fa LC_GLOBAL_LOCALE
-disables the per-thread locale, while NULL returns the current locale without
-setting a new one.
+disables the per-thread locale,
+while NULL returns the current locale without setting a new one.
 .Sh RETURN VALUES
-Returns the previous locale, or LC_GLOBAL_LOCALE if this thread has no locale
-associated with it.
+Returns the previous locale,
+or LC_GLOBAL_LOCALE if this thread has no locale associated with it.
 .Sh SEE ALSO
 .Xr duplocale 3 ,
 .Xr freelocale 3 ,
@@ -55,5 +56,5 @@
 .Xr querylocale 3 ,
 .Xr xlocale 3
 .Sh STANDARDS
-This function, conforms to
+This function conforms to
 .St -p1003.1-2008
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/lib/libc/locale/wctype.c
--- a/head/lib/libc/locale/wctype.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/lib/libc/locale/wctype.c	Tue Dec 06 20:26:16 2011 +0200
@@ -30,7 +30,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/lib/libc/locale/wctype.c 227753 2011-11-20 14:45:42Z theraven $");
+__FBSDID("$FreeBSD: head/lib/libc/locale/wctype.c 228269 2011-12-05 00:00:47Z jilles $");
 
 #include <ctype.h>
 #include <string.h>
@@ -57,35 +57,54 @@
 wctype_t
 wctype_l(const char *property, locale_t locale)
 {
-	static const struct {
-		const char	*name;
-		wctype_t	 mask;
-	} props[] = {
-		{ "alnum",	_CTYPE_A|_CTYPE_D },
-		{ "alpha",	_CTYPE_A },
-		{ "blank",	_CTYPE_B },
-		{ "cntrl",	_CTYPE_C },
-		{ "digit",	_CTYPE_D },
-		{ "graph",	_CTYPE_G },
-		{ "lower",	_CTYPE_L },
-		{ "print",	_CTYPE_R },
-		{ "punct",	_CTYPE_P },
-		{ "space",	_CTYPE_S },
-		{ "upper",	_CTYPE_U },
-		{ "xdigit",	_CTYPE_X },
-		{ "ideogram",	_CTYPE_I },	/* BSD extension */
-		{ "special",	_CTYPE_T },	/* BSD extension */
-		{ "phonogram",	_CTYPE_Q },	/* BSD extension */
-		{ "rune",	0xFFFFFF00L },	/* BSD extension */
-		{ NULL,		0UL },		/* Default */
+	const char *propnames = 
+		"alnum\0"
+		"alpha\0"
+		"blank\0"
+		"cntrl\0"
+		"digit\0"
+		"graph\0"
+		"lower\0"
+		"print\0"
+		"punct\0"
+		"space\0"
+		"upper\0"
+		"xdigit\0"
+		"ideogram\0"	/* BSD extension */
+		"special\0"	/* BSD extension */
+		"phonogram\0"	/* BSD extension */
+		"rune\0";	/* BSD extension */
+	static const wctype_t propmasks[] = {
+		_CTYPE_A|_CTYPE_D,
+		_CTYPE_A,
+		_CTYPE_B,
+		_CTYPE_C,
+		_CTYPE_D,
+		_CTYPE_G,
+		_CTYPE_L,
+		_CTYPE_R,
+		_CTYPE_P,
+		_CTYPE_S,
+		_CTYPE_U,
+		_CTYPE_X,
+		_CTYPE_I,
+		_CTYPE_T,
+		_CTYPE_Q,
+		0xFFFFFF00L
 	};
-	int i;
+	size_t len1, len2;
+	const char *p;
+	const wctype_t *q;
 
-	i = 0;
-	while (props[i].name != NULL && strcmp(props[i].name, property) != 0)
-		i++;
+	len1 = strlen(property);
+	q = propmasks;
+	for (p = propnames; (len2 = strlen(p)) != 0; p += len2 + 1) {
+		if (len1 == len2 && memcmp(property, p, len1) == 0)
+			return (*q);
+		q++;
+	}
 
-	return (props[i].mask);
+	return (0UL);
 }
 
 wctype_t wctype(const char *property)
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/lib/libc/locale/xlocale.3
--- a/head/lib/libc/locale/xlocale.3	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/lib/libc/locale/xlocale.3	Tue Dec 06 20:26:16 2011 +0200
@@ -25,7 +25,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/lib/libc/locale/xlocale.3 227753 2011-11-20 14:45:42Z theraven $
+.\" $FreeBSD: head/lib/libc/locale/xlocale.3 228199 2011-12-02 11:55:09Z obrien $
 .\"
 .Dd September 17 2011
 .Dt XLOCALE 3
@@ -39,39 +39,45 @@
 .In xlocale.h
 .Sh DESCRIPTION
 The extended locale support includes a set of functions for setting
-thread-local locales, as well convenience functions for performing locale-aware
+thread-local locales,
+as well convenience functions for performing locale-aware
 calls with a specified locale.
 .Pp
 The core of the xlocale API is the
 .Fa locale_t
-type.  This is an opaque type encapsulating a locale.  Instances of this can be
-either set as the locale for a specific thread or passed directly to the
+type.
+This is an opaque type encapsulating a locale.
+Instances of this can be either set as the locale for a specific thread or
+passed directly to the
 .Fa _l
-suffixed variants of various standard C functions.  Two special
+suffixed variants of various standard C functions.
+Two special
 .Fa locale_t
 values are available:
-.Bl -bullet -offset indent 
+.Bl -bullet -offset indent
 .It
-NULL refers to the current locale for the thread, or to the global locale if no
-locale has been set for this thread.
+NULL refers to the current locale for the thread,
+or to the global locale if no locale has been set for this thread.
 .It
 LC_GLOBAL_LOCALE refers to the global locale.
 .El
 .Pp
-The global locale is the locale set with the 
+The global locale is the locale set with the
 .Xr setlocale 3
 function.
 .Sh CAVEATS
-The 
+The
 .Xr setlocale 3
-function, and others in the family, refer to the global locale.  Other
-functions that depend on the locale, however, will take the thread-local locale
-if one has been set.  This means that the idiom of setting the locale using
+function, and others in the family, refer to the global locale.
+Other functions that depend on the locale, however,
+will take the thread-local locale if one has been set.
+This means that the idiom of setting the locale using
 .Xr setlocale 3 ,
-calling a locale-dependent function, and then restoring the locale will not
+calling a locale-dependent function,
+and then restoring the locale will not
 have the expected behavior if the current thread has had a locale set using
 .Xr uselocale 3 .
-You should avoid this idiom and prefer to use the 
+You should avoid this idiom and prefer to use the
 .Fa _l
 suffixed versions instead.
 .Sh SEE ALSO
@@ -84,29 +90,34 @@
 .Sh CONVENIENCE FUNCTIONS
 The xlocale API includes a number of
 .Fa _l
-suffixed convenience functions.  These are variants of standard C functions
-that have been modified to take an explicit 
+suffixed convenience functions.
+These are variants of standard C functions
+that have been modified to take an explicit
 .Fa locale_t
-parameter as the final argument or, in the case of variadic functions, as an
-additional argument directly before the format string.  Each of these functions
-accepts either NULL or LC_GLOBAL_LOCALE.  In these functions, NULL refers to
-the C locale, rather than the thread's current locale.  If you wish to use the
-thread's current locale, then use the unsuffixed version of the function.
+parameter as the final argument or, in the case of variadic functions,
+as an additional argument directly before the format string.
+Each of these functions accepts either NULL or LC_GLOBAL_LOCALE.
+In these functions, NULL refers to the C locale,
+rather than the thread's current locale.
+If you wish to use the thread's current locale,
+then use the unsuffixed version of the function.
 .Pp
-These functions are exposed by including 
+These functions are exposed by including
 .In xlocale.h
 .Em after
-including the relevant headers for the standard variant.  For example, the 
+including the relevant headers for the standard variant.
+For example, the
 .Xr strtol_l 3
-function is exposed by including 
+function is exposed by including
 .In xlocale.h
-after 
+after
 .In stdlib.h ,
 which defines
 .Xr strtol 3 .
 .Pp
-For reference, a complete list of the locale-aware functions that are available
-in this form, along with the headers that expose them, is provided here:
+For reference,
+a complete list of the locale-aware functions that are available in this form,
+along with the headers that expose them, is provided here:
 .Pp
 .Bl -tag -width "<monetary.h> "
 .It In wctype.h
@@ -117,7 +128,7 @@
 .Xr iswdigit_l 3 ,
 .Xr iswgraph_l 3 ,
 .Xr iswlower_l 3 ,
-.Xr iswprint_l 3 , 
+.Xr iswprint_l 3 ,
 .Xr iswpunct_l 3 ,
 .Xr iswspace_l 3 ,
 .Xr iswupper_l 3 ,
@@ -264,7 +275,7 @@
 conform to
 .St -p1003.1-2008 .
 .Sh HISTORY
-The xlocale APIs first appeared in Darwin 8.0.  This implementation was
-written by David Chisnall, under sponsorship from the FreeBSD Foundation and
-first appeared in
+The xlocale APIs first appeared in Darwin 8.0.
+This implementation was written by David Chisnall,
+under sponsorship from the FreeBSD Foundation and first appeared in
 .Fx 9.1 .
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/lib/libc/string/strcasecmp.c
--- a/head/lib/libc/string/strcasecmp.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/lib/libc/string/strcasecmp.c	Tue Dec 06 20:26:16 2011 +0200
@@ -36,7 +36,7 @@
 static char sccsid[] = "@(#)strcasecmp.c	8.1 (Berkeley) 6/4/93";
 #endif /* LIBC_SCCS and not lint */
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/lib/libc/string/strcasecmp.c 227812 2011-11-22 02:50:24Z eadler $");
+__FBSDID("$FreeBSD: head/lib/libc/string/strcasecmp.c 228202 2011-12-02 15:41:09Z eadler $");
 
 #include <strings.h>
 #include <ctype.h>
@@ -48,9 +48,6 @@
 	const u_char
 			*us1 = (const u_char *)s1,
 			*us2 = (const u_char *)s2;
-	if (s1 == s2)
-		return (0);
-
 	FIX_LOCALE(locale);
 
 	while (tolower_l(*us1, locale) == tolower_l(*us2++, locale))
@@ -68,22 +65,18 @@
 strncasecmp_l(const char *s1, const char *s2, size_t n, locale_t locale)
 {
 	FIX_LOCALE(locale);
+	if (n != 0) {
+		const u_char
+				*us1 = (const u_char *)s1,
+				*us2 = (const u_char *)s2;
 
-	const u_char
-			*us1 = (const u_char *)s1,
-			*us2 = (const u_char *)s2;
-	
-	/* use a bitwise or to avoid an additional branch instruction */
-	if ((s1 == s2) | (n == 0))
-		return (0);
-
-
-	do {
-		if (tolower_l(*us1, locale) != tolower_l(*us2++, locale))
-			return (tolower_l(*us1, locale) - tolower_l(*--us2, locale));
-		if (*us1++ == '\0')
-			break;
-	} while (--n != 0);
+		do {
+			if (tolower_l(*us1, locale) != tolower_l(*us2++, locale))
+				return (tolower_l(*us1, locale) - tolower_l(*--us2, locale));
+			if (*us1++ == '\0')
+				break;
+		} while (--n != 0);
+	}
 	return (0);
 }
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/lib/libc/string/strcmp.c
--- a/head/lib/libc/string/strcmp.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/lib/libc/string/strcmp.c	Tue Dec 06 20:26:16 2011 +0200
@@ -34,7 +34,7 @@
 static char sccsid[] = "@(#)strcmp.c	8.1 (Berkeley) 6/4/93";
 #endif /* LIBC_SCCS and not lint */
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/lib/libc/string/strcmp.c 227808 2011-11-22 00:07:53Z eadler $");
+__FBSDID("$FreeBSD: head/lib/libc/string/strcmp.c 228202 2011-12-02 15:41:09Z eadler $");
 
 #include <string.h>
 
@@ -44,9 +44,6 @@
 int
 strcmp(const char *s1, const char *s2)
 {
-	if (s1 == s2)
-	    return (0);
-
 	while (*s1 == *s2++)
 		if (*s1++ == '\0')
 			return (0);
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/lib/libc/string/strcoll.c
--- a/head/lib/libc/string/strcoll.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/lib/libc/string/strcoll.c	Tue Dec 06 20:26:16 2011 +0200
@@ -31,7 +31,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/lib/libc/string/strcoll.c 227808 2011-11-22 00:07:53Z eadler $");
+__FBSDID("$FreeBSD: head/lib/libc/string/strcoll.c 228202 2011-12-02 15:41:09Z eadler $");
 
 #include <stdlib.h>
 #include <string.h>
@@ -40,7 +40,7 @@
 #include <stdio.h>
 
 int
-strcoll_l(const char *s1, const char *s2, locale_t locale)
+strcoll_l(const char *s, const char *s2, locale_t locale)
 {
 	int len, len2, prim, prim2, sec, sec2, ret, ret2;
 	const char *t, *t2;
@@ -50,16 +50,16 @@
 		(struct xlocale_collate*)locale->components[XLC_COLLATE];
 
 	if (table->__collate_load_error)
-		return strcmp(s1, s2);
+		return strcmp(s, s2);
 
 	len = len2 = 1;
 	ret = ret2 = 0;
 	if (table->__collate_substitute_nontrivial) {
-		t = tt = __collate_substitute(table, s1);
+		t = tt = __collate_substitute(table, s);
 		t2 = tt2 = __collate_substitute(table, s2);
 	} else {
 		tt = tt2 = NULL;
-		t = s1;
+		t = s;
 		t2 = s2;
 	}
 	while(*t && *t2) {
@@ -95,8 +95,8 @@
 }
 
 int
-strcoll(const char *s1, const char *s2)
+strcoll(const char *s, const char *s2)
 {
-	return strcoll_l(s1, s2, __get_locale());
+	return strcoll_l(s, s2, __get_locale());
 }
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/lib/libc/string/strncmp.c
--- a/head/lib/libc/string/strncmp.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/lib/libc/string/strncmp.c	Tue Dec 06 20:26:16 2011 +0200
@@ -31,7 +31,7 @@
 static char sccsid[] = "@(#)strncmp.c	8.1 (Berkeley) 6/4/93";
 #endif /* LIBC_SCCS and not lint */
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/lib/libc/string/strncmp.c 227812 2011-11-22 02:50:24Z eadler $");
+__FBSDID("$FreeBSD: head/lib/libc/string/strncmp.c 228202 2011-12-02 15:41:09Z eadler $");
 
 #include <string.h>
 
@@ -39,10 +39,8 @@
 strncmp(const char *s1, const char *s2, size_t n)
 {
 
-	/* use a bitwise or to avoid an additional branch instruction */
-	if ((n == 0) | (s1 == s2))
+	if (n == 0)
 		return (0);
-
 	do {
 		if (*s1 != *s2++)
 			return (*(const unsigned char *)s1 -
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/lib/libc/sys/cap_enter.2
--- a/head/lib/libc/sys/cap_enter.2	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/lib/libc/sys/cap_enter.2	Tue Dec 06 20:26:16 2011 +0200
@@ -26,7 +26,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/lib/libc/sys/cap_enter.2 228040 2011-11-27 19:45:41Z rwatson $
 .\"
 .Dd June 11, 2009
 .Dt CAP_ENTER 2
@@ -89,7 +89,8 @@
 .Rv -std cap_enter cap_getmode
 .Sh SEE ALSO
 .Xr cap_new 2 ,
-.Xr fexecve 2
+.Xr fexecve 2 ,
+.Xr capsicum 4
 .Sh HISTORY
 Support for capabilities and capabilities mode was developed as part of the
 .Tn TrustedBSD
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/lib/libc/sys/cap_new.2
--- a/head/lib/libc/sys/cap_new.2	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/lib/libc/sys/cap_new.2	Tue Dec 06 20:26:16 2011 +0200
@@ -26,7 +26,7 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/lib/libc/sys/cap_new.2 224987 2011-08-18 22:51:30Z jonathan $
+.\" $FreeBSD: head/lib/libc/sys/cap_new.2 228040 2011-11-27 19:45:41Z rwatson $
 .\"
 .Dd July 20, 2011
 .Dt CAP_NEW 2
@@ -456,6 +456,7 @@
 .Xr sem_post 3 ,
 .Xr sem_trywait 3 ,
 .Xr sem_wait 3 ,
+.Xr capsicum 4 ,
 .Xr snp 4
 .Sh HISTORY
 Support for capabilities and capabilities mode was developed as part of the
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/lib/libcxxrt/Makefile
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/lib/libcxxrt/Makefile	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,25 @@
+# $FreeBSD: head/lib/libcxxrt/Makefile 228004 2011-11-26 18:46:33Z theraven $
+
+SRCDIR=       ${.CURDIR}/../../contrib/libcxxrt
+
+SHLIB_MAJOR=  1
+SHLIBDIR?=    /lib
+
+.PATH: ${SRCDIR}
+
+LIB=          cxxrt
+
+SRCS+=        libelftc_dem_gnu3.c\
+              terminate.cc\
+              dynamic_cast.cc\
+              memory.cc\
+              auxhelper.cc\
+              exception.cc\
+              stdexcept.cc\
+              typeinfo.cc\
+              guard.cc
+
+WARNS=        0
+CFLAGS+=      -I${SRCDIR}
+
+.include <bsd.lib.mk>
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/lib/libedit/edit/readline/Makefile
--- a/head/lib/libedit/edit/readline/Makefile	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/lib/libedit/edit/readline/Makefile	Tue Dec 06 20:26:16 2011 +0200
@@ -1,7 +1,8 @@
 # Copyright (c) 2011 David E O'Brien
-# $FreeBSD: head/lib/libedit/edit/readline/Makefile 220370 2011-04-05 18:41:01Z obrien $
+# $FreeBSD: head/lib/libedit/edit/readline/Makefile 228116 2011-11-29 06:21:01Z fjoe $
 
 INCS=	readline.h history.h
+INCSLINKS=	readline.h ${INCSDIR}/tilde.h
 
 INCSDIR= ${INCLUDEDIR}/edit/readline
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/lib/libedit/edit/readline/readline.h
--- a/head/lib/libedit/edit/readline/readline.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/lib/libedit/edit/readline/readline.h	Tue Dec 06 20:26:16 2011 +0200
@@ -28,7 +28,7 @@
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  * POSSIBILITY OF SUCH DAMAGE.
  *
- * $FreeBSD: head/lib/libedit/edit/readline/readline.h 220624 2011-04-14 15:42:15Z obrien $
+ * $FreeBSD: head/lib/libedit/edit/readline/readline.h 228114 2011-11-29 04:50:57Z fjoe $
  */
 #ifndef _READLINE_H_
 #define _READLINE_H_
@@ -200,7 +200,6 @@
 void		 rl_set_screen_size(int, int);
 char 		*rl_filename_completion_function (const char *, int);
 int		 _rl_abort_internal(void);
-int		 _rl_qsort_string_compare(char **, char **);
 char 	       **rl_completion_matches(const char *, rl_compentry_func_t *);
 void		 rl_forced_update_display(void);
 int		 rl_set_prompt(const char *);
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/lib/libpam/modules/Makefile.inc
--- a/head/lib/libpam/modules/Makefile.inc	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/lib/libpam/modules/Makefile.inc	Tue Dec 06 20:26:16 2011 +0200
@@ -1,12 +1,21 @@
-# $FreeBSD: head/lib/libpam/modules/Makefile.inc 227798 2011-11-21 16:40:39Z des $
+# $FreeBSD: head/lib/libpam/modules/Makefile.inc 227933 2011-11-24 13:18:58Z des $
 
 PAMDIR=		${.CURDIR}/../../../../contrib/openpam
 
 NO_INSTALLLIB=
 NO_PROFILE=
 
-CFLAGS+=	-I${PAMDIR}/include -I${.CURDIR}/../../libpam
+CFLAGS+= -I${PAMDIR}/include -I${.CURDIR}/../../libpam
 
+# This is nasty.
+# For the static case, libpam.a depends on the modules.
+# For the dynamic case, the modules depend on libpam.so.N
+.if defined(_NO_LIBPAM_SO_YET)
+NO_PIC=
+.else
 SHLIB_NAME?=	${LIB}.so.${SHLIB_MAJOR}
+DPADD+=		${LIBPAM}
+LDADD+=		-lpam
+.endif
 
 .include "../Makefile.inc"
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/lib/libpam/modules/pam_unix/Makefile
--- a/head/lib/libpam/modules/pam_unix/Makefile	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/lib/libpam/modules/pam_unix/Makefile	Tue Dec 06 20:26:16 2011 +0200
@@ -32,11 +32,9 @@
 # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 # SUCH DAMAGE.
 #
-# $FreeBSD$
+# $FreeBSD: head/lib/libpam/modules/pam_unix/Makefile 228065 2011-11-28 14:01:17Z fjoe $
 
-NO_PROFILE=
-NO_INSTALLLIB=
-.include <bsd.own.mk>
+.include <bsd.init.mk>
 
 LIB=	pam_unix
 SRCS=	pam_unix.c
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/lib/libusb/libusb10.c
--- a/head/lib/libusb/libusb10.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/lib/libusb/libusb10.c	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-/* $FreeBSD: head/lib/libusb/libusb10.c 226220 2011-10-10 16:13:33Z hselasky $ */
+/* $FreeBSD: head/lib/libusb/libusb10.c 228236 2011-12-03 16:30:47Z hselasky $ */
 /*-
  * Copyright (c) 2009 Sylvestre Gallon. All rights reserved.
  * Copyright (c) 2009 Hans Petter Selasky. All rights reserved.
@@ -417,9 +417,12 @@
 	if ((i = libusb_get_device_list(ctx, &devs)) < 0)
 		return (NULL);
 
+	pdev = NULL;
 	for (j = 0; j < i; j++) {
-		pdev = devs[j]->os_priv;
-		pdesc = libusb20_dev_get_device_desc(pdev);
+		struct libusb20_device *tdev;
+
+		tdev = devs[j]->os_priv;
+		pdesc = libusb20_dev_get_device_desc(tdev);
 		/*
 		 * NOTE: The USB library will automatically swap the
 		 * fields in the device descriptor to be of host
@@ -427,13 +430,10 @@
 		 */
 		if (pdesc->idVendor == vendor_id &&
 		    pdesc->idProduct == product_id) {
-			if (libusb_open(devs[j], &pdev) < 0)
-				pdev = NULL;
+			libusb_open(devs[j], &pdev);
 			break;
 		}
 	}
-	if (j == i)
-		pdev = NULL;
 
 	libusb_free_device_list(devs, 1);
 	DPRINTF(ctx, LIBUSB_DEBUG_FUNCTION, "libusb_open_device_width_vid_pid leave");
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/release/doc/en_US.ISO8859-1/hardware/article.sgml
--- a/head/release/doc/en_US.ISO8859-1/hardware/article.sgml	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/release/doc/en_US.ISO8859-1/hardware/article.sgml	Tue Dec 06 20:26:16 2011 +0200
@@ -17,7 +17,7 @@
 
     <corpauthor>The &os; Documentation Project</corpauthor>
 
-    <pubdate>$FreeBSD: head/release/doc/en_US.ISO8859-1/hardware/article.sgml 227742 2011-11-19 22:14:08Z brueffer $</pubdate>
+    <pubdate>$FreeBSD: head/release/doc/en_US.ISO8859-1/hardware/article.sgml 228028 2011-11-27 16:50:13Z marius $</pubdate>
 
     <copyright>
       <year>2000</year>
@@ -593,6 +593,10 @@
 	</listitem>
 
 	<listitem>
+	  <para>&sun.fire; V245 (support first appeared in 7.3-RELEASE and 8.1-RELEASE)</para>
+	</listitem>
+
+	<listitem>
 	  <para>&sun.fire; V250</para>
 	</listitem>
 
@@ -603,7 +607,8 @@
 
 	<listitem>
 	  <para>&sun.fire; V480 (501-6780 and 501-6790 centerplanes only, for
-	    which support first appeared in 7.3-RELEASE and 8.1-RELEASE)</para>
+	    which support first appeared in 7.3-RELEASE and 8.1-RELEASE,
+	    other centerplanes might work beginning with 8.3-RELEASE and 9.0-RELEASE)</para>
 	</listitem>
 
 	<listitem>
@@ -629,10 +634,6 @@
 	</listitem>
 
 	<listitem>
-	  <para>&sun.fire; V245 (support first appeared in 7.3-RELEASE and 8.1-RELEASE)</para>
-	</listitem>
-
-	<listitem>
 	  <para>&sun.fire; V490 (support first appeared in 7.4-RELEASE and 8.1-RELEASE,
 	    non-mixed &ultrasparc; IV/IV+ CPU-configurations only)</para>
 	</listitem>
@@ -750,8 +751,6 @@
 
       &hwlist.aic;
 
-      &hwlist.amd;
-
       &hwlist.amr;
 
       &hwlist.arcmsr;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/rescue/rescue/Makefile
--- a/head/rescue/rescue/Makefile	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/rescue/rescue/Makefile	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-#$FreeBSD: head/rescue/rescue/Makefile 227531 2011-11-15 16:20:39Z des $
+#$FreeBSD: head/rescue/rescue/Makefile 228112 2011-11-29 03:27:09Z fjoe $
 #	@(#)Makefile	8.1 (Berkeley) 6/2/93
 
 NO_MAN=
@@ -123,9 +123,9 @@
 CRUNCH_LIBS+= -lipx
 .endif
 .if ${MK_ZFS} != "no"
-CRUNCH_LIBS+= -lavl -lnvpair -lpthread -lzfs -luutil -lumem
+CRUNCH_LIBS+= -lavl -lnvpair -lzfs -lpthread -luutil -lumem
 .endif
-CRUNCH_LIBS+= -lgeom -lbsdxml -ljail -lkiconv -lmd -lreadline -lsbuf -lufs -lz
+CRUNCH_LIBS+= -lgeom -lbsdxml -ljail -lkiconv -lmd -lsbuf -lufs -lz
 
 .if ${MACHINE_CPUARCH} == "i386"
 CRUNCH_PROGS_sbin+= bsdlabel sconfig fdisk
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sbin/camcontrol/Makefile
--- a/head/sbin/camcontrol/Makefile	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sbin/camcontrol/Makefile	Tue Dec 06 20:26:16 2011 +0200
@@ -1,7 +1,7 @@
-# $FreeBSD$
+# $FreeBSD: head/sbin/camcontrol/Makefile 227961 2011-11-25 04:03:37Z emaste $
 
 PROG=	camcontrol
-SRCS=	camcontrol.c util.c
+SRCS=	camcontrol.c fwdownload.c util.c
 .if !defined(RELEASE_CRUNCH)
 SRCS+=	modeedit.c
 .else
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sbin/camcontrol/camcontrol.8
--- a/head/sbin/camcontrol/camcontrol.8	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sbin/camcontrol/camcontrol.8	Tue Dec 06 20:26:16 2011 +0200
@@ -25,9 +25,9 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/sbin/camcontrol/camcontrol.8 227961 2011-11-25 04:03:37Z emaste $
 .\"
-.Dd November 30, 2010
+.Dd November 24, 2011
 .Dt CAMCONTROL 8
 .Os
 .Sh NAME
@@ -220,6 +220,13 @@
 .Op device id
 .Op generic args
 .Nm
+.Ic fwdownload
+.Op device id
+.Op generic args
+.Aq Fl f Ar fw_image
+.Op Fl y
+.Op Fl s
+.Nm
 .Ic help
 .Sh DESCRIPTION
 The
@@ -1060,6 +1067,54 @@
 .It Ic sleep
 Put ATA device into SLEEP state. Note that the only way get device out of
 this state may be reset.
+.It Ic fwdownload
+Program firmware of the named SCSI device using the image file provided.
+.Pp
+Current list of supported vendors:
+.Bl -bullet -offset indent -compact
+.It
+HITACHI
+.It
+HP
+.It
+IBM
+.It
+PLEXTOR
+.It
+QUANTUM
+.It
+SEAGATE
+.El
+.Pp
+.Em WARNING! WARNING! WARNING!
+.Pp
+Little testing has been done to make sure that different device models from
+each vendor work correctly with the fwdownload command.
+A vendor name appearing in the supported list means only that firmware of at
+least one device type from that vendor has successfully been programmed with
+the fwdownload command.
+Extra caution should be taken when using this command since there is no
+guarantee it will not break a device from the listed vendors.
+Ensure that you have a recent backup of the data on the device before
+performing a firmware update.
+.Bl -tag -width 11n
+.It Fl f Ar fw_image
+Path to the firmware image file to be downloaded to the specified device.
+.It Fl y
+Do not ask for confirmation.
+.It Fl s
+Run in simulation mode.
+Packet sizes that will be sent are shown, but no actual packet is sent to the
+device.
+No confimation is asked in simulation mode.
+.It Fl v
+Besides showing sense information in case of a failure, the verbose option
+causes
+.Nm
+to output a line for every firmware segment that is sent to the device by the
+fwdownload command
+-- the same as the ones shown in simulation mode.
+.El
 .It Ic help
 Print out verbose usage information.
 .El
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sbin/camcontrol/camcontrol.c
--- a/head/sbin/camcontrol/camcontrol.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sbin/camcontrol/camcontrol.c	Tue Dec 06 20:26:16 2011 +0200
@@ -27,7 +27,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sbin/camcontrol/camcontrol.c 227081 2011-11-04 13:36:02Z ed $");
+__FBSDID("$FreeBSD: head/sbin/camcontrol/camcontrol.c 227961 2011-11-25 04:03:37Z emaste $");
 
 #include <sys/ioctl.h>
 #include <sys/stdint.h>
@@ -86,7 +86,8 @@
 	CAM_CMD_SMP_RG		= 0x00000018,
 	CAM_CMD_SMP_PC		= 0x00000019,
 	CAM_CMD_SMP_PHYLIST	= 0x0000001a,
-	CAM_CMD_SMP_MANINFO	= 0x0000001b
+	CAM_CMD_SMP_MANINFO	= 0x0000001b,
+	CAM_CMD_DOWNLOAD_FW	= 0x0000001c
 } cam_cmdmask;
 
 typedef enum {
@@ -180,6 +181,7 @@
 	{"idle", CAM_CMD_IDLE, CAM_ARG_NONE, "t:"},
 	{"standby", CAM_CMD_STANDBY, CAM_ARG_NONE, "t:"},
 	{"sleep", CAM_CMD_SLEEP, CAM_ARG_NONE, ""},
+	{"fwdownload", CAM_CMD_DOWNLOAD_FW, CAM_ARG_NONE, "f:ys"},
 #endif /* MINIMALISTIC */
 	{"help", CAM_CMD_USAGE, CAM_ARG_NONE, NULL},
 	{"-?", CAM_CMD_USAGE, CAM_ARG_NONE, NULL},
@@ -222,8 +224,6 @@
 			 int timeout, int quiet);
 static int scsistart(struct cam_device *device, int startstop, int loadeject,
 		     int retry_count, int timeout);
-static int scsidoinquiry(struct cam_device *device, int argc, char **argv,
-			 char *combinedopt, int retry_count, int timeout);
 static int scsiinquiry(struct cam_device *device, int retry_count, int timeout);
 static int scsiserial(struct cam_device *device, int retry_count, int timeout);
 static int camxferrate(struct cam_device *device);
@@ -683,7 +683,7 @@
 	return(error);
 }
 
-static int
+int
 scsidoinquiry(struct cam_device *device, int argc, char **argv,
 	      char *combinedopt, int retry_count, int timeout)
 {
@@ -3571,7 +3571,7 @@
 	union ccb *ccb;
 	int c;
 	int ycount = 0, quiet = 0;
-	int error = 0, response = 0, retval = 0;
+	int error = 0, retval = 0;
 	int use_timeout = 10800 * 1000;
 	int immediate = 1;
 	struct format_defect_list_header fh;
@@ -3625,27 +3625,7 @@
 	}
 
 	if (ycount == 0) {
-
-		do {
-			char str[1024];
-
-			fprintf(stdout, "Are you SURE you want to do "
-				"this? (yes/no) ");
-
-			if (fgets(str, sizeof(str), stdin) != NULL) {
-
-				if (strncasecmp(str, "yes", 3) == 0)
-					response = 1;
-				else if (strncasecmp(str, "no", 2) == 0)
-					response = -1;
-				else {
-					fprintf(stdout, "Please answer"
-						" \"yes\" or \"no\"\n");
-				}
-			}
-		} while (response == 0);
-
-		if (response == -1) {
+		if (!get_confirmation()) {
 			error = 1;
 			goto scsiformat_bailout;
 		}
@@ -5693,6 +5673,7 @@
 "        camcontrol idle       [dev_id][generic args][-t time]\n"
 "        camcontrol standby    [dev_id][generic args][-t time]\n"
 "        camcontrol sleep      [dev_id][generic args]\n"
+"        camcontrol fwdownload [dev_id][generic args] <-f fw_image> [-y][-s]\n"
 #endif /* MINIMALISTIC */
 "        camcontrol help\n");
 	if (!verbose)
@@ -5728,6 +5709,7 @@
 "idle        send the ATA IDLE command to the named device\n"
 "standby     send the ATA STANDBY command to the named device\n"
 "sleep       send the ATA SLEEP command to the named device\n"
+"fwdownload  program firmware of the named device with the given image"
 "help        this message\n"
 "Device Identifiers:\n"
 "bus:target        specify the bus and target, lun defaults to 0\n"
@@ -5819,7 +5801,12 @@
 "-w                don't send immediate format command\n"
 "-y                don't ask any questions\n"
 "idle/standby arguments:\n"
-"-t <arg>          number of seconds before respective state.\n");
+"-t <arg>          number of seconds before respective state.\n"
+"fwdownload arguments:\n"
+"-f fw_image       path to firmware image file\n"
+"-y                don't ask any questions\n"
+"-s                run in simulation mode\n"
+"-v                print info for every firmware segment sent to device\n");
 #endif /* MINIMALISTIC */
 }
 
@@ -6135,6 +6122,10 @@
 						 combinedopt, retry_count,
 						 timeout);
 			break;
+		case CAM_CMD_DOWNLOAD_FW:
+			error = fwdownload(cam_dev, argc, argv, combinedopt,
+			    arglist & CAM_ARG_VERBOSE, retry_count, timeout);
+			break;
 #endif /* MINIMALISTIC */
 		case CAM_CMD_USAGE:
 			usage(1);
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sbin/camcontrol/camcontrol.h
--- a/head/sbin/camcontrol/camcontrol.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sbin/camcontrol/camcontrol.h	Tue Dec 06 20:26:16 2011 +0200
@@ -25,7 +25,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD$
+ * $FreeBSD: head/sbin/camcontrol/camcontrol.h 227961 2011-11-25 04:03:37Z emaste $
  */
 
 #ifndef _CAMCONTROL_H
@@ -40,6 +40,8 @@
 	int got;
 };
 
+int fwdownload(struct cam_device *device, int argc, char **argv,
+	       char *combinedopt, int verbose, int retry_count, int timeout);
 void mode_sense(struct cam_device *device, int mode_page, int page_control,
 		int dbd, int retry_count, int timeout, u_int8_t *data,
 		int datalen);
@@ -49,8 +51,11 @@
 	       int edit, int binary, int retry_count, int timeout);
 void mode_list(struct cam_device *device, int page_control, int dbd,
 	       int retry_count, int timeout);
+int scsidoinquiry(struct cam_device *device, int argc, char **argv,
+		  char *combinedopt, int retry_count, int timeout);
 char *cget(void *hook, char *name);
 int iget(void *hook, char *name);
 void arg_put(void *hook, int letter, void *arg, int count, char *name);
+int get_confirmation(void);
 void usage(int verbose);
 #endif /* _CAMCONTROL_H */
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sbin/camcontrol/fwdownload.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/sbin/camcontrol/fwdownload.c	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,389 @@
+/*-
+ * Copyright (c) 2011 Sandvine Incorporated. All rights reserved.
+ * Copyright (c) 2002-2011 Andre Albsmeier <andre at albsmeier.net>
+ * 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, immediately at the beginning of the file.
+ * 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.
+ */
+
+/*
+ * This software is derived from Andre Albsmeier's fwprog.c which contained
+ * the following note:
+ *
+ * Many thanks goes to Marc Frajola <marc at terasolutions.com> from
+ * TeraSolutions for the initial idea and his programme for upgrading
+ * the firmware of I*M DDYS drives.
+ */
+
+/*
+ * BEWARE:
+ *
+ * The fact that you see your favorite vendor listed below does not
+ * imply that your equipment won't break when you use this software
+ * with it. It only means that the firmware of at least one device type
+ * of each vendor listed has been programmed successfully using this code.
+ *
+ * The -s option simulates a download but does nothing apart from that.
+ * It can be used to check what chunk sizes would have been used with the
+ * specified device.
+ */
+
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD: head/sbin/camcontrol/fwdownload.c 228203 2011-12-02 15:47:05Z emaste $");
+
+#include <sys/types.h>
+#include <sys/stat.h>
+
+#include <err.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <cam/scsi/scsi_all.h>
+#include <cam/scsi/scsi_message.h>
+#include <camlib.h>
+
+#include "camcontrol.h"
+
+#define	CMD_TIMEOUT 50000	/* 50 seconds */
+
+typedef enum {
+	VENDOR_HITACHI,
+	VENDOR_HP,
+	VENDOR_IBM,
+	VENDOR_PLEXTOR,
+	VENDOR_QUANTUM,
+	VENDOR_SEAGATE,
+	VENDOR_UNKNOWN
+} fw_vendor_t;
+
+struct fw_vendor {
+	fw_vendor_t type;
+	const char *pattern;
+	int max_pkt_size;
+	u_int8_t cdb_byte2;
+	u_int8_t cdb_byte2_last;
+	int inc_cdb_buffer_id;
+	int inc_cdb_offset;
+};
+
+struct fw_vendor vendors_list[] = {
+	{VENDOR_HITACHI,	"HITACHI",	0x8000, 0x05, 0x05, 1, 0},
+	{VENDOR_HP,		"HP",		0x8000, 0x07, 0x07, 0, 1},
+	{VENDOR_IBM,		"IBM",		0x8000, 0x05, 0x05, 1, 0},
+	{VENDOR_PLEXTOR,	"PLEXTOR",	0x2000, 0x04, 0x05, 0, 1},
+	{VENDOR_QUANTUM,	"QUANTUM",	0x2000, 0x04, 0x05, 0, 1},
+	{VENDOR_SEAGATE,	"SEAGATE",	0x8000, 0x07, 0x07, 0, 1},
+	{VENDOR_UNKNOWN,	NULL,		0x0000, 0x00, 0x00, 0, 0}
+};
+
+static struct fw_vendor *fw_get_vendor(struct cam_device *cam_dev);
+static char	*fw_read_img(char *fw_img_path, struct fw_vendor *vp,
+		    int *num_bytes);
+static int	 fw_download_img(struct cam_device *cam_dev,
+		    struct fw_vendor *vp, char *buf, int img_size,
+		    int sim_mode, int verbose, int retry_count, int timeout);
+
+/*
+ * Find entry in vendors list that belongs to
+ * the vendor of given cam device.
+ */
+static struct fw_vendor *
+fw_get_vendor(struct cam_device *cam_dev)
+{
+	char vendor[SID_VENDOR_SIZE + 1];
+	struct fw_vendor *vp;
+
+	if (cam_dev == NULL)
+		return (NULL);
+	cam_strvis((u_char *)vendor, (u_char *)cam_dev->inq_data.vendor,
+	    sizeof(cam_dev->inq_data.vendor), sizeof(vendor));
+	for (vp = vendors_list; vp->pattern != NULL; vp++) {
+		if (!cam_strmatch((const u_char *)vendor,
+		    (const u_char *)vp->pattern, strlen(vendor)))
+			break;
+	}
+	return (vp);
+}
+
+/*
+ * Allocate a buffer and read fw image file into it
+ * from given path. Number of bytes read is stored
+ * in num_bytes.
+ */
+static char *
+fw_read_img(char *fw_img_path, struct fw_vendor *vp, int *num_bytes)
+{
+	int fd;
+	struct stat stbuf;
+	char *buf;
+	off_t img_size;
+	int skip_bytes = 0;
+
+	if ((fd = open(fw_img_path, O_RDONLY)) < 0) {
+		warn("Could not open image file %s", fw_img_path);
+		return (NULL);
+	}
+	if (fstat(fd, &stbuf) < 0) {
+		warn("Could not stat image file %s", fw_img_path);
+		goto bailout1;
+	}
+	if ((img_size = stbuf.st_size) == 0) {
+		warnx("Zero length image file %s", fw_img_path);
+		goto bailout1;
+	}
+	if ((buf = malloc(img_size)) == NULL) {
+		warnx("Could not allocate buffer to read image file %s",
+		    fw_img_path);
+		goto bailout1;
+	}
+	/* Skip headers if applicable. */
+	switch (vp->type) {
+	case VENDOR_SEAGATE:
+		if (read(fd, buf, 16) != 16) {
+			warn("Could not read image file %s", fw_img_path);
+			goto bailout;
+		}
+		if (lseek(fd, 0, SEEK_SET) == -1) {
+			warn("Unable to lseek");
+			goto bailout;
+		}
+		if ((strncmp(buf, "SEAGATE,SEAGATE ", 16) == 0) ||
+		    (img_size % 512 == 80))
+			skip_bytes = 80;
+		break;
+	default:
+		break;
+	}
+	if (skip_bytes != 0) {
+		fprintf(stdout, "Skipping %d byte header.\n", skip_bytes);
+		if (lseek(fd, skip_bytes, SEEK_SET) == -1) {
+			warn("Could not lseek");
+			goto bailout;
+		}
+		img_size -= skip_bytes;
+	}
+	/* Read image into a buffer. */
+	if (read(fd, buf, img_size) != img_size) {
+		warn("Could not read image file %s", fw_img_path);
+		goto bailout;
+	}
+	*num_bytes = img_size;
+	return (buf);
+bailout:
+	free(buf);
+bailout1:
+	close(fd);
+	*num_bytes = 0;
+	return (NULL);
+}
+
+/* 
+ * Download firmware stored in buf to cam_dev. If simulation mode
+ * is enabled, only show what packet sizes would be sent to the 
+ * device but do not sent any actual packets
+ */
+static int
+fw_download_img(struct cam_device *cam_dev, struct fw_vendor *vp,
+    char *buf, int img_size, int sim_mode, int verbose, int retry_count,
+    int timeout)
+{
+	struct scsi_write_buffer cdb;
+	union ccb *ccb;
+	int pkt_count = 0;
+	u_int32_t pkt_size = 0;
+	char *pkt_ptr = buf;
+	u_int32_t offset;
+	int last_pkt = 0;
+
+	if ((ccb = cam_getccb(cam_dev)) == NULL) {
+		warnx("Could not allocate CCB");
+		return (1);
+	}
+	scsi_test_unit_ready(&ccb->csio, 0, NULL, MSG_SIMPLE_Q_TAG,
+	    SSD_FULL_SIZE, 5000);
+	/* Disable freezing the device queue. */
+	ccb->ccb_h.flags |= CAM_DEV_QFRZDIS;
+	if (cam_send_ccb(cam_dev, ccb) < 0) {
+		warnx("Error sending test unit ready");
+		if (verbose)
+			cam_error_print(cam_dev, ccb, CAM_ESF_ALL,
+			    CAM_EPF_ALL, stderr);
+		cam_freeccb(ccb);
+		return(1);
+	}
+	if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
+		warnx("Device is not ready");
+		if (verbose)
+			cam_error_print(cam_dev, ccb, CAM_ESF_ALL,
+			    CAM_EPF_ALL, stderr);
+		cam_freeccb(ccb);
+		return (1);
+	}
+	pkt_size = vp->max_pkt_size;
+	if (verbose || sim_mode) {
+		fprintf(stdout,
+		    "--------------------------------------------------\n");
+		fprintf(stdout,
+		    "PktNo.	PktSize	       BytesRemaining	LastPkt\n");
+		fprintf(stdout,
+		    "--------------------------------------------------\n");
+	}
+	/* Download single fw packets. */
+	do {
+		if (img_size <= vp->max_pkt_size) {
+			last_pkt = 1;
+			pkt_size = img_size;
+		}
+		if (verbose || sim_mode)
+			fprintf(stdout, "%3u   %5u (0x%05X)   %7u (0x%06X)   "
+			    "%d\n", pkt_count, pkt_size, pkt_size,
+			    img_size - pkt_size, img_size - pkt_size,
+			    last_pkt);
+		bzero(&cdb, sizeof(cdb));
+		cdb.opcode  = WRITE_BUFFER;
+		cdb.control = 0;
+		/* Parameter list length. */
+		scsi_ulto3b(pkt_size, &cdb.length[0]);
+		offset = vp->inc_cdb_offset ? (pkt_ptr - buf) : 0;
+		scsi_ulto3b(offset, &cdb.offset[0]);
+		cdb.byte2 = last_pkt ? vp->cdb_byte2_last : vp->cdb_byte2;
+		cdb.buffer_id = vp->inc_cdb_buffer_id ? pkt_count : 0;
+		/* Zero out payload of ccb union after ccb header. */
+		bzero((u_char *)ccb + sizeof(struct ccb_hdr),
+		    sizeof(struct ccb_scsiio) - sizeof(struct ccb_hdr));
+		/* Copy previously constructed cdb into ccb_scsiio struct. */
+		bcopy(&cdb, &ccb->csio.cdb_io.cdb_bytes[0],
+		    sizeof(struct scsi_write_buffer));
+		/* Fill rest of ccb_scsiio struct. */
+		if (!sim_mode) {
+			cam_fill_csio(&ccb->csio,		/* ccb_scsiio	*/
+			    retry_count,			/* retries	*/
+			    NULL,				/* cbfcnp	*/
+			    CAM_DIR_OUT | CAM_DEV_QFRZDIS,	/* flags	*/
+			    CAM_TAG_ACTION_NONE,		/* tag_action	*/
+			    (u_char *)pkt_ptr,			/* data_ptr	*/
+			    pkt_size,				/* dxfer_len	*/
+			    SSD_FULL_SIZE,			/* sense_len	*/
+			    sizeof(struct scsi_write_buffer),	/* cdb_len	*/
+			    timeout ? timeout : CMD_TIMEOUT);	/* timeout	*/
+			/* Execute the command. */
+			if (cam_send_ccb(cam_dev, ccb) < 0) {
+				warnx("Error writing image to device");
+				if (verbose)
+					cam_error_print(cam_dev, ccb, CAM_ESF_ALL,
+					    CAM_EPF_ALL, stderr);
+				goto bailout;
+			}
+		}
+		/* Prepare next round. */
+		pkt_count++;
+		pkt_ptr += pkt_size;
+		img_size -= pkt_size;
+	} while(!last_pkt);
+	if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
+		if (verbose)
+			cam_error_print(cam_dev, ccb, CAM_ESF_ALL,
+			    CAM_EPF_ALL, stderr);
+		goto bailout;
+	}
+	cam_freeccb(ccb);
+	return (0);
+bailout:
+	cam_freeccb(ccb);
+	return (1);
+}
+
+int
+fwdownload(struct cam_device *device, int argc, char **argv,
+    char *combinedopt, int verbose, int retry_count, int timeout)
+{
+	struct fw_vendor *vp;
+	char *fw_img_path = NULL;
+	char *buf;
+	int img_size;
+	int c;
+	int sim_mode = 0;
+	int confirmed = 0;
+
+	while ((c = getopt(argc, argv, combinedopt)) != -1) {
+		switch (c) {
+		case 's':
+			sim_mode = 1;
+			confirmed = 1;
+			break;
+		case 'f':
+			fw_img_path = optarg;
+			break;
+		case 'y':
+			confirmed = 1;
+			break;
+		default:
+			break;
+		}
+	}
+
+	if (fw_img_path == NULL)
+		errx(1,
+		    "you must specify a firmware image file using -f option");
+
+	vp = fw_get_vendor(device);
+	if (vp == NULL || vp->type == VENDOR_UNKNOWN)
+		errx(1, "Unsupported device");
+
+	buf = fw_read_img(fw_img_path, vp, &img_size);
+	if (buf == NULL)
+		goto fail;
+
+	if (!confirmed) {
+		fprintf(stdout, "You are about to download firmware image (%s)"
+		    " into the following device:\n",
+		    fw_img_path);
+		if (scsidoinquiry(device, argc, argv, combinedopt, 0,
+		    5000) != 0) {
+			warnx("Error sending inquiry");
+			goto fail;
+		}
+		fprintf(stdout, "\nIt may damage your drive. ");
+		if (!get_confirmation())
+			goto fail;
+	}
+	if (sim_mode)
+		fprintf(stdout, "Running in simulation mode\n");
+
+	if (fw_download_img(device, vp, buf, img_size, sim_mode, verbose,
+	    retry_count, timeout) != 0) {
+		fprintf(stderr, "Firmware download failed\n");
+		goto fail;
+	} else 
+		fprintf(stdout, "Firmware download successful\n");
+
+	free(buf);
+	return (0);
+fail:
+	if (buf != NULL)
+		free(buf);
+	return (1);
+}
+
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sbin/camcontrol/util.c
--- a/head/sbin/camcontrol/util.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sbin/camcontrol/util.c	Tue Dec 06 20:26:16 2011 +0200
@@ -44,7 +44,7 @@
  * from: scsi.c,v 1.17 1998/01/12 07:57:57 charnier Exp $";
  */
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/sbin/camcontrol/util.c 227963 2011-11-25 07:11:02Z delphij $");
 
 #include <sys/stdint.h>
 #include <sys/types.h>
@@ -154,3 +154,31 @@
 	if (verbose)
 		putchar('\n');
 }
+
+/*
+ * Get confirmation from user
+ * Return values:
+ *    1: confirmed
+ *    0: unconfirmed
+ */
+int
+get_confirmation(void)
+{
+	char str[1024];
+	int response = -1;
+
+	do {
+		fprintf(stdout, "Are you SURE you want to do this? (yes/no) ");
+		if (fgets(str, sizeof(str), stdin) != NULL) {
+			if (strncasecmp(str, "yes", 3) == 0)
+				response = 1;
+			else if (strncasecmp(str, "no", 2) == 0)
+				response = 0;
+			else
+				fprintf(stdout,
+				    "Please answer \"yes\" or \"no\"\n");
+		} else
+			response = 0;
+	} while (response == -1);
+	return (response);
+}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sbin/dhclient/clparse.c
--- a/head/sbin/dhclient/clparse.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sbin/dhclient/clparse.c	Tue Dec 06 20:26:16 2011 +0200
@@ -41,7 +41,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/sbin/dhclient/clparse.c 228259 2011-12-04 14:44:31Z dumbbell $");
 
 #include "dhcpd.h"
 #include "dhctoken.h"
@@ -100,6 +100,8 @@
 	    DHO_DOMAIN_NAME_SERVERS;
 	top_level_config.requested_options
 	    [top_level_config.requested_option_count++] = DHO_HOST_NAME;
+	top_level_config.requested_options
+	    [top_level_config.requested_option_count++] = DHO_DOMAIN_SEARCH;
 
 	if ((cfile = fopen(path_dhclient_conf, "r")) != NULL) {
 		do {
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sbin/dhclient/dhclient-script
--- a/head/sbin/dhclient/dhclient-script	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sbin/dhclient/dhclient-script	Tue Dec 06 20:26:16 2011 +0200
@@ -1,7 +1,7 @@
 #!/bin/sh
 #
 # $OpenBSD: dhclient-script,v 1.6 2004/05/06 18:22:41 claudio Exp $
-# $FreeBSD$
+# $FreeBSD: head/sbin/dhclient/dhclient-script 228259 2011-12-04 14:44:31Z dumbbell $
 #
 # Copyright (c) 2003 Kenneth R Westerback <krw at openbsd.org>
 #
@@ -201,7 +201,9 @@
 	local tmpres=/var/run/resolv.conf.${interface}
 	rm -f $tmpres
 
-	if [ -n "$new_domain_name" ]; then
+	if [ -n "$new_domain_search" ]; then
+		echo "search $new_domain_search" >>$tmpres
+	elif [ -n "$new_domain_name" ]; then
 		echo "search $new_domain_name" >>$tmpres
 	fi
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sbin/dhclient/dhclient.c
--- a/head/sbin/dhclient/dhclient.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sbin/dhclient/dhclient.c	Tue Dec 06 20:26:16 2011 +0200
@@ -54,7 +54,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sbin/dhclient/dhclient.c 226345 2011-10-13 17:20:45Z des $");
+__FBSDID("$FreeBSD: head/sbin/dhclient/dhclient.c 228259 2011-12-04 14:44:31Z dumbbell $");
 
 #include "dhcpd.h"
 #include "privsep.h"
@@ -2401,6 +2401,7 @@
 		}
 		return (1);
 	case DHO_DOMAIN_NAME:
+	case DHO_DOMAIN_SEARCH:
 		if (!res_hnok(sbuf)) {
 			if (!check_search(sbuf)) {
 				warning("Bogus domain search list %d: %s (%s)",
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sbin/dhclient/dhcp-options.5
--- a/head/sbin/dhclient/dhcp-options.5	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sbin/dhclient/dhcp-options.5	Tue Dec 06 20:26:16 2011 +0200
@@ -36,7 +36,7 @@
 .\" see ``http://www.isc.org/isc''.  To learn more about Vixie
 .\" Enterprises, see ``http://www.vix.com''.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/sbin/dhclient/dhcp-options.5 228259 2011-12-04 14:44:31Z dumbbell $
 .\"
 .Dd January 1, 1995
 .Dt DHCP-OPTIONS 5
@@ -265,6 +265,10 @@
 .It Ic option domain-name Ar string ;
 This option specifies the domain name that the client should use when
 resolving hostnames via the Domain Name System.
+.It Ic option domain-search Ar string ;
+This option specifies a list of domain names that the client should use
+when resolving hostnames via the Domain Name System. This option is
+defined in RFC 3397.
 .It Ic option swap-server Ar ip-address ;
 This specifies the IP address of the client's swap server.
 .It Ic option root-path Ar string ;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sbin/dhclient/dhcp.h
--- a/head/sbin/dhclient/dhcp.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sbin/dhclient/dhcp.h	Tue Dec 06 20:26:16 2011 +0200
@@ -1,5 +1,5 @@
 /*	$OpenBSD: dhcp.h,v 1.5 2004/05/04 15:49:49 deraadt Exp $	*/
-/*	$FreeBSD$	*/
+/*	$FreeBSD: head/sbin/dhclient/dhcp.h 228259 2011-12-04 14:44:31Z dumbbell $	*/
 
 /* Protocol structures... */
 
@@ -169,6 +169,7 @@
 #define	DHO_STREETTALK_SERVER		75
 #define	DHO_STREETTALK_DA_SERVER	76
 #define DHO_DHCP_USER_CLASS_ID		77
+#define	DHO_DOMAIN_SEARCH		119
 #define DHO_CLASSLESS_ROUTES		121
 #define DHO_END				255
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sbin/dhclient/options.c
--- a/head/sbin/dhclient/options.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sbin/dhclient/options.c	Tue Dec 06 20:26:16 2011 +0200
@@ -41,7 +41,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/sbin/dhclient/options.c 228259 2011-12-04 14:44:31Z dumbbell $");
 
 #include <ctype.h>
 
@@ -55,6 +55,10 @@
 void	parse_option_buffer(struct packet *, unsigned char *, int);
 int	store_options(unsigned char *, int, struct tree_cache **,
 	    unsigned char *, int, int, int, int);
+void	expand_domain_search(struct packet *packet);
+int	find_search_domain_name_len(struct option_data *option, int *offset);
+void	expand_search_domain_name(struct option_data *option, int *offset,
+	    unsigned char **domain_search);
 
 
 /*
@@ -94,6 +98,11 @@
 			    (unsigned char *)packet->raw->sname,
 			    sizeof(packet->raw->sname));
 	}
+
+	/* Expand DHCP Domain Search option. */
+	if (packet->options_valid) {
+		expand_domain_search(packet);
+	}
 }
 
 /*
@@ -194,6 +203,163 @@
 }
 
 /*
+ * Expand DHCP Domain Search option. The value of this option is
+ * encoded like DNS' list of labels. See:
+ *   RFC 3397
+ *   RFC 1035
+ */
+void
+expand_domain_search(struct packet *packet)
+{
+	int offset, expanded_len;
+	struct option_data *option;
+	unsigned char *domain_search, *cursor;
+
+	if (packet->options[DHO_DOMAIN_SEARCH].data == NULL)
+		return;
+
+	option = &packet->options[DHO_DOMAIN_SEARCH];
+
+	/* Compute final expanded length. */
+	expanded_len = 0;
+	offset = 0;
+	while (offset < option->len) {
+		/* We add 1 for the space between domain names. */
+		expanded_len +=
+		    find_search_domain_name_len(option, &offset) + 1;
+	}
+	if (expanded_len > 0)
+		/* Remove 1 for the superfluous trailing space. */
+		--expanded_len;
+
+	domain_search = malloc(expanded_len + 1);
+	if (domain_search == NULL)
+		error("Can't allocate storage for expanded domain-search\n");
+
+	offset = 0;
+	cursor = domain_search;
+	while (offset < option->len) {
+		expand_search_domain_name(option, &offset, &cursor);
+		cursor[0] = ' ';
+		cursor++;
+	}
+	domain_search[expanded_len] = '\0';
+
+	free(option->data);
+	option->len = expanded_len;
+	option->data = domain_search;
+}
+
+int
+find_search_domain_name_len(struct option_data *option, int *offset)
+{
+	int domain_name_len, i, label_len, pointer, pointed_len;
+
+	domain_name_len = 0;
+
+	i = *offset;
+	while (i < option->len) {
+		label_len = option->data[i];
+		if (label_len == 0) {
+			/*
+			 * A zero-length label marks the end of this
+			 * domain name.
+			 */
+			*offset = i + 1;
+			return (domain_name_len);
+		} else if (label_len & 0xC0) {
+			/* This is a pointer to another list of labels. */
+			if (i + 1 >= option->len) {
+				/* The pointer is truncated. */
+				error("Truncated pointer in DHCP Domain "
+				    "Search option.");
+			}
+
+			pointer = ((label_len & ~(0xC0)) << 8) +
+			    option->data[i + 1];
+			if (pointer >= *offset) {
+				/*
+				 * The pointer must indicates a prior
+				 * occurance.
+				 */
+				error("Invalid forward pointer in DHCP Domain "
+				    "Search option compression.");
+			}
+
+			pointed_len = find_search_domain_name_len(option,
+			    &pointer);
+			domain_name_len += pointed_len;
+
+			*offset = i + 2;
+			return (domain_name_len);
+		}
+
+		if (i + label_len >= option->len) {
+			error("Truncated label in DHCP Domain Search option.");
+		}
+
+		/*
+		 * Update the domain name length with the length of the
+		 * current label, plus a trailing dot ('.').
+		 */
+		domain_name_len += label_len + 1;
+
+		/* Move cursor. */
+		i += label_len + 1;
+	}
+
+	error("Truncated DHCP Domain Search option.");
+
+	return (0);
+}
+
+void
+expand_search_domain_name(struct option_data *option, int *offset,
+    unsigned char **domain_search)
+{
+	int i, label_len, pointer;
+	unsigned char *cursor;
+
+	/*
+	 * This is the same loop than the function above
+	 * (find_search_domain_name_len). Therefore, we remove checks,
+	 * they're already done. Here, we just make the copy.
+	 */
+	i = *offset;
+	cursor = *domain_search;
+	while (i < option->len) {
+		label_len = option->data[i];
+		if (label_len == 0) {
+			/*
+			 * A zero-length label marks the end of this
+			 * domain name.
+			 */
+			*offset = i + 1;
+			*domain_search = cursor;
+			return;
+		} else if (label_len & 0xC0) {
+			/* This is a pointer to another list of labels. */
+			pointer = ((label_len & ~(0xC0)) << 8) +
+			    option->data[i + 1];
+
+			expand_search_domain_name(option, &pointer, &cursor);
+
+			*offset = i + 2;
+			*domain_search = cursor;
+			return;
+		}
+
+		/* Copy the label found. */
+		memcpy(cursor, option->data + i + 1, label_len);
+		cursor[label_len] = '.';
+
+		/* Move cursor. */
+		i += label_len + 1;
+		cursor += label_len + 1;
+	}
+}
+
+/*
  * cons options into a big buffer, and then split them out into the
  * three separate buffers if needed.  This allows us to cons up a set of
  * vendor options using the same routine.
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sbin/dhclient/tables.c
--- a/head/sbin/dhclient/tables.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sbin/dhclient/tables.c	Tue Dec 06 20:26:16 2011 +0200
@@ -41,7 +41,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/sbin/dhclient/tables.c 228259 2011-12-04 14:44:31Z dumbbell $");
 
 #include "dhcpd.h"
 
@@ -184,7 +184,7 @@
 	{ "option-116", "X",				&dhcp_universe, 116 },
 	{ "option-117", "X",				&dhcp_universe, 117 },
 	{ "option-118", "X",				&dhcp_universe, 118 },
-	{ "option-119", "X",				&dhcp_universe, 119 },
+	{ "domain-search", "t",				&dhcp_universe, 119 },
 	{ "option-120", "X",				&dhcp_universe, 120 },
 	{ "classless-routes", "BA",			&dhcp_universe, 121 },
 	{ "option-122", "X",				&dhcp_universe, 122 },
@@ -400,12 +400,13 @@
 	DHO_IRC_SERVER,
 	DHO_STREETTALK_SERVER,
 	DHO_STREETTALK_DA_SERVER,
+	DHO_DOMAIN_SEARCH,
 
 	/* Presently-undefined options... */
 	62, 63, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91,
 	92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105,
 	106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117,
-	118, 119, 120, 122, 123, 124, 125, 126, 127, 128, 129, 130,
+	118,      120, 122, 123, 124, 125, 126, 127, 128, 129, 130,
 	131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142,
 	143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154,
 	155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166,
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sbin/switchctl/switchctl.c
--- a/head/sbin/switchctl/switchctl.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sbin/switchctl/switchctl.c	Tue Dec 06 20:26:16 2011 +0200
@@ -26,6 +26,49 @@
 int	set_port(struct info *, int fd, int argc, char **argv);
 int	get_reg(struct info *info, int fd, int argc, char **argv);
 int	set_reg(struct info *info, int fd, int argc, char **argv);
+#if 0
+		    case 'I': /* IngressCheck */
+		    case 'Q': /* Q-in-Q */
+		    case 'L': /* LAN */
+		    case 'W': /* WAN */
+		    case 'T': /* Global Tagged */
+		    case 'U': /* Global Untagged */
+
+
+get reg 0x100
+set reg 0x100 0x1230 
+get port 7
+set port 7 pvid 17 flags WAN Q-in-Q IngressCheck
+set vlan 7 add port 3 t/u/f
+set vlan 7 del port 3
+get vlan 7
+
+
+set	 - can be placed anywhere before value
+get/show - ------- << --------
+
+reg	N	+ N
+----------------+------------------------------------
+port	NRANGE	+ pvid	N
+----------------+------------------------------------
+		+ flags	WAN
+		+	Q-in-Q
+		+	IngressCheck
+----------------+------------------------------------
+vlan	N	+ vid	N
+		+ add	port	NRANGE	tagged
+		+			untagged
+		+			forbidden
+		+ del	port	NRANGE
+
+struct sm {
+	int		action;	/* get - 0, set - 1 */
+	uint32_t	reg;
+	uint32_t	ports;	/* ports bitmap, so "add port" will OR this value, "delete port" will MASK it */
+	uint16_t	vlan;
+} *sm_p;
+
+#endif
 
 int
 main(int argc, char **argv)
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sbin/sysctl/sysctl.c
--- a/head/sbin/sysctl/sysctl.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sbin/sysctl/sysctl.c	Tue Dec 06 20:26:16 2011 +0200
@@ -38,7 +38,7 @@
 static char sccsid[] = "@(#)from: sysctl.c	8.1 (Berkeley) 6/6/93";
 #endif
 static const char rcsid[] =
-  "$FreeBSD$";
+  "$FreeBSD: head/sbin/sysctl/sysctl.c 228181 2011-12-01 15:01:23Z jhb $";
 #endif /* not lint */
 
 #include <sys/param.h>
@@ -201,7 +201,7 @@
 	if (oidfmt(mib, len, fmt, &kind))
 		err(1, "couldn't find format of oid '%s'", bufp);
 
-	if (newval == NULL) {
+	if (newval == NULL || dflag) {
 		if ((kind & CTLTYPE) == CTLTYPE_NODE) {
 			if (dflag) {
 				i = show_var(mib, len);
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/secure/lib/libcrypto/Makefile
--- a/head/secure/lib/libcrypto/Makefile	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/secure/lib/libcrypto/Makefile	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-# $FreeBSD$
+# $FreeBSD: head/secure/lib/libcrypto/Makefile 228307 2011-12-06 11:28:17Z kib $
 
 SHLIBDIR?=	/lib
 SUBDIR=		engines
@@ -7,6 +7,7 @@
 
 LIB=		crypto
 SHLIB_MAJOR=	6
+ALLOW_SHARED_TEXTREL=
 
 NO_LINT=
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/share/man/man4/Makefile
--- a/head/share/man/man4/Makefile	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/share/man/man4/Makefile	Tue Dec 06 20:26:16 2011 +0200
@@ -1,5 +1,5 @@
 #	@(#)Makefile	8.1 (Berkeley) 6/18/93
-# $FreeBSD: head/share/man/man4/Makefile 227614 2011-11-17 12:17:39Z luigi $
+# $FreeBSD: head/share/man/man4/Makefile 228174 2011-12-01 07:41:30Z lstewart $
 
 MAN=	aac.4 \
 	acpi.4 \
@@ -32,7 +32,6 @@
 	ale.4 \
 	alpm.4 \
 	altq.4 \
-	amd.4 \
 	amdpm.4 \
 	${_amdsbwd.4} \
 	${_amdsmb.4} \
@@ -68,6 +67,7 @@
 	bt.4 \
 	bwi.4 \
 	bwn.4 \
+	capsicum.4 \
 	cardbus.4 \
 	carp.4 \
 	cas.4 \
@@ -123,6 +123,7 @@
 	fdc.4 \
 	fdt.4 \
 	fdtbus.4 \
+	ffclock.4 \
 	firewire.4 \
 	fpa.4 \
 	fwe.4 \
@@ -378,7 +379,7 @@
 	send.4 \
 	ses.4 \
 	sf.4 \
-	sfxge.4 \
+	${_sfxge.4} \
 	sge.4 \
 	si.4 \
 	siba.4 \
@@ -718,6 +719,7 @@
 
 .if ${MACHINE_CPUARCH} == "amd64"
 _qlxgb.4=	qlxgb.4
+_sfxge.4=	sfxge.4
 .endif
 
 .if ${MACHINE_CPUARCH} == "powerpc"
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/share/man/man4/ahci.4
--- a/head/share/man/man4/ahci.4	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/share/man/man4/ahci.4	Tue Dec 06 20:26:16 2011 +0200
@@ -22,9 +22,9 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/share/man/man4/ahci.4 222039 2011-05-17 22:07:45Z mav $
+.\" $FreeBSD: head/share/man/man4/ahci.4 228305 2011-12-06 09:12:11Z mav $
 .\"
-.Dd May 17, 2011
+.Dd December 6, 2011
 .Dt AHCI 4
 .Os
 .Sh NAME
@@ -90,12 +90,15 @@
 Because of artificial entering latency, performance degradation in modes
 4 and 5 is much smaller then in modes 2 and 3.
 .Pp
-Note that interface Power Management is not compatible with
-device presence detection.
-A manual bus reset is needed on device hot-plug.
+Note that interface Power Management complicates device presence detection.
+A manual bus reset/rescan may be needed after device hot-plug, unless hardware
+implements Cold Presence Detection.
 .It Va hint.ahcich. Ns Ar X Ns Va .sata_rev
 setting to nonzero value limits maximum SATA revision (speed).
 Values 1, 2 and 3 are respectively 1.5, 3 and 6Gbps.
+.It Va hw.ahci.force
+setting to nonzero value forces driver attach to some known AHCI-capable
+chips even if they are configured for legacy IDE emulation. Default is 1.
 .El
 .Sh DESCRIPTION
 This driver provides the
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/share/man/man4/amd.4
--- a/head/share/man/man4/amd.4	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,78 +0,0 @@
-.\"
-.\" Copyright (c) 1999 Alexey Zelkin
-.\" 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. 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 August 8, 2004
-.Dt AMD 4
-.Os
-.Sh NAME
-.Nm amd
-.Nd amd53c974 PCI SCSI 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 scbus"
-.Cd "device amd"
-.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
-amd_load="YES"
-.Ed
-.Sh DESCRIPTION
-The
-.Nm
-driver provides support for the
-.Tn amd53c974
-based SCSI cards.
-.Sh HARDWARE
-Controllers supported by the
-.Nm
-driver include:
-.Pp
-.Bl -bullet -compact
-.It
-MELCO IFC-DP (PC-98)
-.It
-Tekram DC390
-.It
-Tekram DC390T
-.El
-.Sh SEE ALSO
-.Xr cd 4 ,
-.Xr ch 4 ,
-.Xr da 4 ,
-.Xr intro 4 ,
-.Xr sa 4 ,
-.Xr scsi 4
-.Sh AUTHORS
-The
-.Nm
-driver was written and submitted to
-.Fx
-by Tekram, Inc.
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/share/man/man4/bge.4
--- a/head/share/man/man4/bge.4	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/share/man/man4/bge.4	Tue Dec 06 20:26:16 2011 +0200
@@ -29,9 +29,9 @@
 .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 .\" THE POSSIBILITY OF SUCH DAMAGE.
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/share/man/man4/bge.4 228205 2011-12-02 19:01:26Z yongari $
 .\"
-.Dd November 23, 2010
+.Dd December 2, 2011
 .Dt BGE 4
 .Os
 .Sh NAME
@@ -82,9 +82,9 @@
 which support autonegotiation of 10, 100 and 1000Mbps modes in
 full or half duplex.
 .Pp
-The BCM5700, BCM5701, BCM5702, BCM5703, BCM5704 and BCM5717 also support
-jumbo frames, which can be configured
-via the interface MTU setting.
+The BCM5700, BCM5701, BCM5702, BCM5703, BCM5704, BCM5714, BCM5717, BCM5719,
+BCM5720, BCM5780 and BCM57765 also support jumbo frames, which can be
+configured via the interface MTU setting.
 Selecting an MTU larger than 1500 bytes with the
 .Xr ifconfig 8
 utility configures the adapter to receive and transmit jumbo frames.
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/share/man/man4/capsicum.4
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/share/man/man4/capsicum.4	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,120 @@
+.\"
+.\" Copyright (c) 2011 Robert N. M. Watson
+.\" Copyright (c) 2011 Jonathan Anderson
+.\" 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: head/share/man/man4/capsicum.4 228039 2011-11-27 19:44:15Z rwatson $
+.\"
+.Dd September 20, 2011
+.Dt CAPSICUM 4
+.Os
+.Sh NAME
+.Nm Capsicum
+.Nd lightweight OS capability and sandbox framework
+.Sh SYNOPSIS
+.Cd "options CAPABILITY_MODE"
+.Cd "options CAPABILITIES"
+.Cd "options PROCDESC"
+.Sh DESCRIPTION
+.Nm
+is a lightweight OS capability and sandbox framework implementing a hybrid
+capability system model.
+.Nm
+can be used for application and library compartmentalisation, the
+decomposition of larger bodies of software into isolated (sandboxed)
+components in order to implement security policies and limit the impact of
+software vulnerabilities.
+.Pp
+.Nm
+provides two core kernel primitives:
+.Bl -tag -width indent
+.It capability mode
+A process mode, entered by invoking
+.Xr cap_enter 2 ,
+in which access to global OS namespaces (such as the file system and PID
+namespaces) is restricted; only explicitly delegated rights, referenced by
+memory mappings or file descriptors, may be used.
+Once set, the flag is inherited by future children proceses, and may not be
+cleared.
+.It capabilities
+File descriptors that wrap other file descriptors, masking operations that can
+be called on them; for example, a file descriptor returned by
+.Xr open 2
+may be refined using
+.Xr cap_new 2
+so that only
+.Xr read 2
+and
+.Xr write 2
+can be called, but not
+.Xr fchmod 2 .
+.El
+.Pp
+In some cases,
+.Nm
+requires use of alternatives to traditional POSIX APIs in order to name
+objects using capabilities rather than global namespaces:
+.Bl -tag -width indent
+.It process descriptors
+File descriptors representing processes, allowing parent processes to manage
+child processes without requiring access to the PID namespace.
+.It anonymous shared memory
+An extension to the POSIX shared memory API to support anonymous swap objects
+associated with file descriptors.
+.El
+.Sh SEE ALSO
+.Xr cap_enter 2 ,
+.Xr cap_getmode 2 ,
+.Xr cap_getrights 2 ,
+.Xr cap_new 2 ,
+.Xr fchmod 2 ,
+.Xr open 2 ,
+.Xr pdfork 2 ,
+.Xr pdgetpid 2 ,
+.Xr pdkill 2 ,
+.Xr pdwait4 2 ,
+.Xr read 2 ,
+.Xr shm_open 2 ,
+.Xr write 2
+.Sh HISTORY
+.Nm
+first appeared in
+.Fx 9.0 ,
+and was developed at the University of Cambridge.
+.Sh AUTHORS
+.Nm
+was developed by
+.An -nosplit
+.An "Robert Watson" Aq rwatson at FreeBSD.org
+and
+.An "Jonathan Anderson" Aq jonathan at FreeBSD.org
+at the University of Cambridge, and
+.An "Ben Laurie" Aq benl at FreeBSD.org
+and
+.An "Kris Kennaway" Aq kris at FreeBSD.org
+at Google, Inc.
+.Sh BUGS
+.Nm
+is considered experimental in
+.Fx .
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/share/man/man4/ffclock.4
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/share/man/man4/ffclock.4	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,128 @@
+.\" Copyright (c) 2011 The University of Melbourne
+.\" All rights reserved.
+.\"
+.\" This documentation was written by Julien Ridoux at the University of
+.\" Melbourne 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: head/share/man/man4/ffclock.4 228174 2011-12-01 07:41:30Z lstewart $
+.\"
+.Dd December 1, 2011
+.Dt FFCLOCK 4
+.Os
+.Sh NAME
+.Nm FFCLOCK
+.Nd Feed-forward system clock
+.Sh SYNOPSIS
+.Cd options FFCLOCK
+.Sh DESCRIPTION
+The
+.Xr ntpd 8
+daemon has been the dominant solution for system clock synchronisation for many
+years, which has in turn influenced the design of the system clock.
+The ntpd daemon implements a feedback control algorithm which has been
+demonstrated to perform poorly in common use cases.
+.Pp
+Feed-forward clock synchronisation algorithms implemented by an appropriate
+daemon, in concert with the
+.Nm
+kernel support, have been shown to provide highly robust and accurate clock
+synchronisation.
+In addition to time keeping, the
+.Nm
+kernel mechanism provides new timestamping capabilities and the ability to
+use specialised clocks.
+Feed-forward synchronisation is also very well suited for virtualised
+environments, reducing the overhead of timekeeping in guests and ensuring
+continued smooth operation of the system clock during guest live migration.
+.Pp
+The
+.Nm
+kernel support provides feed-forward timestamping functions within the kernel
+and system calls to support feed-forward synchronisation daemons
+.Po see
+.Xr ffclock 2
+.Pc .
+.Ss Kernel Options
+The following kernel configuration options are related to
+.Nm :
+.Pp
+.Bl -tag -width ".Dv FFCLOCK" -compact
+.It Dv FFCLOCK
+Enable feed-forward clock support.
+.El
+.Ss Configuration
+When feed-forward clock support is compiled into the kernel, multiple system
+clocks become available to choose from.
+System clock configuration is possible via the
+.Va kern.sysclock
+.Xr sysctl 8
+tree which provides the following variables:
+.Bl -tag -width "    " -offset indent
+.It Va kern.sysclock.active
+Name of the current active system clock which is serving time.
+Set to one of the names in
+.Va kern.sysclock.available
+in order to change the default active system clock.
+.It Va kern.sysclock.available
+Lists the names of available system clocks
+.Po
+read only
+.Pc .
+.El
+.Pp
+Feed-forward system clock configuration is possible via the
+.Va kern.sysclock.ffclock
+sysctl tree which provides the following variables:
+.Bl -tag -width "    " -offset indent
+.It Va kern.sysclock.ffclock.version
+Feed-forward clock kernel version
+.Po
+read only
+.Pc .
+.It Va kern.sysclock.ffclock.ffcounter_bypass
+Use reliable hardware timecounter as the feed-forward counter.
+Will eventually be useful for virtualised environment like
+.Xr xen 4 ,
+but currently does nothing.
+.El
+.Sh SEE ALSO
+.Xr clock_gettime 2 ,
+.Xr ffclock 2 ,
+.Xr bpf 4 ,
+.Xr sysctl 8
+.Sh HISTORY
+Feed-forward clock support first appeared in
+.Fx 10.0 .
+.Sh AUTHORS
+.An -nosplit
+The feed-forward clock support was written by
+.An Julien Ridoux Aq jridoux at unimelb.edu.au
+in collaboration with
+.An Darryl Veitch Aq dveitch at unimelb.edu.au
+at the University of Melbourne under sponsorship from the FreeBSD Foundation.
+.Pp
+This manual page was written by
+.An Julien Ridoux Aq jridoux at unimelb.edu.au
+and
+.An Lawrence Stewart Aq lstewart at FreeBSD.org .
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/share/man/man4/netmap.4
--- a/head/share/man/man4/netmap.4	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/share/man/man4/netmap.4	Tue Dec 06 20:26:16 2011 +0200
@@ -25,7 +25,7 @@
 .\" This document is derived in part from the enet man page (enet.4)
 .\" distributed with 4.3BSD Unix.
 .\"
-.\" $FreeBSD: head/share/man/man4/netmap.4 227614 2011-11-17 12:17:39Z luigi $
+.\" $FreeBSD: head/share/man/man4/netmap.4 228017 2011-11-27 06:55:57Z gjb $
 .\" $Id: netmap.4 9662 2011-11-16 13:18:06Z luigi $: stable/8/share/man/man4/bpf.4 181694 2008-08-13 17:45:06Z ed $
 .\"
 .Dd November 16, 2011
@@ -155,7 +155,6 @@
 region. In particular:
 .Bd -literal
 struct netmap_if *nifp;
-...
 struct netmap_ring *txring = NETMAP_TXRING(nifp, i);
 struct netmap_ring *rxring = NETMAP_RXRING(nifp, i);
 int i = txring->slot[txring->cur].buf_idx;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/share/man/man5/src.conf.5
--- a/head/share/man/man5/src.conf.5	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/share/man/man5/src.conf.5	Tue Dec 06 20:26:16 2011 +0200
@@ -1,7 +1,7 @@
 .\" DO NOT EDIT-- this file is automatically generated.
 .\" from FreeBSD: head/tools/build/options/makeman 221733 2011-05-10 13:01:11Z ru
-.\" $FreeBSD: head/share/man/man5/src.conf.5 223210 2011-06-17 21:31:13Z ed $
-.Dd June 17, 2011
+.\" $FreeBSD: head/share/man/man5/src.conf.5 228197 2011-12-02 09:28:19Z fjoe $
+.Dd December 2, 2011
 .Dt SRC.CONF 5
 .Os
 .Sh NAME
@@ -258,6 +258,8 @@
 .Pp
 .Bl -item -compact
 .It
+.Va WITHOUT_CTF
+.It
 .Va WITHOUT_ZFS
 .El
 .It Va WITHOUT_CLANG
@@ -265,13 +267,13 @@
 Set to not build the Clang C/C++ compiler.
 .Pp
 It is a default setting on
-arm/arm, arm/armeb, ia64/ia64, mips/mipsel, mips/mipseb, mips/mips64el, mips/mips64eb, mips/mipsn32eb, powerpc/powerpc64 and sparc64/sparc64.
+arm/arm, arm/armeb, ia64/ia64, mips/mipsel, mips/mipseb, mips/mips64el, mips/mips64eb, mips/mipsn32eb and sparc64/sparc64.
 .It Va WITH_CLANG
 .\" from FreeBSD: head/tools/build/options/WITH_CLANG 221730 2011-05-10 11:14:40Z ru
 Set to build the Clang C/C++ compiler.
 .Pp
 It is a default setting on
-amd64/amd64, i386/i386, pc98/i386 and powerpc/powerpc.
+amd64/amd64, i386/i386, pc98/i386, powerpc/powerpc and powerpc/powerpc64.
 .It Va WITHOUT_CPP
 .\" from FreeBSD: head/tools/build/options/WITHOUT_CPP 156932 2006-03-21 07:50:50Z ru
 Set to not build
@@ -300,6 +302,11 @@
 .Va WITH_GSSAPI
 is set explicitly)
 .El
+.It Va WITH_CTF
+.\" from FreeBSD: head/tools/build/options/WITH_CTF 228159 2011-11-30 18:22:44Z fjoe
+Set to compile with CTF (Compact C Type Format) data.
+CTF data encapsulates a reduced form of debugging information
+similar to DWARF and the venerable stabs and is required for DTrace.
 .It Va WITHOUT_CTM
 .\" from FreeBSD: head/tools/build/options/WITHOUT_CTM 183242 2008-09-21 22:02:26Z sam
 Set to not build
@@ -345,14 +352,14 @@
 This includes the device tree compiler (dtc) and libfdt support library.
 .Pp
 It is a default setting on
-amd64/amd64, i386/i386, ia64/ia64, mips/mipsel, mips/mipseb, mips/mips64el, mips/mips64eb, mips/mipsn32eb, pc98/i386, powerpc/powerpc64 and sparc64/sparc64.
+amd64/amd64, i386/i386, ia64/ia64, pc98/i386 and sparc64/sparc64.
 .It Va WITH_FDT
 .\" from FreeBSD: head/tools/build/options/WITH_FDT 221730 2011-05-10 11:14:40Z ru
 Set to build Flattened Device Tree support as part of the base system.
 This includes the device tree compiler (dtc) and libfdt support library.
 .Pp
 It is a default setting on
-arm/arm, arm/armeb and powerpc/powerpc.
+arm/arm, arm/armeb, mips/mipsel, mips/mipseb, mips/mips64el, mips/mips64eb, mips/mipsn32eb, powerpc/powerpc and powerpc/powerpc64.
 .It Va WITHOUT_FLOPPY
 .\" from FreeBSD: head/tools/build/options/WITHOUT_FLOPPY 221540 2011-05-06 19:13:03Z ru
 Set to not build or install programs
@@ -409,7 +416,7 @@
 .\" from FreeBSD: head/tools/build/options/WITHOUT_GPIB 156932 2006-03-21 07:50:50Z ru
 Set to not build GPIB bus support.
 .It Va WITHOUT_GPIO
-.\" from FreeBSD: head/tools/build/options/WITHOUT_GPIO 221541 2011-05-06 19:14:06Z ru
+.\" from FreeBSD: head/tools/build/options/WITHOUT_GPIO 228081 2011-11-28 17:54:34Z dim
 Set to not build
 .Xr gpioctl 8
 as part of the base system.
@@ -563,6 +570,9 @@
 On amd64, set to not build 32-bit library set and a
 .Nm ld-elf32.so.1
 runtime linker.
+.It Va WITH_LIBCPLUSPLUS
+.\" from FreeBSD: head/tools/build/options/WITH_LIBCPLUSPLUS 228082 2011-11-28 17:56:46Z dim
+Set to build libcxxrt and libc++.
 .It Va WITHOUT_LIBPTHREAD
 .\" from FreeBSD: head/tools/build/options/WITHOUT_LIBPTHREAD 188848 2009-02-20 11:09:55Z mtm
 Set to not build the
@@ -734,7 +744,7 @@
 .Xr ntpd 8
 and related programs.
 .It Va WITH_OFED
-.\" from FreeBSD: head/tools/build/options/WITH_OFED 222016 2011-05-17 11:06:41Z ru
+.\" from FreeBSD: head/tools/build/options/WITH_OFED 228081 2011-11-28 17:54:34Z dim
 Set to build the
 .Dq "OpenFabrics Enterprise Distribution"
 Infiniband software stack.
@@ -811,7 +821,7 @@
 .Xr ppp 8
 and related programs.
 .It Va WITHOUT_PROFILE
-.\" from FreeBSD: head/tools/build/options/WITHOUT_PROFILE 156932 2006-03-21 07:50:50Z ru
+.\" from FreeBSD: head/tools/build/options/WITH_PROFILE 228143 2011-11-29 19:46:17Z fjoe
 Set to avoid compiling profiled libraries.
 .It Va WITHOUT_QUOTAS
 .\" from FreeBSD: head/tools/build/options/WITHOUT_QUOTAS 183242 2008-09-21 22:02:26Z sam
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/share/misc/committers-src.dot
--- a/head/share/misc/committers-src.dot	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/share/misc/committers-src.dot	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-# $FreeBSD: head/share/misc/committers-src.dot 227453 2011-11-11 20:13:24Z theraven $
+# $FreeBSD: head/share/misc/committers-src.dot 228225 2011-12-03 14:03:53Z jhibbits $
 
 # This file is meant to list all FreeBSD src committers and describe the
 # mentor-mentee relationships between them.
@@ -159,6 +159,7 @@
 jeff [label="Jeff Roberson\njeff at FreeBSD.org\n2002/02/21"]
 jh [label="Jaakko Heinonen\njh at FreeBSD.org\n2009/10/02"]
 jhb [label="John Baldwin\njhb at FreeBSD.org\n1999/08/23"]
+jhibbits [label="Justin Hibbits\njhibbits at FreeBSD.org\n2011/11/30"]
 jilles [label="Jilles Tjoelker\njilles at FreeBSD.org\n2009/05/22"]
 jinmei [label="JINMEI Tatuya\njinmei at FreeBSD.org\n2007/03/17"]
 jkim [label="Jung-uk Kim\njkim at FreeBSD.org\n2005/07/06"]
@@ -497,6 +498,7 @@
 njl -> sepotvin
 
 nwhitehorn -> andreast
+nwhitehorn -> jhibbits
 
 obrien -> benno
 obrien -> groudier
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/share/mk/bsd.lib.mk
--- a/head/share/mk/bsd.lib.mk	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/share/mk/bsd.lib.mk	Tue Dec 06 20:26:16 2011 +0200
@@ -1,5 +1,5 @@
 #	from: @(#)bsd.lib.mk	5.26 (Berkeley) 5/2/91
-# $FreeBSD: head/share/mk/bsd.lib.mk 227797 2011-11-21 16:35:57Z des $
+# $FreeBSD: head/share/mk/bsd.lib.mk 228307 2011-12-06 11:28:17Z kib $
 #
 
 .include <bsd.init.mk>
@@ -33,15 +33,10 @@
 NO_WERROR=
 .endif
 
-# Enable CTF conversion on request.
-.if defined(WITH_CTF)
-.undef NO_CTF
-.endif
-
 .if defined(DEBUG_FLAGS)
 CFLAGS+= ${DEBUG_FLAGS}
 
-.if !defined(NO_CTF) && (${DEBUG_FLAGS:M-g} != "")
+.if ${MK_CTF} != "no" && ${DEBUG_FLAGS:M-g} != ""
 CTFFLAGS+= -g
 .endif
 .endif
@@ -69,18 +64,15 @@
 
 .c.o:
 	${CC} ${STATIC_CFLAGS} ${CFLAGS} -c ${.IMPSRC} -o ${.TARGET}
+	${CTFCONVERT_CMD}
 
 .c.po:
 	${CC} ${PO_FLAG} ${STATIC_CFLAGS} ${PO_CFLAGS} -c ${.IMPSRC} -o ${.TARGET}
-	@[ -z "${CTFCONVERT}" -o -n "${NO_CTF}" ] || \
-		(${ECHO} ${CTFCONVERT} ${CTFFLAGS} ${.TARGET} && \
-		${CTFCONVERT} ${CTFFLAGS} ${.TARGET})
+	${CTFCONVERT_CMD}
 
 .c.So:
 	${CC} ${PICFLAG} -DPIC ${SHARED_CFLAGS} ${CFLAGS} -c ${.IMPSRC} -o ${.TARGET}
-	@[ -z "${CTFCONVERT}" -o -n "${NO_CTF}" ] || \
-		(${ECHO} ${CTFCONVERT} ${CTFFLAGS} ${.TARGET} && \
-		${CTFCONVERT} ${CTFFLAGS} ${.TARGET})
+	${CTFCONVERT_CMD}
 
 .cc.o:
 	${CXX} ${STATIC_CXXFLAGS} ${CXXFLAGS} -c ${.IMPSRC} -o ${.TARGET}
@@ -93,47 +85,33 @@
 
 .f.po:
 	${FC} -pg ${FFLAGS} -o ${.TARGET} -c ${.IMPSRC}
-	@[ -z "${CTFCONVERT}" -o -n "${NO_CTF}" ] || \
-		(${ECHO} ${CTFCONVERT} ${CTFFLAGS} ${.TARGET} && \
-		${CTFCONVERT} ${CTFFLAGS} ${.TARGET})
+	${CTFCONVERT_CMD}
 
 .f.So:
 	${FC} ${PICFLAG} -DPIC ${FFLAGS} -o ${.TARGET} -c ${.IMPSRC}
-	@[ -z "${CTFCONVERT}" -o -n "${NO_CTF}" ] || \
-		(${ECHO} ${CTFCONVERT} ${CTFFLAGS} ${.TARGET} && \
-		${CTFCONVERT} ${CTFFLAGS} ${.TARGET})
+	${CTFCONVERT_CMD}
 
 .s.po .s.So:
 	${AS} ${AFLAGS} -o ${.TARGET} ${.IMPSRC}
-	@[ -z "${CTFCONVERT}" -o -n "${NO_CTF}" ] || \
-		(${ECHO} ${CTFCONVERT} ${CTFFLAGS} ${.TARGET} && \
-		${CTFCONVERT} ${CTFFLAGS} ${.TARGET})
+	${CTFCONVERT_CMD}
 
 .asm.po:
 	${CC} -x assembler-with-cpp -DPROF ${PO_CFLAGS} ${ACFLAGS} \
 		-c ${.IMPSRC} -o ${.TARGET}
-	@[ -z "${CTFCONVERT}" -o -n "${NO_CTF}" ] || \
-		(${ECHO} ${CTFCONVERT} ${CTFFLAGS} ${.TARGET} && \
-		${CTFCONVERT} ${CTFFLAGS} ${.TARGET})
+	${CTFCONVERT_CMD}
 
 .asm.So:
 	${CC} -x assembler-with-cpp ${PICFLAG} -DPIC ${CFLAGS} ${ACFLAGS} \
 	    -c ${.IMPSRC} -o ${.TARGET}
-	@[ -z "${CTFCONVERT}" -o -n "${NO_CTF}" ] || \
-		(${ECHO} ${CTFCONVERT} ${CTFFLAGS} ${.TARGET} && \
-		${CTFCONVERT} ${CTFFLAGS} ${.TARGET})
+	${CTFCONVERT_CMD}
 
 .S.po:
 	${CC} -DPROF ${PO_CFLAGS} ${ACFLAGS} -c ${.IMPSRC} -o ${.TARGET}
-	@[ -z "${CTFCONVERT}" -o -n "${NO_CTF}" ] || \
-		(${ECHO} ${CTFCONVERT} ${CTFFLAGS} ${.TARGET} && \
-		${CTFCONVERT} ${CTFFLAGS} ${.TARGET})
+	${CTFCONVERT_CMD}
 
 .S.So:
 	${CC} ${PICFLAG} -DPIC ${CFLAGS} ${ACFLAGS} -c ${.IMPSRC} -o ${.TARGET}
-	@[ -z "${CTFCONVERT}" -o -n "${NO_CTF}" ] || \
-		(${ECHO} ${CTFCONVERT} ${CTFFLAGS} ${.TARGET} && \
-		${CTFCONVERT} ${CTFFLAGS} ${.TARGET})
+	${CTFCONVERT_CMD}
 
 all: objwarn
 
@@ -189,6 +167,11 @@
 .if defined(SHLIB_NAME)
 _LIBS+=		${SHLIB_NAME}
 
+SOLINKOPTS=	-shared -Wl,-x
+.if !defined(ALLOW_SHARED_TEXTREL)
+SOLINKOPTS+=	-Wl,--fatal-warnings -Wl,--warn-shared-textrel
+.endif
+
 .if target(beforelinking)
 ${SHLIB_NAME}: ${SOBJS} beforelinking
 .else
@@ -200,17 +183,17 @@
 	@ln -fs ${.TARGET} ${SHLIB_LINK}
 .endif
 .if !defined(NM)
-	@${CC} ${LDFLAGS} ${SSP_CFLAGS} -shared -Wl,-x \
+	@${CC} ${LDFLAGS} ${SSP_CFLAGS} ${SOLINKOPTS} \
 	    -o ${.TARGET} -Wl,-soname,${SONAME} \
 	    `lorder ${SOBJS} | tsort -q` ${LDADD}
 .else
-	@${CC} ${LDFLAGS} ${SSP_CFLAGS} -shared -Wl,-x \
+	@${CC} ${LDFLAGS} ${SSP_CFLAGS} ${SOLINKOPTS} \
 	    -o ${.TARGET} -Wl,-soname,${SONAME} \
 	    `NM='${NM}' lorder ${SOBJS} | tsort -q` ${LDADD}
 .endif
-	@[ -z "${CTFMERGE}" -o -n "${NO_CTF}" ] || \
-		(${ECHO} ${CTFMERGE} ${CTFFLAGS} -o ${.TARGET} ${SOBJS} && \
-		${CTFMERGE} ${CTFFLAGS} -o ${.TARGET} ${SOBJS})
+.if ${MK_CTF} != "no"
+	${CTFMERGE} ${CTFFLAGS} -o ${.TARGET} ${SOBJS}
+.endif
 .endif
 
 .if defined(INSTALL_PIC_ARCHIVE) && defined(LIB) && !empty(LIB) && ${MK_TOOLCHAIN} != "no" && !defined(NO_STATIC_LIB)
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/share/mk/bsd.libnames.mk
--- a/head/share/mk/bsd.libnames.mk	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/share/mk/bsd.libnames.mk	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-# $FreeBSD: head/share/mk/bsd.libnames.mk 222035 2011-05-17 19:11:47Z flz $
+# $FreeBSD: head/share/mk/bsd.libnames.mk 227983 2011-11-25 20:59:04Z theraven $
 
 # The include file <bsd.libnames.mk> define library names.
 # Other include files (e.g. bsd.prog.mk, bsd.lib.mk) include this
@@ -26,6 +26,8 @@
 LIBBSM?=	${DESTDIR}${LIBDIR}/libbsm.a
 LIBBSNMP?=	${DESTDIR}${LIBDIR}/libbsnmp.a
 LIBBZ2?=	${DESTDIR}${LIBDIR}/libbz2.a
+LIBCXXRT?=	${DESTDIR}${LIBDIR}/libcxxrt.a
+LIBCPLUSPLUS?=	${DESTDIR}${LIBDIR}/libc++.a
 LIBC?=		${DESTDIR}${LIBDIR}/libc.a
 LIBC_PIC?=	${DESTDIR}${LIBDIR}/libc_pic.a
 LIBCALENDAR?=	${DESTDIR}${LIBDIR}/libcalendar.a
@@ -100,7 +102,6 @@
 LIBNETGRAPH?=	${DESTDIR}${LIBDIR}/libnetgraph.a
 LIBNGATM?=	${DESTDIR}${LIBDIR}/libngatm.a
 LIBNVPAIR?=	${DESTDIR}${LIBDIR}/libnvpair.a
-LIBODIALOG?=	${DESTDIR}${LIBDIR}/libodialog.a
 LIBOPIE?=	${DESTDIR}${LIBDIR}/libopie.a
 
 # The static PAM library doesn't know its secondary dependencies,
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/share/mk/bsd.own.mk
--- a/head/share/mk/bsd.own.mk	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/share/mk/bsd.own.mk	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-# $FreeBSD: head/share/mk/bsd.own.mk 227775 2011-11-21 00:49:46Z nwhitehorn $
+# $FreeBSD: head/share/mk/bsd.own.mk 228196 2011-12-02 09:09:54Z fjoe $
 #
 # The include file <bsd.own.mk> set common variables for owner,
 # group, mode, and directories. Defaults are in brackets.
@@ -207,10 +207,14 @@
 # regardless of user's setting).
 #
 .for var in \
+    CTF \
     INSTALLLIB \
     MAN \
     PROFILE
 .if defined(NO_${var})
+.if defined(WITH_${var})
+.undef WITH_${var}
+.endif
 WITHOUT_${var}=
 .endif
 .endfor
@@ -416,9 +420,11 @@
     BIND_LIBS \
     BIND_SIGCHASE \
     BIND_XML \
+    CTF \
     HESIOD \
     ICONV \
     IDEA \
+    LIBCPLUSPLUS \
     OFED
 
 #
@@ -512,6 +518,7 @@
 
 .if ${MK_CDDL} == "no"
 MK_ZFS:=	no
+MK_CTF:=	no
 .endif
 
 .if ${MK_CRYPT} == "no"
@@ -612,6 +619,14 @@
 .endif
 .endfor
 
+.if ${MK_CTF} != "no"
+CTFCONVERT_CMD=	${CTFCONVERT} ${CTFFLAGS} ${.TARGET}
+.elif ${MAKE_VERSION} >= 5201111300
+CTFCONVERT_CMD=
+.else
+CTFCONVERT_CMD=	@:
+.endif 
+
 .endif # !_WITHOUT_SRCCONF
 
 .endif	# !target(__<bsd.own.mk>__)
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/share/mk/bsd.prog.mk
--- a/head/share/mk/bsd.prog.mk	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/share/mk/bsd.prog.mk	Tue Dec 06 20:26:16 2011 +0200
@@ -1,5 +1,5 @@
 #	from: @(#)bsd.prog.mk	5.26 (Berkeley) 6/25/91
-# $FreeBSD: head/share/mk/bsd.prog.mk 220755 2011-04-17 21:03:23Z dim $
+# $FreeBSD: head/share/mk/bsd.prog.mk 228158 2011-11-30 18:11:49Z fjoe $
 
 .include <bsd.init.mk>
 
@@ -15,16 +15,11 @@
 NO_WERROR=
 .endif
 
-# Enable CTF conversion on request.
-.if defined(WITH_CTF)
-.undef NO_CTF
-.endif
-
 .if defined(DEBUG_FLAGS)
 CFLAGS+=${DEBUG_FLAGS}
 CXXFLAGS+=${DEBUG_FLAGS}
 
-.if !defined(NO_CTF) && (${DEBUG_FLAGS:M-g} != "")
+.if ${MK_CTF} != "no" && ${DEBUG_FLAGS:M-g} != ""
 CTFFLAGS+= -g
 .endif
 .endif
@@ -60,9 +55,9 @@
 .else
 	${CC} ${CFLAGS} ${LDFLAGS} -o ${.TARGET} ${OBJS} ${LDADD}
 .endif
-	@[ -z "${CTFMERGE}" -o -n "${NO_CTF}" ] || \
-		(${ECHO} ${CTFMERGE} ${CTFFLAGS} -o ${.TARGET} ${OBJS} && \
-		${CTFMERGE} ${CTFFLAGS} -o ${.TARGET} ${OBJS})
+.if ${MK_CTF} != "no"
+	${CTFMERGE} ${CTFFLAGS} -o ${.TARGET} ${OBJS}
+.endif
 
 .else	# !defined(SRCS)
 
@@ -90,9 +85,9 @@
 .else
 	${CC} ${CFLAGS} ${LDFLAGS} -o ${.TARGET} ${OBJS} ${LDADD}
 .endif
-	@[ -z "${CTFMERGE}" -o -n "${NO_CTF}" ] || \
-		(${ECHO} ${CTFMERGE} ${CTFFLAGS} -o ${.TARGET} ${OBJS} && \
-		${CTFMERGE} ${CTFFLAGS} -o ${.TARGET} ${OBJS})
+.if ${MK_CTF} != "no"
+	${CTFMERGE} ${CTFFLAGS} -o ${.TARGET} ${OBJS}
+.endif
 .endif
 
 .endif
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/share/mk/sys.mk
--- a/head/share/mk/sys.mk	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/share/mk/sys.mk	Tue Dec 06 20:26:16 2011 +0200
@@ -1,5 +1,5 @@
 #	from: @(#)sys.mk	8.2 (Berkeley) 3/21/94
-# $FreeBSD$
+# $FreeBSD: head/share/mk/sys.mk 228137 2011-11-29 16:34:44Z fjoe $
 
 unix		?=	We run FreeBSD, not UNIX.
 .FreeBSD	?=	true
@@ -59,12 +59,6 @@
 .endif
 PO_CFLAGS	?=	${CFLAGS}
 
-# Turn CTF conversion off by default for now. This default could be
-# changed later if DTrace becomes popular.
-.if !defined(WITH_CTF)
-NO_CTF		=	1
-.endif
-
 # C Type Format data is required for DTrace
 CTFFLAGS	?=	-L VERSION
 
@@ -158,15 +152,11 @@
 # SINGLE SUFFIX RULES
 .c:
 	${CC} ${CFLAGS} ${LDFLAGS} -o ${.TARGET} ${.IMPSRC}
-	@[ -z "${CTFCONVERT}" -o -n "${NO_CTF}" ] || \
-		(${ECHO} ${CTFCONVERT} ${CTFFLAGS} ${.TARGET} && \
-		${CTFCONVERT} ${CTFFLAGS} ${.TARGET})
+	${CTFCONVERT_CMD}
 
 .f:
 	${FC} ${FFLAGS} ${LDFLAGS} -o ${.TARGET} ${.IMPSRC}
-	@[ -z "${CTFCONVERT}" -o -n "${NO_CTF}" ] || \
-		(${ECHO} ${CTFCONVERT} ${CTFFLAGS} ${.TARGET} && \
-		${CTFCONVERT} ${CTFFLAGS} ${.TARGET})
+	${CTFCONVERT_CMD}
 
 .sh:
 	cp -f ${.IMPSRC} ${.TARGET}
@@ -176,33 +166,25 @@
 
 .c.o:
 	${CC} ${CFLAGS} -c ${.IMPSRC}
-	@[ -z "${CTFCONVERT}" -o -n "${NO_CTF}" ] || \
-		(${ECHO} ${CTFCONVERT} ${CTFFLAGS} ${.TARGET} && \
-		${CTFCONVERT} ${CTFFLAGS} ${.TARGET})
+	${CTFCONVERT_CMD}
 
 .f.o:
 	${FC} ${FFLAGS} -c ${.IMPSRC}
-	@[ -z "${CTFCONVERT}" -o -n "${NO_CTF}" ] || \
-		(${ECHO} ${CTFCONVERT} ${CTFFLAGS} ${.TARGET} && \
-		${CTFCONVERT} ${CTFFLAGS} ${.TARGET})
+	${CTFCONVERT_CMD}
 
 .y.o:
 	${YACC} ${YFLAGS} ${.IMPSRC}
 	${CC} ${CFLAGS} -c y.tab.c
 	rm -f y.tab.c
 	mv y.tab.o ${.TARGET}
-	@[ -z "${CTFCONVERT}" -o -n "${NO_CTF}" ] || \
-		(${ECHO} ${CTFCONVERT} ${CTFFLAGS} ${.TARGET} && \
-		${CTFCONVERT} ${CTFFLAGS} ${.TARGET})
+	${CTFCONVERT_CMD}
 
 .l.o:
 	${LEX} ${LFLAGS} ${.IMPSRC}
 	${CC} ${CFLAGS} -c lex.yy.c
 	rm -f lex.yy.c
 	mv lex.yy.o ${.TARGET}
-	@[ -z "${CTFCONVERT}" -o -n "${NO_CTF}" ] || \
-		(${ECHO} ${CTFCONVERT} ${CTFFLAGS} ${.TARGET} && \
-		${CTFCONVERT} ${CTFFLAGS} ${.TARGET})
+	${CTFCONVERT_CMD}
 
 .y.c:
 	${YACC} ${YFLAGS} ${.IMPSRC}
@@ -240,15 +222,11 @@
 
 .c:
 	${CC} ${CFLAGS} ${LDFLAGS} ${.IMPSRC} ${LDLIBS} -o ${.TARGET}
-	@[ -z "${CTFCONVERT}" -o -n "${NO_CTF}" ] || \
-		(${ECHO} ${CTFCONVERT} ${CTFFLAGS} ${.TARGET} && \
-		${CTFCONVERT} ${CTFFLAGS} ${.TARGET})
+	${CTFCONVERT_CMD}
 
 .c.o:
 	${CC} ${CFLAGS} -c ${.IMPSRC}
-	@[ -z "${CTFCONVERT}" -o -n "${NO_CTF}" ] || \
-		(${ECHO} ${CTFCONVERT} ${CTFFLAGS} ${.TARGET} && \
-		${CTFCONVERT} ${CTFFLAGS} ${.TARGET})
+	${CTFCONVERT_CMD}
 
 .cc .cpp .cxx .C:
 	${CXX} ${CXXFLAGS} ${LDFLAGS} ${.IMPSRC} ${LDLIBS} -o ${.TARGET}
@@ -258,15 +236,11 @@
 
 .m.o:
 	${OBJC} ${OBJCFLAGS} -c ${.IMPSRC}
-	@[ -z "${CTFCONVERT}" -o -n "${NO_CTF}" ] || \
-		(${ECHO} ${CTFCONVERT} ${CTFFLAGS} ${.TARGET} && \
-		${CTFCONVERT} ${CTFFLAGS} ${.TARGET})
+	${CTFCONVERT_CMD}
 
 .p.o:
 	${PC} ${PFLAGS} -c ${.IMPSRC}
-	@[ -z "${CTFCONVERT}" -o -n "${NO_CTF}" ] || \
-		(${ECHO} ${CTFCONVERT} ${CTFFLAGS} ${.TARGET} && \
-		${CTFCONVERT} ${CTFFLAGS} ${.TARGET})
+	${CTFCONVERT_CMD}
 
 .e .r .F .f:
 	${FC} ${RFLAGS} ${EFLAGS} ${FFLAGS} ${LDFLAGS} ${.IMPSRC} ${LDLIBS} \
@@ -277,38 +251,28 @@
 
 .S.o:
 	${CC} ${CFLAGS} ${ACFLAGS} -c ${.IMPSRC}
-	@[ -z "${CTFCONVERT}" -o -n "${NO_CTF}" ] || \
-		(${ECHO} ${CTFCONVERT} ${CTFFLAGS} ${.TARGET} && \
-		${CTFCONVERT} ${CTFFLAGS} ${.TARGET})
+	${CTFCONVERT_CMD}
 
 .asm.o:
 	${CC} -x assembler-with-cpp ${CFLAGS} ${ACFLAGS} -c ${.IMPSRC}
-	@[ -z "${CTFCONVERT}" -o -n "${NO_CTF}" ] || \
-		(${ECHO} ${CTFCONVERT} ${CTFFLAGS} ${.TARGET} && \
-		${CTFCONVERT} ${CTFFLAGS} ${.TARGET})
+	${CTFCONVERT_CMD}
 
 .s.o:
 	${AS} ${AFLAGS} -o ${.TARGET} ${.IMPSRC}
-	@[ -z "${CTFCONVERT}" -o -n "${NO_CTF}" ] || \
-		(${ECHO} ${CTFCONVERT} ${CTFFLAGS} ${.TARGET} && \
-		${CTFCONVERT} ${CTFFLAGS} ${.TARGET})
+	${CTFCONVERT_CMD}
 
 # XXX not -j safe
 .y.o:
 	${YACC} ${YFLAGS} ${.IMPSRC}
 	${CC} ${CFLAGS} -c y.tab.c -o ${.TARGET}
 	rm -f y.tab.c
-	@[ -z "${CTFCONVERT}" -o -n "${NO_CTF}" ] || \
-		(${ECHO} ${CTFCONVERT} ${CTFFLAGS} ${.TARGET} && \
-		${CTFCONVERT} ${CTFFLAGS} ${.TARGET})
+	${CTFCONVERT_CMD}
 
 .l.o:
 	${LEX} -t ${LFLAGS} ${.IMPSRC} > ${.PREFIX}.tmp.c
 	${CC} ${CFLAGS} -c ${.PREFIX}.tmp.c -o ${.TARGET}
 	rm -f ${.PREFIX}.tmp.c
-	@[ -z "${CTFCONVERT}" -o -n "${NO_CTF}" ] || \
-		(${ECHO} ${CTFCONVERT} ${CTFFLAGS} ${.TARGET} && \
-		${CTFCONVERT} ${CTFFLAGS} ${.TARGET})
+	${CTFCONVERT_CMD}
 
 # XXX not -j safe
 .y.c:
@@ -320,34 +284,26 @@
 
 .s.out .c.out .o.out:
 	${CC} ${CFLAGS} ${LDFLAGS} ${.IMPSRC} ${LDLIBS} -o ${.TARGET}
-	@[ -z "${CTFCONVERT}" -o -n "${NO_CTF}" ] || \
-		(${ECHO} ${CTFCONVERT} ${CTFFLAGS} ${.TARGET} && \
-		${CTFCONVERT} ${CTFFLAGS} ${.TARGET})
+	${CTFCONVERT_CMD}
 
 .f.out .F.out .r.out .e.out:
 	${FC} ${EFLAGS} ${RFLAGS} ${FFLAGS} ${LDFLAGS} ${.IMPSRC} \
 	    ${LDLIBS} -o ${.TARGET}
 	rm -f ${.PREFIX}.o
-	@[ -z "${CTFCONVERT}" -o -n "${NO_CTF}" ] || \
-		(${ECHO} ${CTFCONVERT} ${CTFFLAGS} ${.TARGET} && \
-		${CTFCONVERT} ${CTFFLAGS} ${.TARGET})
+	${CTFCONVERT_CMD}
 
 # XXX not -j safe
 .y.out:
 	${YACC} ${YFLAGS} ${.IMPSRC}
 	${CC} ${CFLAGS} ${LDFLAGS} y.tab.c ${LDLIBS} -ly -o ${.TARGET}
 	rm -f y.tab.c
-	@[ -z "${CTFCONVERT}" -o -n "${NO_CTF}" ] || \
-		(${ECHO} ${CTFCONVERT} ${CTFFLAGS} ${.TARGET} && \
-		${CTFCONVERT} ${CTFFLAGS} ${.TARGET})
+	${CTFCONVERT_CMD}
 
 .l.out:
 	${LEX} -t ${LFLAGS} ${.IMPSRC} > ${.PREFIX}.tmp.c
 	${CC} ${CFLAGS} ${LDFLAGS} ${.PREFIX}.tmp.c ${LDLIBS} -ll -o ${.TARGET}
 	rm -f ${.PREFIX}.tmp.c
-	@[ -z "${CTFCONVERT}" -o -n "${NO_CTF}" ] || \
-		(${ECHO} ${CTFCONVERT} ${CTFFLAGS} ${.TARGET} && \
-		${CTFCONVERT} ${CTFFLAGS} ${.TARGET})
+	${CTFCONVERT_CMD}
 
 # FreeBSD build pollution.  Hide it in the non-POSIX part of the ifdef.
 __MAKE_CONF?=/etc/make.conf
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/amd64/conf/NOTES
--- a/head/sys/amd64/conf/NOTES	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/amd64/conf/NOTES	Tue Dec 06 20:26:16 2011 +0200
@@ -4,7 +4,7 @@
 # This file contains machine dependent kernel configuration notes.  For
 # machine independent notes, look in /sys/conf/NOTES.
 #
-# $FreeBSD: head/sys/amd64/conf/NOTES 225194 2011-08-26 17:08:22Z jhb $
+# $FreeBSD: head/sys/amd64/conf/NOTES 228085 2011-11-28 18:51:40Z philip $
 #
 
 #
@@ -294,6 +294,7 @@
 #	Requires the mwl firmware module
 # nfe:	nVidia nForce MCP on-board Ethernet Networking (BSD open source)
 # nve:	nVidia nForce MCP on-board Ethernet Networking
+# sfxge: Solarflare SFC9000 family 10Gb Ethernet adapters
 # wpi:	Intel 3945ABG Wireless LAN controller
 #	Requires the wpi firmware module
 
@@ -307,6 +308,7 @@
 device		mwl
 device		nfe
 device		nve
+device		sfxge
 device		wpi
 
 # IEEE 802.11 adapter firmware modules
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/arm/mv/common.c
--- a/head/sys/arm/mv/common.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/arm/mv/common.c	Tue Dec 06 20:26:16 2011 +0200
@@ -30,7 +30,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/arm/mv/common.c 225991 2011-10-04 16:58:20Z marcel $");
+__FBSDID("$FreeBSD: head/sys/arm/mv/common.c 228201 2011-12-02 15:24:39Z jchandra $");
 
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -1693,7 +1693,7 @@
 	int len, tuple_size, tuples_count;
 
 	node = OF_finddevice(nodename);
-	if (node <= 0)
+	if (node == -1)
 		return (EINVAL);
 
 	if ((fdt_addrsize_cells(node, &addr_cells, &size_cells)) != 0)
@@ -1762,11 +1762,11 @@
 	/*
 	 * Retrieve CESA SRAM data.
 	 */
-	if ((node = OF_finddevice("sram")) != 0)
+	if ((node = OF_finddevice("sram")) != -1)
 		if (fdt_is_compatible(node, "mrvl,cesa-sram"))
 			goto moveon;
 
-	if ((node = OF_finddevice("/")) == 0)
+	if ((node = OF_finddevice("/")) != -1)
 		return (ENXIO);
 
 	if ((node = fdt_find_compatible(node, "mrvl,cesa-sram", 0)) == 0)
@@ -1796,7 +1796,7 @@
 	int err, i;
 
 	node = OF_finddevice("/");
-	if (node == 0)
+	if (node == -1)
 		panic("fdt_win_setup: no root node");
 
 	node = fdt_find_compatible(node, "simple-bus", 1);
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/arm/mv/mv_machdep.c
--- a/head/sys/arm/mv/mv_machdep.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/arm/mv/mv_machdep.c	Tue Dec 06 20:26:16 2011 +0200
@@ -39,7 +39,7 @@
 #include "opt_platform.h"
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/arm/mv/mv_machdep.c 225991 2011-10-04 16:58:20Z marcel $");
+__FBSDID("$FreeBSD: head/sys/arm/mv/mv_machdep.c 228201 2011-12-02 15:24:39Z jchandra $");
 
 #define _ARM32_BUS_DMA_PRIVATE
 #include <sys/param.h>
@@ -617,13 +617,13 @@
 	/*
 	 * Try to access the MPP node directly i.e. through /aliases/mpp.
 	 */
-	if ((node = OF_finddevice("mpp")) != 0)
+	if ((node = OF_finddevice("mpp")) != -1)
 		if (fdt_is_compatible(node, "mrvl,mpp"))
 			goto moveon;
 	/*
 	 * Find the node the long way.
 	 */
-	if ((node = OF_finddevice("/")) == 0)
+	if ((node = OF_finddevice("/")) == -1)
 		return (ENXIO);
 
 	if ((node = fdt_find_compatible(node, "simple-bus", 0)) == 0)
@@ -752,7 +752,7 @@
 	/*
 	 * PCI range(s).
 	 */
-	if ((root = OF_finddevice("/")) == 0)
+	if ((root = OF_finddevice("/")) == -1)
 		return (ENXIO);
 
 	for (child = OF_child(root); child != 0; child = OF_peer(child))
@@ -779,7 +779,7 @@
 	/*
 	 * CESA SRAM range.
 	 */
-	if ((child = OF_finddevice("sram")) != 0)
+	if ((child = OF_finddevice("sram")) != -1)
 		if (fdt_is_compatible(child, "mrvl,cesa-sram"))
 			goto moveon;
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/boot/i386/zfsboot/zfsboot.c
--- a/head/sys/boot/i386/zfsboot/zfsboot.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/boot/i386/zfsboot/zfsboot.c	Tue Dec 06 20:26:16 2011 +0200
@@ -14,7 +14,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/boot/i386/zfsboot/zfsboot.c 226506 2011-10-18 09:46:52Z des $");
+__FBSDID("$FreeBSD: head/sys/boot/i386/zfsboot/zfsboot.c 228267 2011-12-04 21:32:18Z avg $");
 
 #include <sys/param.h>
 #include <sys/errno.h>
@@ -541,10 +541,10 @@
     }
 
     if (*cmd) {
+	if (!OPT_CHECK(RBX_QUIET))
+	    printf("%s: %s", PATH_CONFIG, cmd);
 	if (parse())
 	    autoboot = 0;
-	if (!OPT_CHECK(RBX_QUIET))
-	    printf("%s: %s", PATH_CONFIG, cmd);
 	/* Do not process this command twice */
 	*cmd = 0;
     }
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/boot/zfs/zfsimpl.c
--- a/head/sys/boot/zfs/zfsimpl.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/boot/zfs/zfsimpl.c	Tue Dec 06 20:26:16 2011 +0200
@@ -25,7 +25,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/boot/zfs/zfsimpl.c 226568 2011-10-20 15:42:38Z pjd $");
+__FBSDID("$FreeBSD: head/sys/boot/zfs/zfsimpl.c 228266 2011-12-04 21:29:56Z avg $");
 
 /*
  *	Stand-alone ZFS file reader.
@@ -458,6 +458,9 @@
 
 	if (strcmp(type, VDEV_TYPE_MIRROR)
 	    && strcmp(type, VDEV_TYPE_DISK)
+#ifdef ZFS_TEST
+	    && strcmp(type, VDEV_TYPE_FILE)
+#endif
 	    && strcmp(type, VDEV_TYPE_RAIDZ)
 	    && strcmp(type, VDEV_TYPE_REPLACING)) {
 		printf("ZFS: can only boot from disk, mirror, raidz1, raidz2 and raidz3 vdevs\n");
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/cam/cam_xpt.c
--- a/head/sys/cam/cam_xpt.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/cam/cam_xpt.c	Tue Dec 06 20:26:16 2011 +0200
@@ -28,7 +28,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/cam/cam_xpt.c 227637 2011-11-17 21:07:56Z mav $");
+__FBSDID("$FreeBSD: head/sys/cam/cam_xpt.c 228027 2011-11-27 16:22:19Z marius $");
 
 #include <sys/param.h>
 #include <sys/bus.h>
@@ -48,10 +48,6 @@
 #include <sys/sysctl.h>
 #include <sys/kthread.h>
 
-#ifdef PC98
-#include <pc98/pc98/pc98_machdep.h>	/* geometry translation */
-#endif
-
 #include <cam/cam.h>
 #include <cam/cam_ccb.h>
 #include <cam/cam_periph.h>
@@ -66,7 +62,10 @@
 #include <cam/scsi/scsi_all.h>
 #include <cam/scsi/scsi_message.h>
 #include <cam/scsi/scsi_pass.h>
+
+#include <machine/md_var.h>	/* geometry translation */
 #include <machine/stdarg.h>	/* for xpt_print below */
+
 #include "opt_cam.h"
 
 /*
@@ -2456,7 +2455,7 @@
 			start_ccb->ccb_h.status = CAM_REQ_CMP;
 			break;
 		}
-#ifdef PC98
+#if defined(PC98) || defined(__sparc64__)
 		/*
 		 * In a PC-98 system, geometry translation depens on
 		 * the "real" device geometry obtained from mode page 4.
@@ -2465,6 +2464,9 @@
 		 * stored in host memory.  If the translation is available
 		 * in host memory, use it.  If not, rely on the default
 		 * translation the device driver performs.
+		 * For sparc64, we may need adjust the geometry of large
+		 * disks in order to fit the limitations of the 16-bit
+		 * fields of the VTOC8 disk label.
 		 */
 		if (scsi_da_bios_params(&start_ccb->ccg) != 0) {
 			start_ccb->ccb_h.status = CAM_REQ_CMP;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/cddl/contrib/opensolaris/common/zfs/zfs_prop.c
--- a/head/sys/cddl/contrib/opensolaris/common/zfs/zfs_prop.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/cddl/contrib/opensolaris/common/zfs/zfs_prop.c	Tue Dec 06 20:26:16 2011 +0200
@@ -267,7 +267,7 @@
 	/* default index properties */
 	zprop_register_index(ZFS_PROP_VERSION, "version", 0, PROP_DEFAULT,
 	    ZFS_TYPE_FILESYSTEM | ZFS_TYPE_SNAPSHOT,
-	    "1 | 2 | 3 | 4 | current", "VERSION", version_table);
+	    "1 | 2 | 3 | 4 | 5 | current", "VERSION", version_table);
 	zprop_register_index(ZFS_PROP_CANMOUNT, "canmount", ZFS_CANMOUNT_ON,
 	    PROP_DEFAULT, ZFS_TYPE_FILESYSTEM, "on | off | noauto",
 	    "CANMOUNT", canmount_table);
@@ -297,6 +297,8 @@
 	/* string properties */
 	zprop_register_string(ZFS_PROP_ORIGIN, "origin", NULL, PROP_READONLY,
 	    ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME, "<snapshot>", "ORIGIN");
+	zprop_register_string(ZFS_PROP_CLONES, "clones", NULL, PROP_READONLY,
+	    ZFS_TYPE_SNAPSHOT, "<dataset>[,...]", "CLONES");
 	zprop_register_string(ZFS_PROP_MOUNTPOINT, "mountpoint", "/",
 	    PROP_INHERIT, ZFS_TYPE_FILESYSTEM, "<path> | legacy | none",
 	    "MOUNTPOINT");
@@ -342,6 +344,8 @@
 	    ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME, "<size>", "USEDREFRESERV");
 	zprop_register_number(ZFS_PROP_USERREFS, "userrefs", 0, PROP_READONLY,
 	    ZFS_TYPE_SNAPSHOT, "<count>", "USERREFS");
+	zprop_register_number(ZFS_PROP_WRITTEN, "written", 0, PROP_READONLY,
+	    ZFS_TYPE_DATASET, "<size>", "WRITTEN");
 
 	/* default number properties */
 	zprop_register_number(ZFS_PROP_QUOTA, "quota", 0, PROP_DEFAULT,
@@ -468,6 +472,18 @@
 }
 
 /*
+ * Returns true if this is a valid written@ property.
+ * Note that after the @, any character is valid (eg, another @, for
+ * written at pool/fs at origin).
+ */
+boolean_t
+zfs_prop_written(const char *name)
+{
+	static const char *prefix = "written@";
+	return (strncmp(name, prefix, strlen(prefix)) == 0);
+}
+
+/*
  * Tables of index types, plus functions to convert between the user view
  * (strings) and internal representation (uint64_t).
  */
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/cddl/contrib/opensolaris/common/zfs/zfs_prop.h
--- a/head/sys/cddl/contrib/opensolaris/common/zfs/zfs_prop.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/cddl/contrib/opensolaris/common/zfs/zfs_prop.h	Tue Dec 06 20:26:16 2011 +0200
@@ -121,6 +121,8 @@
 const char *zprop_values(int, zfs_type_t);
 size_t zprop_width(int, boolean_t *, zfs_type_t);
 boolean_t zprop_valid_for_type(int, zfs_type_t);
+boolean_t zfs_prop_written(const char *name);
+
 
 #ifdef	__cplusplus
 }
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/cddl/contrib/opensolaris/common/zfs/zpool_prop.c
--- a/head/sys/cddl/contrib/opensolaris/common/zfs/zpool_prop.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/cddl/contrib/opensolaris/common/zfs/zpool_prop.c	Tue Dec 06 20:26:16 2011 +0200
@@ -20,6 +20,8 @@
  */
 /*
  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright 2011 Nexenta Systems, Inc. All rights reserved.
+ * Copyright (c) 2011 by Delphix. All rights reserved.
  */
 
 #include <sys/zio.h>
@@ -69,6 +71,8 @@
 	    ZFS_TYPE_POOL, "<filesystem>", "BOOTFS");
 	zprop_register_string(ZPOOL_PROP_CACHEFILE, "cachefile", NULL,
 	    PROP_DEFAULT, ZFS_TYPE_POOL, "<file> | none", "CACHEFILE");
+	zprop_register_string(ZPOOL_PROP_COMMENT, "comment", NULL,
+	    PROP_DEFAULT, ZFS_TYPE_POOL, "<comment-string>", "COMMENT");
 
 	/* readonly number properties */
 	zprop_register_number(ZPOOL_PROP_SIZE, "size", 0, PROP_READONLY,
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/arc.c
--- a/head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/arc.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/arc.c	Tue Dec 06 20:26:16 2011 +0200
@@ -20,6 +20,8 @@
  */
 /*
  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright 2011 Nexenta Systems, Inc.  All rights reserved.
+ * Copyright (c) 2011 by Delphix. All rights reserved.
  */
 
 /*
@@ -1365,7 +1367,7 @@
 	ASSERT(BUF_EMPTY(hdr));
 	hdr->b_size = size;
 	hdr->b_type = type;
-	hdr->b_spa = spa_guid(spa);
+	hdr->b_spa = spa_load_guid(spa);
 	hdr->b_state = arc_anon;
 	hdr->b_arc_access = 0;
 	buf = kmem_cache_alloc(buf_cache, KM_PUSHPAGE);
@@ -2146,7 +2148,7 @@
 	uint64_t guid = 0;
 
 	if (spa)
-		guid = spa_guid(spa);
+		guid = spa_load_guid(spa);
 
 	while (arc_mru->arcs_lsize[ARC_BUFC_DATA]) {
 		(void) arc_evict(arc_mru, guid, -1, FALSE, ARC_BUFC_DATA);
@@ -2936,7 +2938,7 @@
 	arc_buf_t *buf;
 	kmutex_t *hash_lock;
 	zio_t *rzio;
-	uint64_t guid = spa_guid(spa);
+	uint64_t guid = spa_load_guid(spa);
 
 top:
 	hdr = buf_hash_find(guid, BP_IDENTITY(bp), BP_PHYSICAL_BIRTH(bp),
@@ -4593,7 +4595,7 @@
 	boolean_t have_lock, full;
 	l2arc_write_callback_t *cb;
 	zio_t *pio, *wzio;
-	uint64_t guid = spa_guid(spa);
+	uint64_t guid = spa_load_guid(spa);
 	int try;
 
 	ASSERT(dev->l2ad_vdev != NULL);
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/bpobj.c
--- a/head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/bpobj.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/bpobj.c	Tue Dec 06 20:26:16 2011 +0200
@@ -20,11 +20,13 @@
  */
 /*
  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011 by Delphix. All rights reserved.
  */
 
 #include <sys/bpobj.h>
 #include <sys/zfs_context.h>
 #include <sys/refcount.h>
+#include <sys/dsl_pool.h>
 
 uint64_t
 bpobj_alloc(objset_t *os, int blocksize, dmu_tx_t *tx)
@@ -440,7 +442,10 @@
 	struct space_range_arg *sra = arg;
 
 	if (bp->blk_birth > sra->mintxg && bp->blk_birth <= sra->maxtxg) {
-		sra->used += bp_get_dsize_sync(sra->spa, bp);
+		if (dsl_pool_sync_context(spa_get_dsl(sra->spa)))
+			sra->used += bp_get_dsize_sync(sra->spa, bp);
+		else
+			sra->used += bp_get_dsize(sra->spa, bp);
 		sra->comp += BP_GET_PSIZE(bp);
 		sra->uncomp += BP_GET_UCSIZE(bp);
 	}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/dmu_send.c
--- a/head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/dmu_send.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/dmu_send.c	Tue Dec 06 20:26:16 2011 +0200
@@ -20,9 +20,11 @@
  */
 /*
  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011 by Delphix. All rights reserved.
  */
 /*
  * Copyright 2011 Nexenta Systems, Inc. All rights reserved.
+ * Copyright (c) 2011 by Delphix. All rights reserved.
  */
 
 #include <sys/dmu.h>
@@ -47,6 +49,9 @@
 #include <sys/ddt.h>
 #include <sys/zfs_onexit.h>
 
+/* Set this tunable to TRUE to replace corrupt data with 0x2f5baddb10c */
+int zfs_send_corrupt_data = B_FALSE;
+
 static char *dmu_recv_tag = "dmu_recv_tag";
 
 /*
@@ -384,8 +389,20 @@
 
 		if (dsl_read(NULL, spa, bp, pbuf,
 		    arc_getbuf_func, &abuf, ZIO_PRIORITY_ASYNC_READ,
-		    ZIO_FLAG_CANFAIL, &aflags, zb) != 0)
-			return (EIO);
+		    ZIO_FLAG_CANFAIL, &aflags, zb) != 0) {
+			if (zfs_send_corrupt_data) {
+				/* Send a block filled with 0x"zfs badd bloc" */
+				abuf = arc_buf_alloc(spa, blksz, &abuf,
+				    ARC_BUFC_DATA);
+				uint64_t *ptr;
+				for (ptr = abuf->b_data;
+				    (char *)ptr < (char *)abuf->b_data + blksz;
+				    ptr++)
+					*ptr = 0x2f5baddb10c;
+			} else {
+				return (EIO);
+			}
+		}
 
 		err = dump_data(ba, type, zb->zb_object, zb->zb_blkid * blksz,
 		    blksz, bp, abuf->b_data);
@@ -515,6 +532,86 @@
 	return (0);
 }
 
+int
+dmu_send_estimate(objset_t *tosnap, objset_t *fromsnap, boolean_t fromorigin,
+    uint64_t *sizep)
+{
+	dsl_dataset_t *ds = tosnap->os_dsl_dataset;
+	dsl_dataset_t *fromds = fromsnap ? fromsnap->os_dsl_dataset : NULL;
+	dsl_pool_t *dp = ds->ds_dir->dd_pool;
+	int err;
+	uint64_t size;
+
+	/* tosnap must be a snapshot */
+	if (ds->ds_phys->ds_next_snap_obj == 0)
+		return (EINVAL);
+
+	/* fromsnap must be an earlier snapshot from the same fs as tosnap */
+	if (fromds && (ds->ds_dir != fromds->ds_dir ||
+	    fromds->ds_phys->ds_creation_txg >= ds->ds_phys->ds_creation_txg))
+		return (EXDEV);
+
+	if (fromorigin) {
+		if (fromsnap)
+			return (EINVAL);
+
+		if (dsl_dir_is_clone(ds->ds_dir)) {
+			rw_enter(&dp->dp_config_rwlock, RW_READER);
+			err = dsl_dataset_hold_obj(dp,
+			    ds->ds_dir->dd_phys->dd_origin_obj, FTAG, &fromds);
+			rw_exit(&dp->dp_config_rwlock);
+			if (err)
+				return (err);
+		} else {
+			fromorigin = B_FALSE;
+		}
+	}
+
+	/* Get uncompressed size estimate of changed data. */
+	if (fromds == NULL) {
+		size = ds->ds_phys->ds_uncompressed_bytes;
+	} else {
+		uint64_t used, comp;
+		err = dsl_dataset_space_written(fromds, ds,
+		    &used, &comp, &size);
+		if (fromorigin)
+			dsl_dataset_rele(fromds, FTAG);
+		if (err)
+			return (err);
+	}
+
+	/*
+	 * Assume that space (both on-disk and in-stream) is dominated by
+	 * data.  We will adjust for indirect blocks and the copies property,
+	 * but ignore per-object space used (eg, dnodes and DRR_OBJECT records).
+	 */
+
+	/*
+	 * Subtract out approximate space used by indirect blocks.
+	 * Assume most space is used by data blocks (non-indirect, non-dnode).
+	 * Assume all blocks are recordsize.  Assume ditto blocks and
+	 * internal fragmentation counter out compression.
+	 *
+	 * Therefore, space used by indirect blocks is sizeof(blkptr_t) per
+	 * block, which we observe in practice.
+	 */
+	uint64_t recordsize;
+	rw_enter(&dp->dp_config_rwlock, RW_READER);
+	err = dsl_prop_get_ds(ds, "recordsize",
+	    sizeof (recordsize), 1, &recordsize, NULL);
+	rw_exit(&dp->dp_config_rwlock);
+	if (err)
+		return (err);
+	size -= size / recordsize * sizeof (blkptr_t);
+
+	/* Add in the space for the record associated with each block. */
+	size += size / recordsize * sizeof (dmu_replay_record_t);
+
+	*sizep = size;
+
+	return (0);
+}
+
 struct recvbeginsyncarg {
 	const char *tofs;
 	const char *tosnap;
@@ -1540,7 +1637,7 @@
 {
 	struct recvendsyncarg resa;
 	dsl_dataset_t *ds = drc->drc_logical_ds;
-	int err;
+	int err, myerr;
 
 	/*
 	 * XXX hack; seems the ds is still dirty and dsl_pool_zil_clean()
@@ -1578,7 +1675,8 @@
 	if (err == 0 && drc->drc_guid_to_ds_map != NULL)
 		(void) add_ds_to_guidmap(drc->drc_guid_to_ds_map, ds);
 	dsl_dataset_disown(ds, dmu_recv_tag);
-	(void) dsl_dataset_destroy(drc->drc_real_ds, dmu_recv_tag, B_FALSE);
+	myerr = dsl_dataset_destroy(drc->drc_real_ds, dmu_recv_tag, B_FALSE);
+	ASSERT3U(myerr, ==, 0);
 	return (err);
 }
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/dsl_dataset.c
--- a/head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/dsl_dataset.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/dsl_dataset.c	Tue Dec 06 20:26:16 2011 +0200
@@ -23,6 +23,7 @@
  * Copyright (c) 2011 by Delphix. All rights reserved.
  * Copyright (c) 2011 Pawel Jakub Dawidek <pawel at dawidek.net>.
  * All rights reserved.
+ * Portions Copyright (c) 2011 Martin Matuska <mm at FreeBSD.org>
  */
 
 #include <sys/dmu_objset.h>
@@ -908,69 +909,95 @@
 	return (dsobj);
 }
 
+#ifdef __FreeBSD__
+/* FreeBSD ioctl compat begin */
 struct destroyarg {
-	dsl_sync_task_group_t *dstg;
-	char *snapname;
-	char *failed;
-	boolean_t defer;
+	nvlist_t *nvl;
+	const char *snapname;
 };
 
 static int
-dsl_snapshot_destroy_one(const char *name, void *arg)
+dsl_check_snap_cb(const char *name, void *arg)
 {
 	struct destroyarg *da = arg;
 	dsl_dataset_t *ds;
+	char *dsname;
+
+	dsname = kmem_asprintf("%s@%s", name, da->snapname);
+	VERIFY(nvlist_add_boolean(da->nvl, dsname) == 0);
+
+	return (0);
+}
+
+int
+dmu_get_recursive_snaps_nvl(const char *fsname, const char *snapname,
+    nvlist_t *snaps)
+{
+	struct destroyarg *da;
 	int err;
-	char *dsname;
-
-	dsname = kmem_asprintf("%s@%s", name, da->snapname);
-	err = dsl_dataset_own(dsname, B_TRUE, da->dstg, &ds);
-	strfree(dsname);
-	if (err == 0) {
-		struct dsl_ds_destroyarg *dsda;
-
-		dsl_dataset_make_exclusive(ds, da->dstg);
-		dsda = kmem_zalloc(sizeof (struct dsl_ds_destroyarg), KM_SLEEP);
-		dsda->ds = ds;
-		dsda->defer = da->defer;
-		dsl_sync_task_create(da->dstg, dsl_dataset_destroy_check,
-		    dsl_dataset_destroy_sync, dsda, da->dstg, 0);
-	} else if (err == ENOENT) {
-		err = 0;
-	} else {
-		(void) strcpy(da->failed, name);
-	}
+
+	da = kmem_zalloc(sizeof (struct destroyarg), KM_SLEEP);
+	da->nvl = snaps;
+	da->snapname = snapname;
+	err = dmu_objset_find(fsname, dsl_check_snap_cb, da,
+	    DS_FIND_CHILDREN);
+	kmem_free(da, sizeof (struct destroyarg));
+
 	return (err);
 }
+/* FreeBSD ioctl compat end */
+#endif /* __FreeBSD__ */
 
 /*
- * Destroy 'snapname' in all descendants of 'fsname'.
+ * The snapshots must all be in the same pool.
  */
-#pragma weak dmu_snapshots_destroy = dsl_snapshots_destroy
 int
-dsl_snapshots_destroy(char *fsname, char *snapname, boolean_t defer)
+dmu_snapshots_destroy_nvl(nvlist_t *snaps, boolean_t defer, char *failed)
 {
 	int err;
-	struct destroyarg da;
 	dsl_sync_task_t *dst;
 	spa_t *spa;
-
-	err = spa_open(fsname, &spa, FTAG);
+	nvpair_t *pair;
+	dsl_sync_task_group_t *dstg;
+
+	pair = nvlist_next_nvpair(snaps, NULL);
+	if (pair == NULL)
+		return (0);
+
+	err = spa_open(nvpair_name(pair), &spa, FTAG);
 	if (err)
 		return (err);
-	da.dstg = dsl_sync_task_group_create(spa_get_dsl(spa));
-	da.snapname = snapname;
-	da.failed = fsname;
-	da.defer = defer;
-
-	err = dmu_objset_find(fsname,
-	    dsl_snapshot_destroy_one, &da, DS_FIND_CHILDREN);
+	dstg = dsl_sync_task_group_create(spa_get_dsl(spa));
+
+	for (pair = nvlist_next_nvpair(snaps, NULL); pair != NULL;
+	    pair = nvlist_next_nvpair(snaps, pair)) {
+		dsl_dataset_t *ds;
+		int err;
+
+		err = dsl_dataset_own(nvpair_name(pair), B_TRUE, dstg, &ds);
+		if (err == 0) {
+			struct dsl_ds_destroyarg *dsda;
+
+			dsl_dataset_make_exclusive(ds, dstg);
+			dsda = kmem_zalloc(sizeof (struct dsl_ds_destroyarg),
+			    KM_SLEEP);
+			dsda->ds = ds;
+			dsda->defer = defer;
+			dsl_sync_task_create(dstg, dsl_dataset_destroy_check,
+			    dsl_dataset_destroy_sync, dsda, dstg, 0);
+		} else if (err == ENOENT) {
+			err = 0;
+		} else {
+			(void) strcpy(failed, nvpair_name(pair));
+			break;
+		}
+	}
 
 	if (err == 0)
-		err = dsl_sync_task_group_wait(da.dstg);
-
-	for (dst = list_head(&da.dstg->dstg_tasks); dst;
-	    dst = list_next(&da.dstg->dstg_tasks, dst)) {
+		err = dsl_sync_task_group_wait(dstg);
+
+	for (dst = list_head(&dstg->dstg_tasks); dst;
+	    dst = list_next(&dstg->dstg_tasks, dst)) {
 		struct dsl_ds_destroyarg *dsda = dst->dst_arg1;
 		dsl_dataset_t *ds = dsda->ds;
 
@@ -978,17 +1005,17 @@
 		 * Return the file system name that triggered the error
 		 */
 		if (dst->dst_err) {
-			dsl_dataset_name(ds, fsname);
-			*strchr(fsname, '@') = '\0';
+			dsl_dataset_name(ds, failed);
 		}
 		ASSERT3P(dsda->rm_origin, ==, NULL);
-		dsl_dataset_disown(ds, da.dstg);
+		dsl_dataset_disown(ds, dstg);
 		kmem_free(dsda, sizeof (struct dsl_ds_destroyarg));
 	}
 
-	dsl_sync_task_group_destroy(da.dstg);
+	dsl_sync_task_group_destroy(dstg);
 	spa_close(spa, FTAG);
 	return (err);
+
 }
 
 static boolean_t
@@ -2150,6 +2177,55 @@
 	dmu_objset_sync(ds->ds_objset, zio, tx);
 }
 
+static void
+get_clones_stat(dsl_dataset_t *ds, nvlist_t *nv)
+{
+	uint64_t count = 0;
+	objset_t *mos = ds->ds_dir->dd_pool->dp_meta_objset;
+	zap_cursor_t zc;
+	zap_attribute_t za;
+	nvlist_t *propval;
+	nvlist_t *val;
+
+	rw_enter(&ds->ds_dir->dd_pool->dp_config_rwlock, RW_READER);
+	VERIFY(nvlist_alloc(&propval, NV_UNIQUE_NAME, KM_SLEEP) == 0);
+	VERIFY(nvlist_alloc(&val, NV_UNIQUE_NAME, KM_SLEEP) == 0);
+
+	/*
+	 * There may me missing entries in ds_next_clones_obj
+	 * due to a bug in a previous version of the code.
+	 * Only trust it if it has the right number of entries.
+	 */
+	if (ds->ds_phys->ds_next_clones_obj != 0) {
+		ASSERT3U(0, ==, zap_count(mos, ds->ds_phys->ds_next_clones_obj,
+		    &count));
+	}
+	if (count != ds->ds_phys->ds_num_children - 1) {
+		goto fail;
+	}
+	for (zap_cursor_init(&zc, mos, ds->ds_phys->ds_next_clones_obj);
+	    zap_cursor_retrieve(&zc, &za) == 0;
+	    zap_cursor_advance(&zc)) {
+		dsl_dataset_t *clone;
+		char buf[ZFS_MAXNAMELEN];
+		if (dsl_dataset_hold_obj(ds->ds_dir->dd_pool,
+		    za.za_first_integer, FTAG, &clone) != 0) {
+			goto fail;
+		}
+		dsl_dir_name(clone->ds_dir, buf);
+		VERIFY(nvlist_add_boolean(val, buf) == 0);
+		dsl_dataset_rele(clone, FTAG);
+	}
+	zap_cursor_fini(&zc);
+	VERIFY(nvlist_add_nvlist(propval, ZPROP_VALUE, val) == 0);
+	VERIFY(nvlist_add_nvlist(nv, zfs_prop_to_name(ZFS_PROP_CLONES),
+	    propval) == 0);
+fail:
+	nvlist_free(val);
+	nvlist_free(propval);
+	rw_exit(&ds->ds_dir->dd_pool->dp_config_rwlock);
+}
+
 void
 dsl_dataset_stats(dsl_dataset_t *ds, nvlist_t *nv)
 {
@@ -2180,6 +2256,26 @@
 	dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_DEFER_DESTROY,
 	    DS_IS_DEFER_DESTROY(ds) ? 1 : 0);
 
+	if (ds->ds_phys->ds_prev_snap_obj != 0) {
+		uint64_t written, comp, uncomp;
+		dsl_pool_t *dp = ds->ds_dir->dd_pool;
+		dsl_dataset_t *prev;
+
+		rw_enter(&dp->dp_config_rwlock, RW_READER);
+		int err = dsl_dataset_hold_obj(dp,
+		    ds->ds_phys->ds_prev_snap_obj, FTAG, &prev);
+		rw_exit(&dp->dp_config_rwlock);
+		if (err == 0) {
+			err = dsl_dataset_space_written(prev, ds, &written,
+			    &comp, &uncomp);
+			dsl_dataset_rele(prev, FTAG);
+			if (err == 0) {
+				dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_WRITTEN,
+				    written);
+			}
+		}
+	}
+
 	ratio = ds->ds_phys->ds_compressed_bytes == 0 ? 100 :
 	    (ds->ds_phys->ds_uncompressed_bytes * 100 /
 	    ds->ds_phys->ds_compressed_bytes);
@@ -2193,6 +2289,8 @@
 		dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_USED,
 		    ds->ds_phys->ds_unique_bytes);
 		dsl_prop_nvlist_add_uint64(nv, ZFS_PROP_COMPRESSRATIO, ratio);
+
+		get_clones_stat(ds, nv);
 	}
 }
 
@@ -4025,7 +4123,7 @@
 }
 
 /*
- * Note, this fuction is used as the callback for dmu_objset_find().  We
+ * Note, this function is used as the callback for dmu_objset_find().  We
  * always return 0 so that we will continue to find and process
  * inconsistent datasets, even if we encounter an error trying to
  * process one of them.
@@ -4044,3 +4142,151 @@
 	}
 	return (0);
 }
+
+/*
+ * Return (in *usedp) the amount of space written in new that is not
+ * present in oldsnap.  New may be a snapshot or the head.  Old must be
+ * a snapshot before new, in new's filesystem (or its origin).  If not then
+ * fail and return EINVAL.
+ *
+ * The written space is calculated by considering two components:  First, we
+ * ignore any freed space, and calculate the written as new's used space
+ * minus old's used space.  Next, we add in the amount of space that was freed
+ * between the two snapshots, thus reducing new's used space relative to old's.
+ * Specifically, this is the space that was born before old->ds_creation_txg,
+ * and freed before new (ie. on new's deadlist or a previous deadlist).
+ *
+ * space freed                         [---------------------]
+ * snapshots                       ---O-------O--------O-------O------
+ *                                         oldsnap            new
+ */
+int
+dsl_dataset_space_written(dsl_dataset_t *oldsnap, dsl_dataset_t *new,
+    uint64_t *usedp, uint64_t *compp, uint64_t *uncompp)
+{
+	int err = 0;
+	uint64_t snapobj;
+	dsl_pool_t *dp = new->ds_dir->dd_pool;
+
+	*usedp = 0;
+	*usedp += new->ds_phys->ds_used_bytes;
+	*usedp -= oldsnap->ds_phys->ds_used_bytes;
+
+	*compp = 0;
+	*compp += new->ds_phys->ds_compressed_bytes;
+	*compp -= oldsnap->ds_phys->ds_compressed_bytes;
+
+	*uncompp = 0;
+	*uncompp += new->ds_phys->ds_uncompressed_bytes;
+	*uncompp -= oldsnap->ds_phys->ds_uncompressed_bytes;
+
+	rw_enter(&dp->dp_config_rwlock, RW_READER);
+	snapobj = new->ds_object;
+	while (snapobj != oldsnap->ds_object) {
+		dsl_dataset_t *snap;
+		uint64_t used, comp, uncomp;
+
+		err = dsl_dataset_hold_obj(dp, snapobj, FTAG, &snap);
+		if (err != 0)
+			break;
+
+		if (snap->ds_phys->ds_prev_snap_txg ==
+		    oldsnap->ds_phys->ds_creation_txg) {
+			/*
+			 * The blocks in the deadlist can not be born after
+			 * ds_prev_snap_txg, so get the whole deadlist space,
+			 * which is more efficient (especially for old-format
+			 * deadlists).  Unfortunately the deadlist code
+			 * doesn't have enough information to make this
+			 * optimization itself.
+			 */
+			dsl_deadlist_space(&snap->ds_deadlist,
+			    &used, &comp, &uncomp);
+		} else {
+			dsl_deadlist_space_range(&snap->ds_deadlist,
+			    0, oldsnap->ds_phys->ds_creation_txg,
+			    &used, &comp, &uncomp);
+		}
+		*usedp += used;
+		*compp += comp;
+		*uncompp += uncomp;
+
+		/*
+		 * If we get to the beginning of the chain of snapshots
+		 * (ds_prev_snap_obj == 0) before oldsnap, then oldsnap
+		 * was not a snapshot of/before new.
+		 */
+		snapobj = snap->ds_phys->ds_prev_snap_obj;
+		dsl_dataset_rele(snap, FTAG);
+		if (snapobj == 0) {
+			err = EINVAL;
+			break;
+		}
+
+	}
+	rw_exit(&dp->dp_config_rwlock);
+	return (err);
+}
+
+/*
+ * Return (in *usedp) the amount of space that will be reclaimed if firstsnap,
+ * lastsnap, and all snapshots in between are deleted.
+ *
+ * blocks that would be freed            [---------------------------]
+ * snapshots                       ---O-------O--------O-------O--------O
+ *                                        firstsnap        lastsnap
+ *
+ * This is the set of blocks that were born after the snap before firstsnap,
+ * (birth > firstsnap->prev_snap_txg) and died before the snap after the
+ * last snap (ie, is on lastsnap->ds_next->ds_deadlist or an earlier deadlist).
+ * We calculate this by iterating over the relevant deadlists (from the snap
+ * after lastsnap, backward to the snap after firstsnap), summing up the
+ * space on the deadlist that was born after the snap before firstsnap.
+ */
+int
+dsl_dataset_space_wouldfree(dsl_dataset_t *firstsnap,
+    dsl_dataset_t *lastsnap,
+    uint64_t *usedp, uint64_t *compp, uint64_t *uncompp)
+{
+	int err = 0;
+	uint64_t snapobj;
+	dsl_pool_t *dp = firstsnap->ds_dir->dd_pool;
+
+	ASSERT(dsl_dataset_is_snapshot(firstsnap));
+	ASSERT(dsl_dataset_is_snapshot(lastsnap));
+
+	/*
+	 * Check that the snapshots are in the same dsl_dir, and firstsnap
+	 * is before lastsnap.
+	 */
+	if (firstsnap->ds_dir != lastsnap->ds_dir ||
+	    firstsnap->ds_phys->ds_creation_txg >
+	    lastsnap->ds_phys->ds_creation_txg)
+		return (EINVAL);
+
+	*usedp = *compp = *uncompp = 0;
+
+	rw_enter(&dp->dp_config_rwlock, RW_READER);
+	snapobj = lastsnap->ds_phys->ds_next_snap_obj;
+	while (snapobj != firstsnap->ds_object) {
+		dsl_dataset_t *ds;
+		uint64_t used, comp, uncomp;
+
+		err = dsl_dataset_hold_obj(dp, snapobj, FTAG, &ds);
+		if (err != 0)
+			break;
+
+		dsl_deadlist_space_range(&ds->ds_deadlist,
+		    firstsnap->ds_phys->ds_prev_snap_txg, UINT64_MAX,
+		    &used, &comp, &uncomp);
+		*usedp += used;
+		*compp += comp;
+		*uncompp += uncomp;
+
+		snapobj = ds->ds_phys->ds_prev_snap_obj;
+		ASSERT3U(snapobj, !=, 0);
+		dsl_dataset_rele(ds, FTAG);
+	}
+	rw_exit(&dp->dp_config_rwlock);
+	return (err);
+}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/dsl_deadlist.c
--- a/head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/dsl_deadlist.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/dsl_deadlist.c	Tue Dec 06 20:26:16 2011 +0200
@@ -20,6 +20,7 @@
  */
 /*
  * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011 by Delphix. All rights reserved.
  */
 
 #include <sys/dsl_dataset.h>
@@ -29,6 +30,26 @@
 #include <sys/zfs_context.h>
 #include <sys/dsl_pool.h>
 
+/*
+ * Deadlist concurrency:
+ *
+ * Deadlists can only be modified from the syncing thread.
+ *
+ * Except for dsl_deadlist_insert(), it can only be modified with the
+ * dp_config_rwlock held with RW_WRITER.
+ *
+ * The accessors (dsl_deadlist_space() and dsl_deadlist_space_range()) can
+ * be called concurrently, from open context, with the dl_config_rwlock held
+ * with RW_READER.
+ *
+ * Therefore, we only need to provide locking between dsl_deadlist_insert() and
+ * the accessors, protecting:
+ *     dl_phys->dl_used,comp,uncomp
+ *     and protecting the dl_tree from being loaded.
+ * The locking is provided by dl_lock.  Note that locking on the bpobj_t
+ * provides its own locking, and dl_oldfmt is immutable.
+ */
+
 static int
 dsl_deadlist_compare(const void *arg1, const void *arg2)
 {
@@ -309,14 +330,14 @@
  * return space used in the range (mintxg, maxtxg].
  * Includes maxtxg, does not include mintxg.
  * mintxg and maxtxg must both be keys in the deadlist (unless maxtxg is
- * UINT64_MAX).
+ * larger than any bp in the deadlist (eg. UINT64_MAX)).
  */
 void
 dsl_deadlist_space_range(dsl_deadlist_t *dl, uint64_t mintxg, uint64_t maxtxg,
     uint64_t *usedp, uint64_t *compp, uint64_t *uncompp)
 {
+	dsl_deadlist_entry_t *dle;
 	dsl_deadlist_entry_t dle_tofind;
-	dsl_deadlist_entry_t *dle;
 	avl_index_t where;
 
 	if (dl->dl_oldfmt) {
@@ -325,9 +346,10 @@
 		return;
 	}
 
-	dsl_deadlist_load_tree(dl);
 	*usedp = *compp = *uncompp = 0;
 
+	mutex_enter(&dl->dl_lock);
+	dsl_deadlist_load_tree(dl);
 	dle_tofind.dle_mintxg = mintxg;
 	dle = avl_find(&dl->dl_tree, &dle_tofind, &where);
 	/*
@@ -336,6 +358,7 @@
 	 */
 	ASSERT(dle != NULL ||
 	    avl_nearest(&dl->dl_tree, where, AVL_AFTER) == NULL);
+
 	for (; dle && dle->dle_mintxg < maxtxg;
 	    dle = AVL_NEXT(&dl->dl_tree, dle)) {
 		uint64_t used, comp, uncomp;
@@ -347,6 +370,7 @@
 		*compp += comp;
 		*uncompp += uncomp;
 	}
+	mutex_exit(&dl->dl_lock);
 }
 
 static void
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/dsl_deleg.c
--- a/head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/dsl_deleg.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/dsl_deleg.c	Tue Dec 06 20:26:16 2011 +0200
@@ -20,6 +20,7 @@
  */
 /*
  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011 by Delphix. All rights reserved.
  */
 
 /*
@@ -525,10 +526,12 @@
 }
 
 /*
- * Check if user has requested permission.
+ * Check if user has requested permission.  If descendent is set, must have
+ * descendent perms.
  */
 int
-dsl_deleg_access_impl(dsl_dataset_t *ds, const char *perm, cred_t *cr)
+dsl_deleg_access_impl(dsl_dataset_t *ds, boolean_t descendent, const char *perm,
+    cred_t *cr)
 {
 	dsl_dir_t *dd;
 	dsl_pool_t *dp;
@@ -549,7 +552,7 @@
 	    SPA_VERSION_DELEGATED_PERMS)
 		return (EPERM);
 
-	if (dsl_dataset_is_snapshot(ds)) {
+	if (dsl_dataset_is_snapshot(ds) || descendent) {
 		/*
 		 * Snapshots are treated as descendents only,
 		 * local permissions do not apply.
@@ -642,7 +645,7 @@
 	if (error)
 		return (error);
 
-	error = dsl_deleg_access_impl(ds, perm, cr);
+	error = dsl_deleg_access_impl(ds, B_FALSE, perm, cr);
 	dsl_dataset_rele(ds, FTAG);
 
 	return (error);
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/dsl_pool.c
--- a/head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/dsl_pool.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/dsl_pool.c	Tue Dec 06 20:26:16 2011 +0200
@@ -20,6 +20,7 @@
  */
 /*
  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011 by Delphix. All rights reserved.
  */
 
 #include <sys/dsl_pool.h>
@@ -316,7 +317,10 @@
 deadlist_enqueue_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
 {
 	dsl_deadlist_t *dl = arg;
+	dsl_pool_t *dp = dmu_objset_pool(dl->dl_os);
+	rw_enter(&dp->dp_config_rwlock, RW_READER);
 	dsl_deadlist_insert(dl, bp, tx);
+	rw_exit(&dp->dp_config_rwlock);
 	return (0);
 }
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/spa.c
--- a/head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/spa.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/spa.c	Tue Dec 06 20:26:16 2011 +0200
@@ -21,6 +21,7 @@
 
 /*
  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011 by Delphix. All rights reserved.
  */
 
 /*
@@ -212,6 +213,11 @@
 
 	spa_prop_add_list(*nvp, ZPOOL_PROP_GUID, NULL, spa_guid(spa), src);
 
+	if (spa->spa_comment != NULL) {
+		spa_prop_add_list(*nvp, ZPOOL_PROP_COMMENT, spa->spa_comment,
+		    0, ZPROP_SRC_LOCAL);
+	}
+
 	if (spa->spa_root != NULL)
 		spa_prop_add_list(*nvp, ZPOOL_PROP_ALTROOT, spa->spa_root,
 		    0, ZPROP_SRC_LOCAL);
@@ -351,7 +357,7 @@
 		char *propname, *strval;
 		uint64_t intval;
 		objset_t *os;
-		char *slash;
+		char *slash, *check;
 
 		propname = nvpair_name(elem);
 
@@ -471,6 +477,26 @@
 				error = EINVAL;
 			break;
 
+		case ZPOOL_PROP_COMMENT:
+			if ((error = nvpair_value_string(elem, &strval)) != 0)
+				break;
+			for (check = strval; *check != '\0'; check++) {
+				/*
+				 * The kernel doesn't have an easy isprint()
+				 * check.  For this kernel check, we merely
+				 * check ASCII apart from DEL.  Fix this if
+				 * there is an easy-to-use kernel isprint().
+				 */
+				if (*check >= 0x7f) {
+					error = EINVAL;
+					break;
+				}
+				check++;
+			}
+			if (strlen(strval) > ZPROP_MAX_COMMENT)
+				error = E2BIG;
+			break;
+
 		case ZPOOL_PROP_DEDUPDITTO:
 			if (spa_version(spa) < SPA_VERSION_DEDUP)
 				error = ENOTSUP;
@@ -572,6 +598,43 @@
 }
 
 /*
+ * Change the GUID for the pool.  This is done so that we can later
+ * re-import a pool built from a clone of our own vdevs.  We will modify
+ * the root vdev's guid, our own pool guid, and then mark all of our
+ * vdevs dirty.  Note that we must make sure that all our vdevs are
+ * online when we do this, or else any vdevs that weren't present
+ * would be orphaned from our pool.  We are also going to issue a
+ * sysevent to update any watchers.
+ */
+int
+spa_change_guid(spa_t *spa)
+{
+	uint64_t	oldguid, newguid;
+	uint64_t	txg;
+
+	if (!(spa_mode_global & FWRITE))
+		return (EROFS);
+
+	txg = spa_vdev_enter(spa);
+
+	if (spa->spa_root_vdev->vdev_state != VDEV_STATE_HEALTHY)
+		return (spa_vdev_exit(spa, NULL, txg, ENXIO));
+
+	oldguid = spa_guid(spa);
+	newguid = spa_generate_guid(NULL);
+	ASSERT3U(oldguid, !=, newguid);
+
+	spa->spa_root_vdev->vdev_guid = newguid;
+	spa->spa_root_vdev->vdev_guid_sum += (newguid - oldguid);
+
+	vdev_config_dirty(spa->spa_root_vdev);
+
+	spa_event_notify(spa, NULL, ESC_ZFS_POOL_REGUID);
+
+	return (spa_vdev_exit(spa, NULL, txg, 0));
+}
+
+/*
  * ==========================================================================
  * SPA state manipulation (open/create/destroy/import/export)
  * ==========================================================================
@@ -1025,6 +1088,11 @@
 
 	spa->spa_async_suspended = 0;
 
+	if (spa->spa_comment != NULL) {
+		spa_strfree(spa->spa_comment);
+		spa->spa_comment = NULL;
+	}
+
 	spa_config_exit(spa, SCL_ALL, FTAG);
 }
 
@@ -1742,6 +1810,7 @@
 {
 	nvlist_t *config = spa->spa_config;
 	char *ereport = FM_EREPORT_ZFS_POOL;
+	char *comment;
 	int error;
 	uint64_t pool_guid;
 	nvlist_t *nvl;
@@ -1749,6 +1818,10 @@
 	if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID, &pool_guid))
 		return (EINVAL);
 
+	ASSERT(spa->spa_comment == NULL);
+	if (nvlist_lookup_string(config, ZPOOL_CONFIG_COMMENT, &comment) == 0)
+		spa->spa_comment = spa_strdup(comment);
+
 	/*
 	 * Versioning wasn't explicitly added to the label until later, so if
 	 * it's not present treat it as the initial version.
@@ -1764,7 +1837,7 @@
 	    spa_guid_exists(pool_guid, 0)) {
 		error = EEXIST;
 	} else {
-		spa->spa_load_guid = pool_guid;
+		spa->spa_config_guid = pool_guid;
 
 		if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_SPLIT,
 		    &nvl) == 0) {
@@ -5380,6 +5453,20 @@
 			 * properties.
 			 */
 			break;
+		case ZPOOL_PROP_COMMENT:
+			VERIFY(nvpair_value_string(elem, &strval) == 0);
+			if (spa->spa_comment != NULL)
+				spa_strfree(spa->spa_comment);
+			spa->spa_comment = spa_strdup(strval);
+			/*
+			 * We need to dirty the configuration on all the vdevs
+			 * so that their labels get updated.  It's unnecessary
+			 * to do this for pool creation since the vdev's
+			 * configuratoin has already been dirtied.
+			 */
+			if (tx->tx_txg != TXG_INITIAL)
+				vdev_config_dirty(spa->spa_root_vdev);
+			break;
 		default:
 			/*
 			 * Set pool property values in the poolprops mos object.
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/spa_config.c
--- a/head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/spa_config.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/spa_config.c	Tue Dec 06 20:26:16 2011 +0200
@@ -21,6 +21,8 @@
 
 /*
  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright 2011 Nexenta Systems, Inc. All rights reserved.
+ * Copyright (c) 2011 by Delphix. All rights reserved.
  */
 
 #include <sys/zfs_context.h>
@@ -343,6 +345,10 @@
 	    txg) == 0);
 	VERIFY(nvlist_add_uint64(config, ZPOOL_CONFIG_POOL_GUID,
 	    spa_guid(spa)) == 0);
+	VERIFY(spa->spa_comment == NULL || nvlist_add_string(config,
+	    ZPOOL_CONFIG_COMMENT, spa->spa_comment) == 0);
+
+
 #ifdef	_KERNEL
 	hostid = zone_get_hostid(NULL);
 #else	/* _KERNEL */
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/spa_history.c
--- a/head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/spa_history.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/spa_history.c	Tue Dec 06 20:26:16 2011 +0200
@@ -21,6 +21,7 @@
 
 /*
  * Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011 by Delphix. All rights reserved.
  */
 
 #include <sys/spa.h>
@@ -101,11 +102,11 @@
 
 	/*
 	 * Figure out maximum size of history log.  We set it at
-	 * 1% of pool size, with a max of 32MB and min of 128KB.
+	 * 0.1% of pool size, with a max of 1G and min of 128KB.
 	 */
 	shpp->sh_phys_max_off =
-	    metaslab_class_get_dspace(spa_normal_class(spa)) / 100;
-	shpp->sh_phys_max_off = MIN(shpp->sh_phys_max_off, 32<<20);
+	    metaslab_class_get_dspace(spa_normal_class(spa)) / 1000;
+	shpp->sh_phys_max_off = MIN(shpp->sh_phys_max_off, 1<<30);
 	shpp->sh_phys_max_off = MAX(shpp->sh_phys_max_off, 128<<10);
 
 	dmu_buf_rele(dbp, FTAG);
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/spa_misc.c
--- a/head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/spa_misc.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/spa_misc.c	Tue Dec 06 20:26:16 2011 +0200
@@ -21,6 +21,7 @@
 /*
  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
  * Copyright (c) 2011 by Delphix. All rights reserved.
+ * Copyright 2011 Nexenta Systems, Inc.  All rights reserved.
  */
 
 #include <sys/zfs_context.h>
@@ -1308,13 +1309,24 @@
 	/*
 	 * If we fail to parse the config during spa_load(), we can go through
 	 * the error path (which posts an ereport) and end up here with no root
-	 * vdev.  We stash the original pool guid in 'spa_load_guid' to handle
+	 * vdev.  We stash the original pool guid in 'spa_config_guid' to handle
 	 * this case.
 	 */
 	if (spa->spa_root_vdev != NULL)
 		return (spa->spa_root_vdev->vdev_guid);
 	else
-		return (spa->spa_load_guid);
+		return (spa->spa_config_guid);
+}
+
+uint64_t
+spa_load_guid(spa_t *spa)
+{
+	/*
+	 * This is a GUID that exists solely as a reference for the
+	 * purposes of the arc.  It is generated at load time, and
+	 * is never written to persistent storage.
+	 */
+	return (spa->spa_load_guid);
 }
 
 uint64_t
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/dmu.h
--- a/head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/dmu.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/dmu.h	Tue Dec 06 20:26:16 2011 +0200
@@ -20,6 +20,7 @@
  */
 /*
  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011 by Delphix. All rights reserved.
  */
 /*
  * Copyright 2011 Nexenta Systems, Inc. All rights reserved.
@@ -194,7 +195,9 @@
 int dmu_objset_clone(const char *name, struct dsl_dataset *clone_origin,
     uint64_t flags);
 int dmu_objset_destroy(const char *name, boolean_t defer);
-int dmu_snapshots_destroy(char *fsname, char *snapname, boolean_t defer);
+int dmu_get_recursive_snaps_nvl(const char *fsname, const char *snapname,
+    struct nvlist *snaps);
+int dmu_snapshots_destroy_nvl(struct nvlist *snaps, boolean_t defer, char *);
 int dmu_objset_snapshot(char *fsname, char *snapname, char *tag,
     struct nvlist *props, boolean_t recursive, boolean_t temporary, int fd);
 int dmu_objset_rename(const char *name, const char *newname,
@@ -705,6 +708,8 @@
 
 int dmu_sendbackup(objset_t *tosnap, objset_t *fromsnap, boolean_t fromorigin,
     struct file *fp, offset_t *off);
+int dmu_send_estimate(objset_t *tosnap, objset_t *fromsnap,
+    boolean_t fromorigin, uint64_t *sizep);
 
 typedef struct dmu_recv_cookie {
 	/*
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/dsl_dataset.h
--- a/head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/dsl_dataset.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/dsl_dataset.h	Tue Dec 06 20:26:16 2011 +0200
@@ -22,6 +22,7 @@
  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
  * Copyright (c) 2011 Pawel Jakub Dawidek <pawel at dawidek.net>.
  * All rights reserved.
+ * Copyright (c) 2011 by Delphix. All rights reserved.
  */
 
 #ifndef	_SYS_DSL_DATASET_H
@@ -257,6 +258,10 @@
     uint64_t *refdbytesp, uint64_t *availbytesp,
     uint64_t *usedobjsp, uint64_t *availobjsp);
 uint64_t dsl_dataset_fsid_guid(dsl_dataset_t *ds);
+int dsl_dataset_space_written(dsl_dataset_t *oldsnap, dsl_dataset_t *new,
+    uint64_t *usedp, uint64_t *compp, uint64_t *uncompp);
+int dsl_dataset_space_wouldfree(dsl_dataset_t *firstsnap, dsl_dataset_t *last,
+    uint64_t *usedp, uint64_t *compp, uint64_t *uncompp);
 
 int dsl_dsobj_to_dsname(char *pname, uint64_t obj, char *buf);
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/dsl_deleg.h
--- a/head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/dsl_deleg.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/dsl_deleg.h	Tue Dec 06 20:26:16 2011 +0200
@@ -20,6 +20,7 @@
  */
 /*
  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011 by Delphix. All rights reserved.
  */
 
 #ifndef	_SYS_DSL_DELEG_H
@@ -64,7 +65,8 @@
 int dsl_deleg_get(const char *ddname, nvlist_t **nvp);
 int dsl_deleg_set(const char *ddname, nvlist_t *nvp, boolean_t unset);
 int dsl_deleg_access(const char *ddname, const char *perm, cred_t *cr);
-int dsl_deleg_access_impl(struct dsl_dataset *ds, const char *perm, cred_t *cr);
+int dsl_deleg_access_impl(struct dsl_dataset *ds, boolean_t descendent,
+    const char *perm, cred_t *cr);
 void dsl_deleg_set_create_perms(dsl_dir_t *dd, dmu_tx_t *tx, cred_t *cr);
 int dsl_deleg_can_allow(char *ddname, nvlist_t *nvp, cred_t *cr);
 int dsl_deleg_can_unallow(char *ddname, nvlist_t *nvp, cred_t *cr);
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/spa.h
--- a/head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/spa.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/spa.h	Tue Dec 06 20:26:16 2011 +0200
@@ -21,6 +21,7 @@
 /*
  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
  * Copyright (c) 2011 by Delphix. All rights reserved.
+ * Copyright 2011 Nexenta Systems, Inc.  All rights reserved.
  */
 
 #ifndef _SYS_SPA_H
@@ -578,6 +579,7 @@
 extern int spa_sync_pass(spa_t *spa);
 extern char *spa_name(spa_t *spa);
 extern uint64_t spa_guid(spa_t *spa);
+extern uint64_t spa_load_guid(spa_t *spa);
 extern uint64_t spa_last_synced_txg(spa_t *spa);
 extern uint64_t spa_first_txg(spa_t *spa);
 extern uint64_t spa_syncing_txg(spa_t *spa);
@@ -611,6 +613,7 @@
 extern uint64_t spa_generate_guid(spa_t *spa);
 extern void sprintf_blkptr(char *buf, const blkptr_t *bp);
 extern void spa_freeze(spa_t *spa);
+extern int spa_change_guid(spa_t *spa);
 extern void spa_upgrade(spa_t *spa, uint64_t version);
 extern void spa_evict_all(void);
 extern vdev_t *spa_lookup_by_guid(spa_t *spa, uint64_t guid,
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/spa_impl.h
--- a/head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/spa_impl.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/spa_impl.h	Tue Dec 06 20:26:16 2011 +0200
@@ -21,6 +21,7 @@
 /*
  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
  * Copyright (c) 2011 by Delphix. All rights reserved.
+ * Copyright 2011 Nexenta Systems, Inc.  All rights reserved.
  */
 
 #ifndef _SYS_SPA_IMPL_H
@@ -111,6 +112,7 @@
 	 * Fields protected by spa_namespace_lock.
 	 */
 	char		spa_name[MAXNAMELEN];	/* pool name */
+	char		*spa_comment;		/* comment */
 	avl_node_t	spa_avl;		/* node in spa_namespace_avl */
 	nvlist_t	*spa_config;		/* last synced config */
 	nvlist_t	*spa_config_syncing;	/* currently syncing config */
@@ -136,7 +138,8 @@
 	objset_t	*spa_meta_objset;	/* copy of dp->dp_meta_objset */
 	txg_list_t	spa_vdev_txg_list;	/* per-txg dirty vdev list */
 	vdev_t		*spa_root_vdev;		/* top-level vdev container */
-	uint64_t	spa_load_guid;		/* initial guid for spa_load */
+	uint64_t	spa_config_guid;	/* config pool guid */
+	uint64_t	spa_load_guid;		/* spa_load initialized guid */
 	list_t		spa_config_dirty_list;	/* vdevs with dirty config */
 	list_t		spa_state_dirty_list;	/* vdevs with dirty state */
 	spa_aux_vdev_t	spa_spares;		/* hot spares */
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/vdev.c
--- a/head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/vdev.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/vdev.c	Tue Dec 06 20:26:16 2011 +0200
@@ -21,6 +21,8 @@
 
 /*
  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright 2011 Nexenta Systems, Inc.  All rights reserved.
+ * Copyright (c) 2011 by Delphix. All rights reserved.
  */
 
 #include <sys/zfs_context.h>
@@ -297,6 +299,7 @@
 	if (spa->spa_root_vdev == NULL) {
 		ASSERT(ops == &vdev_root_ops);
 		spa->spa_root_vdev = vd;
+		spa->spa_load_guid = spa_generate_guid(NULL);
 	}
 
 	if (guid == 0 && ops != &vdev_hole_ops) {
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zap_micro.c
--- a/head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zap_micro.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zap_micro.c	Tue Dec 06 20:26:16 2011 +0200
@@ -20,6 +20,7 @@
  */
 /*
  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011 by Delphix. All rights reserved.
  */
 
 #include <sys/zio.h>
@@ -1414,7 +1415,7 @@
 	}
 
 	/*
-	 * We lock the zap with adding ==  FALSE. Because, if we pass
+	 * We lock the zap with adding == FALSE. Because, if we pass
 	 * the actual value of add, it could trigger a mzap_upgrade().
 	 * At present we are just evaluating the possibility of this operation
 	 * and hence we donot want to trigger an upgrade.
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_ioctl.c
--- a/head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_ioctl.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zfs_ioctl.c	Tue Dec 06 20:26:16 2011 +0200
@@ -23,6 +23,8 @@
  * Copyright (c) 2011 Pawel Jakub Dawidek <pawel at dawidek.net>.
  * All rights reserved.
  * Portions Copyright 2011 Martin Matuska <mm at FreeBSD.org>
+ * Copyright 2011 Nexenta Systems, Inc.  All rights reserved.
+ * Copyright (c) 2011 by Delphix. All rights reserved.
  */
 
 #include <sys/types.h>
@@ -348,17 +350,37 @@
 	return (zfs_dozonecheck_impl(dataset, zoned, cr));
 }
 
+/*
+ * If name ends in a '@', then require recursive permissions.
+ */
 int
 zfs_secpolicy_write_perms(const char *name, const char *perm, cred_t *cr)
 {
 	int error;
-
-	error = zfs_dozonecheck(name, cr);
+	boolean_t descendent = B_FALSE;
+	dsl_dataset_t *ds;
+	char *at;
+
+	at = strchr(name, '@');
+	if (at != NULL && at[1] == '\0') {
+		*at = '\0';
+		descendent = B_TRUE;
+	}
+
+	error = dsl_dataset_hold(name, FTAG, &ds);
+	if (at != NULL)
+		*at = '@';
+	if (error != 0)
+		return (error);
+
+	error = zfs_dozonecheck_ds(name, ds, cr);
 	if (error == 0) {
 		error = secpolicy_zfs(cr);
 		if (error)
-			error = dsl_deleg_access(name, perm, cr);
+			error = dsl_deleg_access_impl(ds, descendent, perm, cr);
 	}
+
+	dsl_dataset_rele(ds, FTAG);
 	return (error);
 }
 
@@ -372,7 +394,7 @@
 	if (error == 0) {
 		error = secpolicy_zfs(cr);
 		if (error)
-			error = dsl_deleg_access_impl(ds, perm, cr);
+			error = dsl_deleg_access_impl(ds, B_FALSE, perm, cr);
 	}
 	return (error);
 }
@@ -685,24 +707,14 @@
 /*
  * Destroying snapshots with delegated permissions requires
  * descendent mount and destroy permissions.
- * Reassemble the full filesystem at snap name so dsl_deleg_access()
- * can do the correct permission check.
- *
- * Since this routine is used when doing a recursive destroy of snapshots
- * and destroying snapshots requires descendent permissions, a successfull
- * check of the top level snapshot applies to snapshots of all descendent
- * datasets as well.
- *
- * The top level snapshot may not exist when doing a recursive destroy.
- * In this case fallback to permissions of the parent dataset.
  */
 static int
-zfs_secpolicy_destroy_snaps(zfs_cmd_t *zc, cred_t *cr)
+zfs_secpolicy_destroy_recursive(zfs_cmd_t *zc, cred_t *cr)
 {
 	int error;
 	char *dsname;
 
-	dsname = kmem_asprintf("%s@%s", zc->zc_name, zc->zc_value);
+	dsname = kmem_asprintf("%s@", zc->zc_name);
 
 	error = zfs_secpolicy_destroy_perms(dsname, cr);
 
@@ -1469,6 +1481,20 @@
 }
 
 static int
+zfs_ioc_pool_reguid(zfs_cmd_t *zc)
+{
+	spa_t *spa;
+	int error;
+
+	error = spa_open(zc->zc_name, &spa, FTAG);
+	if (error == 0) {
+		error = spa_change_guid(spa);
+		spa_close(spa, FTAG);
+	}
+	return (error);
+}
+
+static int
 zfs_ioc_dsobj_to_dsname(zfs_cmd_t *zc)
 {
 	int error;
@@ -1765,9 +1791,12 @@
 		 * inconsistent.  So this is a bit of a workaround...
 		 * XXX reading with out owning
 		 */
-		if (!zc->zc_objset_stats.dds_inconsistent) {
-			if (dmu_objset_type(os) == DMU_OST_ZVOL)
-				VERIFY(zvol_get_stats(os, nv) == 0);
+		if (!zc->zc_objset_stats.dds_inconsistent &&
+		    dmu_objset_type(os) == DMU_OST_ZVOL) {
+			error = zvol_get_stats(os, nv);
+			if (error == EIO)
+				return (error);
+			VERIFY3S(error, ==, 0);
 		}
 		error = put_nvlist(zc, nv);
 		nvlist_free(nv);
@@ -1978,8 +2007,7 @@
 		    NULL, &zc->zc_cookie);
 		if (error == ENOENT)
 			error = ESRCH;
-	} while (error == 0 && dataset_name_hidden(zc->zc_name) &&
-	    !(zc->zc_iflags & FKIOCTL));
+	} while (error == 0 && dataset_name_hidden(zc->zc_name));
 	dmu_objset_rele(os, FTAG);
 
 	/*
@@ -2257,6 +2285,8 @@
 				if (nvpair_type(propval) !=
 				    DATA_TYPE_UINT64_ARRAY)
 					err = EINVAL;
+			} else {
+				err = EINVAL;
 			}
 		} else if (err == 0) {
 			if (nvpair_type(propval) == DATA_TYPE_STRING) {
@@ -3124,25 +3154,62 @@
 
 /*
  * inputs:
- * zc_name		name of filesystem
- * zc_value		short name of snapshot
+ * zc_name		name of filesystem, snaps must be under it
+ * zc_nvlist_src[_size]	full names of snapshots to destroy
  * zc_defer_destroy	mark for deferred destroy
  *
- * outputs:	none
+ * outputs:
+ * zc_name		on failure, name of failed snapshot
  */
 static int
-zfs_ioc_destroy_snaps(zfs_cmd_t *zc)
+zfs_ioc_destroy_snaps_nvl(zfs_cmd_t *zc)
 {
-	int err;
-
-	if (snapshot_namecheck(zc->zc_value, NULL, NULL) != 0)
-		return (EINVAL);
-	err = dmu_objset_find(zc->zc_name,
-	    zfs_unmount_snap, zc->zc_value, DS_FIND_CHILDREN);
-	if (err)
+	int err, len;
+	nvlist_t *nvl;
+	nvpair_t *pair;
+
+	if ((err = get_nvlist(zc->zc_nvlist_src, zc->zc_nvlist_src_size,
+	    zc->zc_iflags, &nvl)) != 0) {
+#ifndef __FreeBSD__
 		return (err);
-	return (dmu_snapshots_destroy(zc->zc_name, zc->zc_value,
-	    zc->zc_defer_destroy));
+#else
+		/*
+		 * We are probably called by older binaries,
+		 * allocate and populate nvlist with recursive snapshots
+		 */
+		if (snapshot_namecheck(zc->zc_value, NULL, NULL) != 0)
+			return (EINVAL);
+		VERIFY(nvlist_alloc(&nvl, NV_UNIQUE_NAME, KM_SLEEP) == 0);
+		err = dmu_get_recursive_snaps_nvl(zc->zc_name,
+		    zc->zc_value, nvl);
+		if (err) {
+			nvlist_free(nvl);
+			return (err);
+		}
+#endif /* __FreeBSD__ */
+	}
+
+	len = strlen(zc->zc_name);
+	for (pair = nvlist_next_nvpair(nvl, NULL); pair != NULL;
+	    pair = nvlist_next_nvpair(nvl, pair)) {
+		const char *name = nvpair_name(pair);
+		/*
+		 * The snap name must be underneath the zc_name.  This ensures
+		 * that our permission checks were legitimate.
+		 */
+		if (strncmp(zc->zc_name, name, len) != 0 ||
+		    (name[len] != '@' && name[len] != '/')) {
+			nvlist_free(nvl);
+			return (EINVAL);
+		}
+
+		(void) zfs_unmount_snap(name, NULL);
+	}
+
+	err = dmu_snapshots_destroy_nvl(nvl, zc->zc_defer_destroy,
+	    zc->zc_name);
+	nvlist_free(nvl);
+	return (err);
 }
 
 /*
@@ -3789,6 +3856,8 @@
  * zc_obj	fromorigin flag (mutually exclusive with zc_fromobj)
  * zc_sendobj	objsetid of snapshot to send
  * zc_fromobj	objsetid of incremental fromsnap (may be zero)
+ * zc_guid	if set, estimate size of stream only.  zc_cookie is ignored.
+ *		output size in zc_objset_type.
  *
  * outputs: none
  */
@@ -3797,13 +3866,13 @@
 {
 	objset_t *fromsnap = NULL;
 	objset_t *tosnap;
-	file_t *fp;
 	int error;
 	offset_t off;
 	dsl_dataset_t *ds;
 	dsl_dataset_t *dsfrom = NULL;
 	spa_t *spa;
 	dsl_pool_t *dp;
+	boolean_t estimate = (zc->zc_guid != 0);
 
 	error = spa_open(zc->zc_name, &spa, FTAG);
 	if (error)
@@ -3844,20 +3913,25 @@
 		spa_close(spa, FTAG);
 	}
 
-	fp = getf(zc->zc_cookie);
-	if (fp == NULL) {
-		dsl_dataset_rele(ds, FTAG);
-		if (dsfrom)
-			dsl_dataset_rele(dsfrom, FTAG);
-		return (EBADF);
+	if (estimate) {
+		error = dmu_send_estimate(tosnap, fromsnap, zc->zc_obj,
+		    &zc->zc_objset_type);
+	} else {
+		file_t *fp = getf(zc->zc_cookie);
+		if (fp == NULL) {
+			dsl_dataset_rele(ds, FTAG);
+			if (dsfrom)
+				dsl_dataset_rele(dsfrom, FTAG);
+			return (EBADF);
+		}
+
+		off = fp->f_offset;
+		error = dmu_sendbackup(tosnap, fromsnap, zc->zc_obj, fp, &off);
+
+		if (off >= 0 && off <= MAXOFFSET_T)
+			fp->f_offset = off;
+		releasef(zc->zc_cookie);
 	}
-
-	off = fp->f_offset;
-	error = dmu_sendbackup(tosnap, fromsnap, zc->zc_obj, fp, &off);
-
-	if (off >= 0 && off <= MAXOFFSET_T)
-		fp->f_offset = off;
-	releasef(zc->zc_cookie);
 	if (dsfrom)
 		dsl_dataset_rele(dsfrom, FTAG);
 	dsl_dataset_rele(ds, FTAG);
@@ -4666,6 +4740,70 @@
 }
 
 /*
+ * inputs:
+ * zc_name		name of new filesystem or snapshot
+ * zc_value		full name of old snapshot
+ *
+ * outputs:
+ * zc_cookie		space in bytes
+ * zc_objset_type	compressed space in bytes
+ * zc_perm_action	uncompressed space in bytes
+ */
+static int
+zfs_ioc_space_written(zfs_cmd_t *zc)
+{
+	int error;
+	dsl_dataset_t *new, *old;
+
+	error = dsl_dataset_hold(zc->zc_name, FTAG, &new);
+	if (error != 0)
+		return (error);
+	error = dsl_dataset_hold(zc->zc_value, FTAG, &old);
+	if (error != 0) {
+		dsl_dataset_rele(new, FTAG);
+		return (error);
+	}
+
+	error = dsl_dataset_space_written(old, new, &zc->zc_cookie,
+	    &zc->zc_objset_type, &zc->zc_perm_action);
+	dsl_dataset_rele(old, FTAG);
+	dsl_dataset_rele(new, FTAG);
+	return (error);
+}
+
+/*
+ * inputs:
+ * zc_name		full name of last snapshot
+ * zc_value		full name of first snapshot
+ *
+ * outputs:
+ * zc_cookie		space in bytes
+ * zc_objset_type	compressed space in bytes
+ * zc_perm_action	uncompressed space in bytes
+ */
+static int
+zfs_ioc_space_snaps(zfs_cmd_t *zc)
+{
+	int error;
+	dsl_dataset_t *new, *old;
+
+	error = dsl_dataset_hold(zc->zc_name, FTAG, &new);
+	if (error != 0)
+		return (error);
+	error = dsl_dataset_hold(zc->zc_value, FTAG, &old);
+	if (error != 0) {
+		dsl_dataset_rele(new, FTAG);
+		return (error);
+	}
+
+	error = dsl_dataset_space_wouldfree(old, new, &zc->zc_cookie,
+	    &zc->zc_objset_type, &zc->zc_perm_action);
+	dsl_dataset_rele(old, FTAG);
+	dsl_dataset_rele(new, FTAG);
+	return (error);
+}
+
+/*
  * pool create, destroy, and export don't log the history as part of
  * zfsdev_ioctl, but rather zfs_ioc_pool_create, and zfs_ioc_pool_export
  * do the logging of those commands.
@@ -4739,7 +4877,7 @@
 	    B_TRUE },
 	{ zfs_ioc_rename, zfs_secpolicy_rename,	DATASET_NAME, B_TRUE, B_TRUE },
 	{ zfs_ioc_recv, zfs_secpolicy_receive, DATASET_NAME, B_TRUE, B_TRUE },
-	{ zfs_ioc_send, zfs_secpolicy_send, DATASET_NAME, B_TRUE, B_FALSE },
+	{ zfs_ioc_send, zfs_secpolicy_send, DATASET_NAME, B_FALSE, B_FALSE },
 	{ zfs_ioc_inject_fault,	zfs_secpolicy_inject, NO_NAME, B_FALSE,
 	    B_FALSE },
 	{ zfs_ioc_clear_fault, zfs_secpolicy_inject, NO_NAME, B_FALSE,
@@ -4751,7 +4889,7 @@
 	{ zfs_ioc_clear, zfs_secpolicy_config, POOL_NAME, B_TRUE, B_FALSE },
 	{ zfs_ioc_promote, zfs_secpolicy_promote, DATASET_NAME, B_TRUE,
 	    B_TRUE },
-	{ zfs_ioc_destroy_snaps, zfs_secpolicy_destroy_snaps, DATASET_NAME,
+	{ zfs_ioc_destroy_snaps_nvl, zfs_secpolicy_destroy_recursive, DATASET_NAME,
 	    B_TRUE, B_TRUE },
 	{ zfs_ioc_snapshot, zfs_secpolicy_snapshot, DATASET_NAME, B_TRUE,
 	    B_TRUE },
@@ -4795,7 +4933,13 @@
 	{ zfs_ioc_obj_to_stats, zfs_secpolicy_diff, DATASET_NAME, B_FALSE,
 	    B_TRUE },
 	{ zfs_ioc_jail, zfs_secpolicy_config, DATASET_NAME, B_TRUE, B_FALSE },
-	{ zfs_ioc_unjail, zfs_secpolicy_config, DATASET_NAME, B_TRUE, B_FALSE }
+	{ zfs_ioc_unjail, zfs_secpolicy_config, DATASET_NAME, B_TRUE, B_FALSE },
+	{ zfs_ioc_pool_reguid, zfs_secpolicy_config, POOL_NAME, B_TRUE,
+	    B_TRUE },
+	{ zfs_ioc_space_written, zfs_secpolicy_read, DATASET_NAME, B_FALSE,
+	    B_TRUE },
+	{ zfs_ioc_space_snaps, zfs_secpolicy_read, DATASET_NAME, B_FALSE,
+	    B_TRUE }
 };
 
 int
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/cddl/contrib/opensolaris/uts/common/sys/fs/zfs.h
--- a/head/sys/cddl/contrib/opensolaris/uts/common/sys/fs/zfs.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/cddl/contrib/opensolaris/uts/common/sys/fs/zfs.h	Tue Dec 06 20:26:16 2011 +0200
@@ -22,6 +22,7 @@
 /*
  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
  * Copyright (c) 2011 by Delphix. All rights reserved.
+ * Copyright 2011 Nexenta Systems, Inc.  All rights reserved.
  */
 
 /* Portions Copyright 2010 Robert Milkowski */
@@ -126,6 +127,8 @@
 	ZFS_PROP_MLSLABEL,
 	ZFS_PROP_SYNC,
 	ZFS_PROP_REFRATIO,
+	ZFS_PROP_WRITTEN,
+	ZFS_PROP_CLONES,
 	ZFS_NUM_PROPS
 } zfs_prop_t;
 
@@ -165,9 +168,13 @@
 	ZPOOL_PROP_FREE,
 	ZPOOL_PROP_ALLOCATED,
 	ZPOOL_PROP_READONLY,
+	ZPOOL_PROP_COMMENT,
 	ZPOOL_NUM_PROPS
 } zpool_prop_t;
 
+/* Small enough to not hog a whole line of printout in zpool(1M). */
+#define	ZPROP_MAX_COMMENT	32
+
 #define	ZPROP_CONT		-2
 #define	ZPROP_INVAL		-1
 
@@ -492,6 +499,7 @@
 #define	ZPOOL_CONFIG_SPLIT_LIST		"guid_list"
 #define	ZPOOL_CONFIG_REMOVING		"removing"
 #define	ZPOOL_CONFIG_RESILVERING	"resilvering"
+#define	ZPOOL_CONFIG_COMMENT		"comment"
 #define	ZPOOL_CONFIG_SUSPENDED		"suspended"	/* not stored on disk */
 #define	ZPOOL_CONFIG_TIMESTAMP		"timestamp"	/* not stored on disk */
 #define	ZPOOL_CONFIG_BOOTFS		"bootfs"	/* not stored on disk */
@@ -758,7 +766,7 @@
 #define	ZFS_IOC_ERROR_LOG		_IOWR('Z', 32, struct zfs_cmd)
 #define	ZFS_IOC_CLEAR			_IOWR('Z', 33, struct zfs_cmd)
 #define	ZFS_IOC_PROMOTE			_IOWR('Z', 34, struct zfs_cmd)
-#define	ZFS_IOC_DESTROY_SNAPS		_IOWR('Z', 35, struct zfs_cmd)
+#define	ZFS_IOC_DESTROY_SNAPS_NVL	_IOWR('Z', 35, struct zfs_cmd)
 #define	ZFS_IOC_SNAPSHOT		_IOWR('Z', 36, struct zfs_cmd)
 #define	ZFS_IOC_DSOBJ_TO_DSNAME		_IOWR('Z', 37, struct zfs_cmd)
 #define	ZFS_IOC_OBJ_TO_PATH		_IOWR('Z', 38, struct zfs_cmd)
@@ -783,6 +791,9 @@
 #define	ZFS_IOC_OBJ_TO_STATS		_IOWR('Z', 57, struct zfs_cmd)
 #define	ZFS_IOC_JAIL			_IOWR('Z', 58, struct zfs_cmd)
 #define	ZFS_IOC_UNJAIL			_IOWR('Z', 59, struct zfs_cmd)
+#define	ZFS_IOC_POOL_REGUID		_IOWR('Z', 60, struct zfs_cmd)
+#define	ZFS_IOC_SPACE_WRITTEN		_IOWR('Z', 61, struct zfs_cmd)
+#define	ZFS_IOC_SPACE_SNAPS		_IOWR('Z', 62, struct zfs_cmd)
 
 /*
  * Internal SPA load state.  Used by FMA diagnosis engine.
@@ -844,6 +855,7 @@
  *	ESC_ZFS_RESILVER_START
  *	ESC_ZFS_RESILVER_END
  *	ESC_ZFS_POOL_DESTROY
+ *	ESC_ZFS_POOL_REGUID
  *
  *		ZFS_EV_POOL_NAME	DATA_TYPE_STRING
  *		ZFS_EV_POOL_GUID	DATA_TYPE_UINT64
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/cddl/contrib/opensolaris/uts/common/sys/sysevent/eventdefs.h
--- a/head/sys/cddl/contrib/opensolaris/uts/common/sys/sysevent/eventdefs.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/cddl/contrib/opensolaris/uts/common/sys/sysevent/eventdefs.h	Tue Dec 06 20:26:16 2011 +0200
@@ -20,6 +20,7 @@
  */
 /*
  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright 2011 Nexenta Systems, Inc.  All rights reserved.
  */
 
 #ifndef	_SYS_SYSEVENT_EVENTDEFS_H
@@ -256,6 +257,7 @@
 #define	ESC_ZFS_SCRUB_FINISH		"ESC_ZFS_scrub_finish"
 #define	ESC_ZFS_VDEV_SPARE		"ESC_ZFS_vdev_spare"
 #define	ESC_ZFS_BOOTFS_VDEV_ATTACH	"ESC_ZFS_bootfs_vdev_attach"
+#define	ESC_ZFS_POOL_REGUID		"ESC_ZFS_pool_reguid"
 #define	ESC_ZFS_VDEV_AUTOEXPAND		"ESC_ZFS_vdev_autoexpand"
 
 /*
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/compat/linprocfs/linprocfs.c
--- a/head/sys/compat/linprocfs/linprocfs.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/compat/linprocfs/linprocfs.c	Tue Dec 06 20:26:16 2011 +0200
@@ -42,7 +42,7 @@
 #include "opt_compat.h"
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/compat/linprocfs/linprocfs.c 227836 2011-11-22 20:45:11Z trociny $");
+__FBSDID("$FreeBSD: head/sys/compat/linprocfs/linprocfs.c 228268 2011-12-04 21:43:13Z trociny $");
 
 #include <sys/param.h>
 #include <sys/queue.h>
@@ -967,7 +967,7 @@
 	int ret;
 
 	PROC_LOCK(p);
-	if ((ret = p_cansee(td, p)) != 0) {
+	if ((ret = p_candebug(td, p)) != 0) {
 		PROC_UNLOCK(p);
 		return (ret);
 	}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/conf/NOTES
--- a/head/sys/conf/NOTES	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/conf/NOTES	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-# $FreeBSD: head/sys/conf/NOTES 227845 2011-11-22 21:50:38Z luigi $
+# $FreeBSD: head/sys/conf/NOTES 228003 2011-11-26 18:02:39Z marius $
 #
 # NOTES -- Lines that can be cut/pasted into kernel and hints configs.
 #
@@ -1471,8 +1471,6 @@
 #      19160x/29160x, aic7770/aic78xx
 # ahd: Adaptec 29320/39320 Controllers.
 # aic: Adaptec 6260/6360, APA-1460 (PC Card), NEC PC9801-100 (C-BUS)
-# amd: Support for the AMD 53C974 SCSI host adapter chip as found on devices
-#      such as the Tekram DC-390(T).
 # bt:  Most Buslogic controllers: including BT-445, BT-54x, BT-64x, BT-74x,
 #      BT-75x, BT-946, BT-948, BT-956, BT-958, SDC3211B, SDC3211F, SDC3222F
 # esp: Emulex ESP, NCR 53C9x and QLogic FAS families based controllers
@@ -1512,7 +1510,6 @@
 device		ahb
 device		ahc
 device		ahd
-device		amd
 device		esp
 device		iscsi_initiator
 device		isp
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/conf/files
--- a/head/sys/conf/files	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/conf/files	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-# $FreeBSD: head/sys/conf/files 227845 2011-11-22 21:50:38Z luigi $
+# $FreeBSD: head/sys/conf/files 228110 2011-11-28 23:36:48Z jkim $
 #
 # The long compile-with and dependency lines are required because of
 # limitations in config: backslash-newline doesn't work in strings, and
@@ -172,6 +172,7 @@
 contrib/dev/acpica/disassembler/dmobject.c	optional acpi acpi_debug
 contrib/dev/acpica/disassembler/dmresrc.c	optional acpi acpi_debug
 contrib/dev/acpica/disassembler/dmresrcl.c	optional acpi acpi_debug
+contrib/dev/acpica/disassembler/dmresrcl2.c	optional acpi acpi_debug
 contrib/dev/acpica/disassembler/dmresrcs.c	optional acpi acpi_debug
 contrib/dev/acpica/disassembler/dmutils.c	optional acpi acpi_debug
 contrib/dev/acpica/disassembler/dmwalk.c	optional acpi acpi_debug
@@ -272,6 +273,7 @@
 contrib/dev/acpica/resources/rslist.c		optional acpi
 contrib/dev/acpica/resources/rsmemory.c		optional acpi
 contrib/dev/acpica/resources/rsmisc.c		optional acpi
+contrib/dev/acpica/resources/rsserial.c		optional acpi
 contrib/dev/acpica/resources/rsutils.c		optional acpi
 contrib/dev/acpica/resources/rsxface.c		optional acpi
 contrib/dev/acpica/tables/tbfadt.c		optional acpi
@@ -300,6 +302,7 @@
 contrib/dev/acpica/utilities/utstate.c		optional acpi
 contrib/dev/acpica/utilities/utxface.c		optional acpi
 contrib/dev/acpica/utilities/utxferror.c	optional acpi
+#contrib/dev/acpica/utilities/utxfmutex.c	optional acpi
 contrib/ipfilter/netinet/fil.c	optional ipfilter inet \
 	compile-with "${NORMAL_C} -I$S/contrib/ipfilter"
 contrib/ipfilter/netinet/ip_auth.c optional ipfilter inet \
@@ -517,7 +520,6 @@
 dev/aic7xxx/aic7xxx_pci.c	optional ahc pci
 dev/alc/if_alc.c		optional alc pci
 dev/ale/if_ale.c		optional ale pci
-dev/amd/amd.c			optional amd
 dev/amr/amr.c			optional amr
 dev/amr/amr_cam.c		optional amrp amr
 dev/amr/amr_disk.c		optional amr
@@ -779,13 +781,15 @@
 	ath_ar9287 \
 	compile-with "${NORMAL_C} -I$S/dev/ath -I$S/dev/ath/ath_hal"
 # ar9130 (depends upon ar5416) - also requires AH_SUPPORT_AR9130
-dev/ath/ath_hal/ar9001/ar9130_attach.c optional ath_hal | ath_ar9130 \
+#
+# Since this is an embedded MAC SoC, there's no need to compile it into the
+# default HAL.
+dev/ath/ath_hal/ar9001/ar9130_attach.c optional ath_ar9130 \
 	compile-with "${NORMAL_C} -I$S/dev/ath -I$S/dev/ath/ath_hal"
-dev/ath/ath_hal/ar9001/ar9130_phy.c optional ath_hal | ath_ar9130 \
+dev/ath/ath_hal/ar9001/ar9130_phy.c optional ath_ar9130 \
 	compile-with "${NORMAL_C} -I$S/dev/ath -I$S/dev/ath/ath_hal"
-dev/ath/ath_hal/ar9001/ar9130_eeprom.c optional ath_hal | ath_ar9130 \
+dev/ath/ath_hal/ar9001/ar9130_eeprom.c optional ath_ar9130 \
 	compile-with "${NORMAL_C} -I$S/dev/ath -I$S/dev/ath/ath_hal"
-
 # ar9160 (depends on ar5416)
 dev/ath/ath_hal/ar9001/ar9160_attach.c optional ath_hal | ath_ar9160 \
 	compile-with "${NORMAL_C} -I$S/dev/ath -I$S/dev/ath/ath_hal"
@@ -832,7 +836,8 @@
 	compile-with "${NORMAL_C} -I$S/dev/ath -I$S/dev/ath/ath_hal"
 dev/ath/ath_hal/ar5212/ar5413.c	optional ath_hal | ath_rf5413 \
 	compile-with "${NORMAL_C} -I$S/dev/ath -I$S/dev/ath/ath_hal"
-dev/ath/ath_hal/ar5416/ar2133.c optional ath_hal | ath_ar5416 | ath_ar9160 \
+dev/ath/ath_hal/ar5416/ar2133.c optional ath_hal | ath_ar5416 | \
+	ath_ar9130 | ath_ar9160 | ath_ar9280 \
 	compile-with "${NORMAL_C} -I$S/dev/ath -I$S/dev/ath/ath_hal"
 dev/ath/ath_hal/ar9002/ar9280.c optional ath_hal | ath_ar9280 | ath_ar9285 \
 	compile-with "${NORMAL_C} -I$S/dev/ath -I$S/dev/ath/ath_hal"
@@ -1683,37 +1688,6 @@
 dev/scd/scd_isa.c		optional scd isa
 dev/sdhci/sdhci.c		optional sdhci pci
 dev/sf/if_sf.c			optional sf pci
-dev/sfxge/common/efx_bootcfg.c	optional sfxge inet pci
-dev/sfxge/common/efx_ev.c	optional sfxge inet pci
-dev/sfxge/common/efx_filter.c	optional sfxge inet pci
-dev/sfxge/common/efx_intr.c	optional sfxge inet pci
-dev/sfxge/common/efx_mac.c	optional sfxge inet pci
-dev/sfxge/common/efx_mcdi.c	optional sfxge inet pci
-dev/sfxge/common/efx_mon.c	optional sfxge inet pci
-dev/sfxge/common/efx_nic.c	optional sfxge inet pci
-dev/sfxge/common/efx_nvram.c	optional sfxge inet pci
-dev/sfxge/common/efx_phy.c	optional sfxge inet pci
-dev/sfxge/common/efx_port.c	optional sfxge inet pci
-dev/sfxge/common/efx_rx.c	optional sfxge inet pci
-dev/sfxge/common/efx_sram.c	optional sfxge inet pci
-dev/sfxge/common/efx_tx.c	optional sfxge inet pci
-dev/sfxge/common/efx_vpd.c	optional sfxge inet pci
-dev/sfxge/common/efx_wol.c	optional sfxge inet pci
-dev/sfxge/common/siena_mac.c	optional sfxge inet pci
-dev/sfxge/common/siena_mon.c	optional sfxge inet pci
-dev/sfxge/common/siena_nic.c	optional sfxge inet pci
-dev/sfxge/common/siena_nvram.c	optional sfxge inet pci
-dev/sfxge/common/siena_phy.c	optional sfxge inet pci
-dev/sfxge/common/siena_sram.c	optional sfxge inet pci
-dev/sfxge/common/siena_vpd.c	optional sfxge inet pci
-dev/sfxge/sfxge.c		optional sfxge inet pci
-dev/sfxge/sfxge_dma.c		optional sfxge inet pci
-dev/sfxge/sfxge_ev.c		optional sfxge inet pci
-dev/sfxge/sfxge_intr.c		optional sfxge inet pci
-dev/sfxge/sfxge_mcdi.c		optional sfxge inet pci
-dev/sfxge/sfxge_port.c		optional sfxge inet pci
-dev/sfxge/sfxge_rx.c		optional sfxge inet pci
-dev/sfxge/sfxge_tx.c		optional sfxge inet pci
 dev/sge/if_sge.c		optional sge pci
 dev/si/si.c			optional si
 dev/si/si2_z280.c		optional si
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/conf/files.amd64
--- a/head/sys/conf/files.amd64	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/conf/files.amd64	Tue Dec 06 20:26:16 2011 +0200
@@ -1,7 +1,7 @@
 # This file tells config what files go into building a kernel,
 # files marked standard are always included.
 #
-# $FreeBSD: head/sys/conf/files.amd64 227064 2011-11-03 21:20:22Z bz $
+# $FreeBSD: head/sys/conf/files.amd64 228085 2011-11-28 18:51:40Z philip $
 #
 # The long compile-with and dependency lines are required because of
 # limitations in config: backslash-newline doesn't work in strings, and
@@ -214,6 +214,37 @@
 dev/qlxgb/qla_isr.c		optional	qlxgb pci
 dev/qlxgb/qla_misc.c		optional	qlxgb pci
 dev/qlxgb/qla_os.c		optional	qlxgb pci
+dev/sfxge/common/efx_bootcfg.c	optional sfxge inet pci
+dev/sfxge/common/efx_ev.c	optional sfxge inet pci
+dev/sfxge/common/efx_filter.c	optional sfxge inet pci
+dev/sfxge/common/efx_intr.c	optional sfxge inet pci
+dev/sfxge/common/efx_mac.c	optional sfxge inet pci
+dev/sfxge/common/efx_mcdi.c	optional sfxge inet pci
+dev/sfxge/common/efx_mon.c	optional sfxge inet pci
+dev/sfxge/common/efx_nic.c	optional sfxge inet pci
+dev/sfxge/common/efx_nvram.c	optional sfxge inet pci
+dev/sfxge/common/efx_phy.c	optional sfxge inet pci
+dev/sfxge/common/efx_port.c	optional sfxge inet pci
+dev/sfxge/common/efx_rx.c	optional sfxge inet pci
+dev/sfxge/common/efx_sram.c	optional sfxge inet pci
+dev/sfxge/common/efx_tx.c	optional sfxge inet pci
+dev/sfxge/common/efx_vpd.c	optional sfxge inet pci
+dev/sfxge/common/efx_wol.c	optional sfxge inet pci
+dev/sfxge/common/siena_mac.c	optional sfxge inet pci
+dev/sfxge/common/siena_mon.c	optional sfxge inet pci
+dev/sfxge/common/siena_nic.c	optional sfxge inet pci
+dev/sfxge/common/siena_nvram.c	optional sfxge inet pci
+dev/sfxge/common/siena_phy.c	optional sfxge inet pci
+dev/sfxge/common/siena_sram.c	optional sfxge inet pci
+dev/sfxge/common/siena_vpd.c	optional sfxge inet pci
+dev/sfxge/sfxge.c		optional sfxge inet pci
+dev/sfxge/sfxge_dma.c		optional sfxge inet pci
+dev/sfxge/sfxge_ev.c		optional sfxge inet pci
+dev/sfxge/sfxge_intr.c		optional sfxge inet pci
+dev/sfxge/sfxge_mcdi.c		optional sfxge inet pci
+dev/sfxge/sfxge_port.c		optional sfxge inet pci
+dev/sfxge/sfxge_rx.c		optional sfxge inet pci
+dev/sfxge/sfxge_tx.c		optional sfxge inet pci
 dev/sio/sio.c			optional	sio
 dev/sio/sio_isa.c		optional	sio isa
 dev/sio/sio_pccard.c		optional	sio pccard
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/conf/files.sparc64
--- a/head/sys/conf/files.sparc64	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/conf/files.sparc64	Tue Dec 06 20:26:16 2011 +0200
@@ -1,7 +1,7 @@
 # This file tells config what files go into building a kernel,
 # files marked standard are always included.
 #
-# $FreeBSD: head/sys/conf/files.sparc64 220885 2011-04-20 12:58:30Z bz $
+# $FreeBSD: head/sys/conf/files.sparc64 228022 2011-11-27 15:43:40Z marius $
 #
 # The long compile-with and dependency lines are required because of
 # limitations in config: backslash-newline doesn't work in strings, and
@@ -90,6 +90,7 @@
 sparc64/sparc64/autoconf.c	standard
 sparc64/sparc64/bus_machdep.c	standard
 sparc64/sparc64/cache.c		standard
+sparc64/sparc64/cam_machdep.c	optional	scbus
 sparc64/sparc64/cheetah.c	standard
 sparc64/sparc64/clock.c		standard
 sparc64/sparc64/counter.c	standard
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/conf/kern.mk
--- a/head/sys/conf/kern.mk	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/conf/kern.mk	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-# $FreeBSD: head/sys/conf/kern.mk 226802 2011-10-26 17:26:38Z rmh $
+# $FreeBSD: head/sys/conf/kern.mk 228137 2011-11-29 16:34:44Z fjoe $
 
 #
 # Warning flags for compiling the kernel and components of the kernel:
@@ -126,10 +126,3 @@
     ${MACHINE_CPUARCH} != "arm" && ${MACHINE_CPUARCH} != "mips"
 CFLAGS+=	-fstack-protector
 .endif
-
-#
-# Enable CTF conversation on request
-#
-.if defined(WITH_CTF)
-.undef NO_CTF
-.endif
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/conf/kern.post.mk
--- a/head/sys/conf/kern.post.mk	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/conf/kern.post.mk	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-# $FreeBSD: head/sys/conf/kern.post.mk 222229 2011-05-23 21:32:45Z imp $
+# $FreeBSD: head/sys/conf/kern.post.mk 228158 2011-11-30 18:11:49Z fjoe $
 
 # Part of a unified Makefile for building kernels.  This part includes all
 # the definitions that need to be after all the % directives except %RULES
@@ -94,7 +94,9 @@
 	@rm -f ${.TARGET}
 	@echo linking ${.TARGET}
 	${SYSTEM_LD}
-	@${SYSTEM_CTFMERGE}
+.if ${MK_CTF} != "no"
+	${CTFMERGE} ${CTFFLAGS} -o ${.TARGET} ${SYSTEM_OBJS} vers.o
+.endif
 .if !defined(DEBUG)
 	${OBJCOPY} --strip-debug ${.TARGET}
 .endif
@@ -247,7 +249,7 @@
 
 config.o env.o hints.o vers.o vnode_if.o:
 	${NORMAL_C}
-	@[ -z "${CTFCONVERT}" -o -n "${NO_CTF}" ] || ${CTFCONVERT} ${CTFFLAGS} ${.TARGET}
+	${NORMAL_CTFCONVERT}
 
 config.ln env.ln hints.ln vers.ln vnode_if.ln:
 	${NORMAL_LINT}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/conf/kern.pre.mk
--- a/head/sys/conf/kern.pre.mk	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/conf/kern.pre.mk	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-# $FreeBSD: head/sys/conf/kern.pre.mk 224882 2011-08-15 13:33:14Z nwhitehorn $
+# $FreeBSD: head/sys/conf/kern.pre.mk 228158 2011-11-30 18:11:49Z fjoe $
 
 # Part of a unified Makefile for building kernels.  This part contains all
 # of the definitions that need to be before %BEFORE_DEPEND.
@@ -123,8 +123,13 @@
 NORMAL_M= ${AWK} -f $S/tools/makeobjops.awk ${.IMPSRC} -c ; \
 	  ${CC} -c ${CFLAGS} ${WERROR} ${PROF} ${.PREFIX}.c
 
-NORMAL_CTFCONVERT= [ -z "${CTFCONVERT}" -o -n "${NO_CTF}" ] || \
-		   ${CTFCONVERT} ${CTFFLAGS} ${.TARGET}
+.if ${MK_CTF} != "no"
+NORMAL_CTFCONVERT=	${CTFCONVERT} ${CTFFLAGS} ${.TARGET}
+.elif ${MAKE_VERSION} >= 5201111300
+NORMAL_CTFCONVERT=
+.else
+NORMAL_CTFCONVERT=	@:
+.endif
 
 NORMAL_LINT=	${LINT} ${LINTFLAGS} ${CFLAGS:M-[DIU]*} ${.IMPSRC}
 
@@ -142,7 +147,6 @@
 SYSTEM_OBJS= locore.o ${MDOBJS} ${OBJS}
 SYSTEM_OBJS+= ${SYSTEM_CFILES:.c=.o}
 SYSTEM_OBJS+= hack.So
-SYSTEM_CTFMERGE= [ -z "${CTFMERGE}" -o -n "${NO_CTF}" ] || ${CTFMERGE} ${CTFFLAGS} -o ${.TARGET} ${SYSTEM_OBJS} vers.o
 SYSTEM_LD= @${LD} -Bdynamic -T ${LDSCRIPT} \
 	-warn-common -export-dynamic -dynamic-linker /red/herring \
 	-o ${.TARGET} -X ${SYSTEM_OBJS} vers.o
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/conf/kmod.mk
--- a/head/sys/conf/kmod.mk	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/conf/kmod.mk	Tue Dec 06 20:26:16 2011 +0200
@@ -1,5 +1,5 @@
 #	From: @(#)bsd.prog.mk	5.26 (Berkeley) 6/25/91
-# $FreeBSD: head/sys/conf/kmod.mk 222229 2011-05-23 21:32:45Z imp $
+# $FreeBSD: head/sys/conf/kmod.mk 228158 2011-11-30 18:11:49Z fjoe $
 #
 # The include file <bsd.kmod.mk> handles building and installing loadable
 # kernel modules.
@@ -72,11 +72,6 @@
 .error "Do not use KMODDEPS on 5.0+; use MODULE_VERSION/MODULE_DEPEND"
 .endif
 
-# Enable CTF conversion on request.
-.if defined(WITH_CTF)
-.undef NO_CTF
-.endif
-
 .include <bsd.init.mk>
 
 .SUFFIXES: .out .o .c .cc .cxx .C .y .l .s .S
@@ -206,7 +201,9 @@
 ${FULLPROG}: ${OBJS}
 .endif
 	${LD} ${LDFLAGS} -r -d -o ${.TARGET} ${OBJS}
-	@[ -z "${CTFMERGE}" -o -n "${NO_CTF}" ] || ${CTFMERGE} ${CTFFLAGS} -o ${.TARGET} ${OBJS}
+.if ${MK_CTF} != "no"
+	${CTFMERGE} ${CTFFLAGS} -o ${.TARGET} ${OBJS}
+.endif
 .if defined(EXPORT_SYMS)
 .if ${EXPORT_SYMS} != YES
 .if ${EXPORT_SYMS} == NO
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/conf/makeLINT.mk
--- a/head/sys/conf/makeLINT.mk	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/conf/makeLINT.mk	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-# $FreeBSD: head/sys/conf/makeLINT.mk 221353 2011-05-02 22:54:24Z bz $
+# $FreeBSD: head/sys/conf/makeLINT.mk 228021 2011-11-27 13:53:36Z jh $
 
 all:
 	@echo "make LINT only"
@@ -6,7 +6,7 @@
 clean:
 	rm -f LINT
 .if ${TARGET} == "amd64" || ${TARGET} == "i386"
-	rm -f LINT-VIMAGE
+	rm -f LINT-VIMAGE LINT-NOINET LINT-NOINET6 LINT-NOIP
 .endif
 
 NOTES=	../../conf/NOTES NOTES
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/conf/newvers.sh
--- a/head/sys/conf/newvers.sh	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/conf/newvers.sh	Tue Dec 06 20:26:16 2011 +0200
@@ -28,7 +28,7 @@
 # SUCH DAMAGE.
 #
 #	@(#)newvers.sh	8.1 (Berkeley) 4/20/94
-# $FreeBSD: head/sys/conf/newvers.sh 226863 2011-10-27 20:44:28Z dougb $
+# $FreeBSD: head/sys/conf/newvers.sh 228148 2011-11-29 21:28:48Z jhb $
 
 TYPE="FreeBSD"
 REVISION="10.0"
@@ -99,7 +99,6 @@
 done
 
 if [ -n "$svnversion" ] ; then
-	echo "$svnversion"
 	svn=`cd ${SYSDIR} && $svnversion`
 	case "$svn" in
 	[0-9]*)	svn=" r${svn}" ;;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/conf/options
--- a/head/sys/conf/options	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/conf/options	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-# $FreeBSD: head/sys/conf/options 227845 2011-11-22 21:50:38Z luigi $
+# $FreeBSD: head/sys/conf/options 227924 2011-11-24 07:32:52Z adrian $
 #
 #        On the handling of kernel options
 #
@@ -900,4 +900,5 @@
 # that "lies" about the amount of RAM it has. Until a cleaner method is
 # defined, this option will suffice in overriding what Redboot says.
 AR71XX_REALMEM    opt_global.h
-
+AR71XX_ENV_UBOOT	opt_global.h
+AR71XX_ENV_REDBOOT	opt_global.h
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/acpica_prep.sh
--- a/head/sys/contrib/dev/acpica/acpica_prep.sh	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/acpica_prep.sh	Tue Dec 06 20:26:16 2011 +0200
@@ -1,5 +1,5 @@
 #!/bin/sh
-# $FreeBSD: head/sys/contrib/dev/acpica/acpica_prep.sh 220663 2011-04-15 18:34:27Z jkim $
+# $FreeBSD: head/sys/contrib/dev/acpica/acpica_prep.sh 228110 2011-11-28 23:36:48Z jkim $
 #
 # Unpack an ACPI CA drop and restructure it to fit the FreeBSD layout
 #
@@ -15,16 +15,14 @@
 
 # files that should keep their full directory path
 fulldirs="common compiler debugger disassembler dispatcher events	\
-	executer hardware include namespace parser resources tables	\
-	tools utilities"
+	executer hardware include namespace os_specific parser		\
+	resources tables utilities"
 
 # files to remove
-stripdirs="acpinames acpisrc acpixtract examples generate os_specific	\
-	tests"
+stripdirs="generate tests tools"
 stripfiles="Makefile README acintel.h aclinux.h acmsvc.h acnetbsd.h	\
-	acos2.h accygwin.h acefi.h acwin.h acwin64.h aeexec.c		\
-	aehandlers.c aemain.c aetables.c aetables.h osunixdir.c		\
-	readme.txt utclib.c"
+	acos2.h accygwin.h acefi.h acwin.h acwin64.h osunixdir.c	\
+	oswindir.c oswintbl.c oswinxf.c readme.txt utclib.c"
 
 # include files to canonify
 src_headers="acapps.h accommon.h acconfig.h acdebug.h acdisasm.h	\
@@ -32,7 +30,7 @@
 	aclocal.h acmacros.h acnames.h acnamesp.h acobject.h acopcode.h	\
 	acoutput.h acparser.h acpi.h acpiosxf.h acpixf.h acpredef.h	\
 	acresrc.h acrestyp.h acstruct.h actables.h actbl.h actbl1.h	\
-	actbl2.h actypes.h acutils.h amlcode.h amlresrc.h		\
+	actbl2.h actbl3.h actypes.h acutils.h amlcode.h amlresrc.h	\
 	platform/acenv.h platform/acfreebsd.h platform/acgcc.h"
 comp_headers="aslcompiler.h asldefine.h aslglobal.h aslmessages.h	\
 	asltypes.h dtcompiler.h dttemplate.h"
@@ -84,8 +82,8 @@
 rm -rf ${wrk}
 
 # assist the developer in generating a diff
-echo "Directories you may want to 'cvs diff':"
-echo "    src/sys/contrib/dev/acpica src/sys/dev/acpica \\"
-echo "    src/sys/amd64/acpica src/sys/i386/acpica src/sys/ia64/acpica \\"
-echo "    src/sys/amd64/include src/sys/i386/include src/sys/ia64/include \\"
-echo "    src/sys/boot src/sys/conf src/sys/modules/acpi src/usr.sbin/acpi"
+echo "Directories you may want to 'svn diff':"
+echo "    sys/contrib/dev/acpica sys/dev/acpica \\"
+echo "    sys/amd64/acpica sys/i386/acpica sys/ia64/acpica sys/x86/acpica \\"
+echo "    sys/amd64/include sys/i386/include sys/ia64/include \\"
+echo "    sys/boot sys/conf sys/modules/acpi usr.sbin/acpi"
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/changes.txt
--- a/head/sys/contrib/dev/acpica/changes.txt	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/changes.txt	Tue Dec 06 20:26:16 2011 +0200
@@ -1,8 +1,357 @@
+----------------------------------------
+23 November 2011. Summary of changes for version 20111123:
+
+This release is available at www.acpica.org/downloads
+The ACPI 5.0 specification is available at www.acpi.info
+
+0) ACPI 5.0 Support:
+
+This release contains full support for the ACPI 5.0 specification, as 
+summarized below.
+
+Reduced Hardware Support:
+-------------------------
+
+This support allows for ACPI systems without the usual ACPI hardware. This 
+support is enabled by a flag in the revision 5 FADT. If it is set, ACPICA will 
+not attempt to initialize or use any of the usual ACPI hardware. Note, when 
+this flag is set, all of the following ACPI hardware is assumed to be not 
+present and is not initialized or accessed:
+
+    General Purpose Events (GPEs)
+    Fixed Events (PM1a/PM1b and PM Control)
+    Power Management Timer and Console Buttons (power/sleep)
+    Real-time Clock Alarm
+    Global Lock
+    System Control Interrupt (SCI)
+    The FACS is assumed to be non-existent
+
+ACPI Tables:
+------------
+
+All new tables and updates to existing tables are fully supported in the 
+ACPICA headers (for use by device drivers), the disassembler, and the iASL 
+Data Table Compiler. ACPI 5.0 defines these new tables:
+
+    BGRT        /* Boot Graphics Resource Table */
+    DRTM        /* Dynamic Root of Trust for Measurement table */
+    FPDT        /* Firmware Performance Data Table */
+    GTDT        /* Generic Timer Description Table */
+    MPST        /* Memory Power State Table */
+    PCCT        /* Platform Communications Channel Table */
+    PMTT        /* Platform Memory Topology Table */
+    RASF        /* RAS Feature table */
+
+Operation Regions/SpaceIDs:
+---------------------------
+
+All new operation regions are fully supported by the iASL compiler, the 
+disassembler, and the ACPICA runtime code (for dispatch to region handlers.) 
+The new operation region Space IDs are:
+
+    GeneralPurposeIo
+    GenericSerialBus
+
+Resource Descriptors:
+---------------------
+
+All new ASL resource descriptors are fully supported by the iASL compiler, the 
+ASL/AML disassembler, and the ACPICA runtime Resource Manager code (including 
+all new predefined resource tags). New descriptors are:
+
+    FixedDma
+    GpioIo
+    GpioInt
+    I2cSerialBus
+    SpiSerialBus
+    UartSerialBus
+
+ASL/AML Operators, New and Modified:
+------------------------------------
+
+One new operator is added, the Connection operator, which is used to associate 
+a GeneralPurposeIo or GenericSerialBus resource descriptor with individual 
+field objects within an operation region. Several new protocols are associated 
+with the AccessAs operator. All are fully supported by the iASL compiler, 
+disassembler, and runtime ACPICA AML interpreter:
+
+    Connection                      // Declare Field Connection attributes
+    AccessAs: AttribBytes (n)           // Read/Write N-Bytes Protocol
+    AccessAs: AttribRawBytes (n)        // Raw Read/Write N-Bytes Protocol
+    AccessAs: AttribRawProcessBytes (n) // Raw Process Call Protocol
+    RawDataBuffer                       // Data type for Vendor Data fields
+
+Predefined ASL/AML Objects:
+---------------------------
+
+All new predefined objects/control-methods are supported by the iASL compiler 
+and the ACPICA runtime validation/repair (arguments and return values.) New 
+predefined names include the following:
+
+Standard Predefined Names (Objects or Control Methods):
+    _AEI, _CLS, _CPC, _CWS, _DEP,
+    _DLM, _EVT, _GCP, _CRT, _GWS,
+    _HRV, _PRE, _PSE, _SRT, _SUB.
+
+Resource Tags (Names used to access individual fields within resource 
+descriptors):
+    _DBT, _DPL, _DRS, _END, _FLC,
+    _IOR, _LIN, _MOD, _PAR, _PHA,
+    _PIN, _PPI, _POL, _RXL, _SLV,
+    _SPE, _STB, _TXL, _VEN.
+
+ACPICA External Interfaces:
+---------------------------
+
+Several new interfaces have been defined for use by ACPI-related device 
+drivers and other host OS services:
+
+AcpiAcquireMutex and AcpiReleaseMutex: These interfaces allow the host OS to 
+acquire and release AML mutexes that are defined in the DSDT/SSDT tables 
+provided by the BIOS. They are intended to be used in conjunction with the 
+ACPI 5.0 _DLM (Device Lock Method) in order to provide transaction-level 
+mutual exclusion with the AML code/interpreter.
+
+AcpiGetEventResources: Returns the (formatted) resource descriptors as defined 
+by the ACPI 5.0 _AEI object (ACPI Event Information).  This object provides 
+resource descriptors associated with hardware-reduced platform events, similar 
+to the AcpiGetCurrentResources interface.
+
+Operation Region Handlers: For General Purpose IO and Generic Serial Bus 
+operation regions, information about the Connection() object and any optional 
+length information is passed to the region handler within the Context 
+parameter.
+
+AcpiBufferToResource: This interface converts a raw AML buffer containing a 
+resource template or resource descriptor to the ACPI_RESOURCE internal format 
+suitable for use by device drivers. Can be used by an operation region handler 
+to convert the Connection() buffer object into a ACPI_RESOURCE.
+
+Miscellaneous/Tools/TestSuites: 
+-------------------------------
+
+Support for extended _HID names (Four alpha characters instead of three).
+Support for ACPI 5.0 features in the AcpiExec and AcpiHelp utilities.
+Support for ACPI 5.0 features in the ASLTS test suite.
+Fully updated documentation (ACPICA and iASL reference documents.)
+
+ACPI Table Definition Language:
+-------------------------------
+
+Support for this language was implemented and released as a subsystem of the 
+iASL compiler in 2010. (See the iASL compiler User Guide.)
+
+
+Non-ACPI 5.0 changes for this release:
+--------------------------------------
+
+1) ACPICA Core Subsystem:
+
+Fix a problem with operation region declarations where a failure can occur if 
+the region name and an argument that evaluates to an object (such as the 
+region address) are in different namespace scopes. Lin Ming, ACPICA BZ 937.
+
+Do not abort an ACPI table load if an invalid space ID is found within. This 
+will be caught later if the offending method is executed. ACPICA BZ 925.
+
+Fixed an issue with the FFixedHW space ID where the ID was not always 
+recognized properly (Both ACPICA and iASL). ACPICA BZ 926.
+
+Fixed a problem with the 32-bit generation of the unix-specific OSL 
+(osunixxf.c). Lin Ming, ACPICA BZ 936.
+
+Several changes made to enable generation with the GCC 4.6 compiler. ACPICA BZ 
+935.
+
+New error messages: Unsupported I/O requests (not 8/16/32 bit), and Index/Bank 
+field registers out-of-range.
+
+2) iASL Compiler/Disassembler and Tools:
+
+iASL: Implemented the __PATH__ operator, which returns the full pathname of 
+the current source file.
+
+AcpiHelp: Automatically display expanded keyword information for all ASL 
+operators.
+
+Debugger: Add "Template" command to disassemble/dump resource template 
+buffers.
+
+Added a new master script to generate and execute the ASLTS test suite. 
+Automatically handles 32- and 64-bit generation. See tests/aslts.sh
+
+iASL: Fix problem with listing generation during processing of the Switch() 
+operator where AML listing was disabled until the entire Switch block was 
+completed.
+
+iASL: Improve support for semicolon statement terminators. Fix "invalid 
+character" message for some cases when the semicolon is used. Semicolons are 
+now allowed after every <Term> grammar element. ACPICA BZ 927.
+
+iASL: Fixed some possible aliasing warnings during generation. ACPICA BZ 923.
+
+Disassembler: Fix problem with disassembly of the DataTableRegion operator 
+where an inadvertent "Unhandled deferred opcode" message could be generated.
+
+3) Example Code and Data Size
+
+These are the sizes for the OS-independent acpica.lib produced by the 
+Microsoft Visual C++ 9.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:  90.2K Code, 23.9K Data, 114.1K Total
+    Debug Version:     165.6K Code, 68.4K Data, 234.0K Total
+  Current Release:
+    Non-Debug Version:  92.3K Code, 24.9K Data, 117.2K Total
+    Debug Version:     170.8K Code, 72.6K Data, 243.4K Total
+
+----------------------------------------
+22 September 2011. Summary of changes for version 20110922:
+
+0) ACPI 5.0 News:
+
+Support for ACPI 5.0 in ACPICA has been underway for several months and will 
+be released at the same time that ACPI 5.0 is officially released.
+
+The ACPI 5.0 specification is on track for release in the next few months.
+ 
+1) ACPICA Core Subsystem:
+
+Fixed a problem where the maximum sleep time for the Sleep() operator was 
+intended to be limited to two seconds, but was inadvertently limited to 20 
+seconds instead.
+
+Linux and Unix makefiles: Added header file dependencies to ensure correct 
+generation of ACPICA core code and utilities. Also simplified the makefiles 
+considerably through the use of the vpath variable to specify search paths. 
+ACPICA BZ 924.
+
+2) iASL Compiler/Disassembler and Tools:
+
+iASL: Implemented support to check the access length for all fields created to 
+access named Resource Descriptor fields. For example, if a resource field is 
+defined to be two bits, a warning is issued if a CreateXxxxField() is used 
+with an incorrect bit length. This is implemented for all current resource 
+descriptor names. ACPICA BZ 930.
+  
+Disassembler: Fixed a byte ordering problem with the output of 24-bit and 56-
+bit integers.
+
+iASL: Fixed a couple of issues associated with variable-length package 
+objects. 1) properly handle constants like One, Ones, Zero -- do not make a 
+VAR_PACKAGE when these are used as a package length. 2) Allow the VAR_PACKAGE 
+opcode (in addition to PACKAGE) when validating object types for predefined 
+names.
+
+iASL: Emit statistics for all output files (instead of just the ASL input and 
+AML output). Includes listings, hex files, etc.
+
+iASL: Added -G option to the table compiler to allow the compilation of custom 
+ACPI tables. The only part of a table that is required is the standard 36-byte 
+ACPI header.
+
+AcpiXtract: Ported to the standard ACPICA environment (with ACPICA headers), 
+which also adds correct 64-bit support. Also, now all output filenames are 
+completely lower case.
+
+AcpiExec: Ignore any non-AML tables (tables other than DSDT or SSDT) when 
+loading table files. A warning is issued for any such tables. The only 
+exception is an FADT. This also fixes a possible fault when attempting to load 
+non-AML tables. ACPICA BZ 932.
+
+AcpiHelp: Added the AccessAs and Offset operators. Fixed a problem where a 
+missing table terminator could cause a fault when using the -p option.
+
+AcpiSrc: Fixed a possible divide-by-zero fault when generating file 
+statistics.
+
+3) Example Code and Data Size
+
+These are the sizes for the OS-independent acpica.lib produced by the 
+Microsoft Visual C++ 9.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 (VC 9.0):
+    Non-Debug Version:  90.2K Code, 23.9K Data, 114.1K Total
+    Debug Version:     165.6K Code, 68.4K Data, 234.0K Total
+  Current Release (VC 9.0):
+    Non-Debug Version:  90.2K Code, 23.9K Data, 114.1K Total
+    Debug Version:     165.6K Code, 68.4K Data, 234.0K Total
+
+
+----------------------------------------
+23 June 2011. Summary of changes for version 20110623:
+
+1) ACPI CA Core Subsystem:
+
+Updated the predefined name repair mechanism to not attempt repair of a _TSS 
+return object if a _PSS object is present. We can only sort the _TSS return 
+package if there is no _PSS within the same scope. This is because if _PSS is 
+present, the ACPI specification dictates that the _TSS Power Dissipation field 
+is to be ignored, and therefore some BIOSs leave garbage values in the _TSS 
+Power field(s). In this case, it is best to just return the _TSS package as-
+is. Reported by, and fixed with assistance from Fenghua Yu.
+
+Added an option to globally disable the control method return value validation 
+and repair. This runtime option can be used to disable return value repair if 
+this is causing a problem on a particular machine. Also added an option to 
+AcpiExec (-dr) to set this disable flag.
+
+All makefiles and project files: Major changes to improve generation of ACPICA 
+tools. ACPICA BZ 912:
+    Reduce default optimization levels to improve compatibility
+    For Linux, add strict-aliasing=0 for gcc 4
+    Cleanup and simplify use of command line defines
+    Cleanup multithread library support
+    Improve usage messages
+
+Linux-specific header: update handling of THREAD_ID and pthread. For the 32-
+bit case, improve casting to eliminate possible warnings, especially with the 
+acpica tools.
+
+Example Code and Data Size: These are the sizes for the OS-independent 
+acpica.lib produced by the Microsoft Visual C++ 9.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 (VC 9.0):
+    Non-Debug Version:  90.1K Code, 23.9K Data, 114.0K Total
+    Debug Version:     165.6K Code, 68.4K Data, 234.0K Total
+  Current Release (VC 9.0):
+    Non-Debug Version:  90.2K Code, 23.9K Data, 114.1K Total
+    Debug Version:     165.6K Code, 68.4K Data, 234.0K Total
+
+2) iASL Compiler/Disassembler and Tools:
+
+With this release, a new utility named "acpihelp" has been added to the ACPICA 
+package. This utility summarizes the ACPI specification chapters for the ASL 
+and AML languages. It generates under Linux/Unix as well as Windows, and 
+provides the following functionality:
+    Find/display ASL operator(s) -- with description and syntax.
+    Find/display ASL keyword(s) -- with exact spelling and descriptions.
+    Find/display ACPI predefined name(s) -- with description, number
+        of arguments, and the return value data type.
+    Find/display AML opcode name(s) -- with opcode, arguments, and grammar.
+    Decode/display AML opcode -- with opcode name, arguments, and grammar.
+
+Service Layers: Make multi-thread support configurable. Conditionally compile 
+the multi-thread support so that threading libraries will not be linked if not 
+necessary. The only tool that requires multi-thread support is AcpiExec.
+
+iASL: Update yyerrror/AslCompilerError for "const" errors. Newer versions of 
+Bison appear to want the interface to yyerror to be a const char * (or at 
+least this is a problem when generating iASL on some systems.) ACPICA BZ 923 
+Pierre Lejeune.
+
+Tools: Fix for systems where O_BINARY is not defined. Only used for Windows 
+versions of the tools.
+
 ----------------------------------------
 27 May 2011. Summary of changes for version 20110527:
 
-This release is available at www.acpica.org/downloads
-
 1) ACPI CA Core Subsystem:
 
 ASL Load() operator: Reinstate most restrictions on the incoming ACPI table 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/common/adisasm.c
--- a/head/sys/contrib/dev/acpica/common/adisasm.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/common/adisasm.c	Tue Dec 06 20:26:16 2011 +0200
@@ -868,6 +868,7 @@
             break;
 
         case AML_REGION_OP:
+        case AML_DATA_REGION_OP:
         case AML_CREATE_QWORD_FIELD_OP:
         case AML_CREATE_DWORD_FIELD_OP:
         case AML_CREATE_WORD_FIELD_OP:
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/common/adwalk.c
--- a/head/sys/contrib/dev/acpica/common/adwalk.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/common/adwalk.c	Tue Dec 06 20:26:16 2011 +0200
@@ -378,6 +378,10 @@
         AcpiOsPrintf ("%X", (UINT32) Op->Common.Value.Integer);
         break;
 
+    case AML_QWORD_OP:
+        AcpiOsPrintf ("%8.8X%8.8X", ACPI_FORMAT_UINT64 (Op->Common.Value.Integer));
+        break;
+
     case AML_INT_NAMEPATH_OP:
         if (Op->Common.Value.String)
         {
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/common/dmrestag.c
--- a/head/sys/contrib/dev/acpica/common/dmrestag.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/common/dmrestag.c	Tue Dec 06 20:26:16 2011 +0200
@@ -63,7 +63,7 @@
 static char *
 AcpiDmSearchTagList (
     UINT32                  BitIndex,
-    ACPI_RESOURCE_TAG       *TagList);
+    const ACPI_RESOURCE_TAG *TagList);
 
 static char *
 AcpiDmGetResourceTag (
@@ -108,7 +108,7 @@
  *
  ******************************************************************************/
 
-static ACPI_RESOURCE_TAG        AcpiDmIrqTags[] =
+static const ACPI_RESOURCE_TAG      AcpiDmIrqTags[] =
 {
     {( 1 * 8),      ACPI_RESTAG_INTERRUPT},
     {( 3 * 8) + 0,  ACPI_RESTAG_INTERRUPTTYPE},
@@ -117,7 +117,7 @@
     {0,             NULL}
 };
 
-static ACPI_RESOURCE_TAG        AcpiDmDmaTags[] =
+static const ACPI_RESOURCE_TAG      AcpiDmDmaTags[] =
 {
     {( 1 * 8),      ACPI_RESTAG_DMA},
     {( 2 * 8) + 0,  ACPI_RESTAG_XFERTYPE},
@@ -126,7 +126,7 @@
     {0,             NULL}
 };
 
-static ACPI_RESOURCE_TAG        AcpiDmIoTags[] =
+static const ACPI_RESOURCE_TAG      AcpiDmIoTags[] =
 {
     {( 1 * 8) + 0,  ACPI_RESTAG_DECODE},
     {( 2 * 8),      ACPI_RESTAG_MINADDR},
@@ -136,14 +136,22 @@
     {0,             NULL}
 };
 
-static ACPI_RESOURCE_TAG        AcpiDmFixedIoTags[] =
+static const ACPI_RESOURCE_TAG      AcpiDmFixedIoTags[] =
 {
     {( 1 * 8),      ACPI_RESTAG_BASEADDRESS},
     {( 3 * 8),      ACPI_RESTAG_LENGTH},
     {0,             NULL}
 };
 
-static ACPI_RESOURCE_TAG        AcpiDmMemory24Tags[] =
+static const ACPI_RESOURCE_TAG      AcpiDmFixedDmaTags[] =
+{
+    {( 1 * 8),      ACPI_RESTAG_DMA},
+    {( 3 * 8),      ACPI_RESTAG_DMATYPE},
+    {( 5 * 8),      ACPI_RESTAG_XFERTYPE},
+    {0,             NULL}
+};
+
+static const ACPI_RESOURCE_TAG      AcpiDmMemory24Tags[] =
 {
     {( 3 * 8) + 0,  ACPI_RESTAG_READWRITETYPE},
     {( 4 * 8),      ACPI_RESTAG_MINADDR},
@@ -153,7 +161,7 @@
     {0,             NULL}
 };
 
-static ACPI_RESOURCE_TAG        AcpiDmRegisterTags[] =
+static const ACPI_RESOURCE_TAG      AcpiDmRegisterTags[] =
 {
     {( 3 * 8),      ACPI_RESTAG_ADDRESSSPACE},
     {( 4 * 8),      ACPI_RESTAG_REGISTERBITWIDTH},
@@ -163,7 +171,7 @@
     {0,             NULL}
 };
 
-static ACPI_RESOURCE_TAG        AcpiDmMemory32Tags[] =
+static const ACPI_RESOURCE_TAG      AcpiDmMemory32Tags[] =
 {
     {( 3 * 8) + 0,  ACPI_RESTAG_READWRITETYPE},
     {( 4 * 8),      ACPI_RESTAG_MINADDR},
@@ -173,7 +181,7 @@
     {0,             NULL}
 };
 
-static ACPI_RESOURCE_TAG        AcpiDmFixedMemory32Tags[] =
+static const ACPI_RESOURCE_TAG      AcpiDmFixedMemory32Tags[] =
 {
     {( 3 * 8) + 0,  ACPI_RESTAG_READWRITETYPE},
     {( 4 * 8),      ACPI_RESTAG_BASEADDRESS},
@@ -181,7 +189,7 @@
     {0,             NULL}
 };
 
-static ACPI_RESOURCE_TAG        AcpiDmInterruptTags[] =
+static const ACPI_RESOURCE_TAG      AcpiDmInterruptTags[] =
 {
     {( 3 * 8) + 1,  ACPI_RESTAG_INTERRUPTTYPE},
     {( 3 * 8) + 2,  ACPI_RESTAG_INTERRUPTLEVEL},
@@ -190,7 +198,7 @@
     {0,             NULL}
 };
 
-static ACPI_RESOURCE_TAG        AcpiDmAddress16Tags[] =
+static const ACPI_RESOURCE_TAG      AcpiDmAddress16Tags[] =
 {
     {( 4 * 8) + 1,  ACPI_RESTAG_DECODE},
     {( 4 * 8) + 2,  ACPI_RESTAG_MINTYPE},
@@ -203,7 +211,7 @@
     {0,             NULL}
 };
 
-static ACPI_RESOURCE_TAG        AcpiDmAddress32Tags[] =
+static const ACPI_RESOURCE_TAG      AcpiDmAddress32Tags[] =
 {
     {( 4 * 8) + 1,  ACPI_RESTAG_DECODE},
     {( 4 * 8) + 2,  ACPI_RESTAG_MINTYPE},
@@ -216,7 +224,7 @@
     {0,             NULL}
 };
 
-static ACPI_RESOURCE_TAG        AcpiDmAddress64Tags[] =
+static const ACPI_RESOURCE_TAG      AcpiDmAddress64Tags[] =
 {
     {( 4 * 8) + 1,  ACPI_RESTAG_DECODE},
     {( 4 * 8) + 2,  ACPI_RESTAG_MINTYPE},
@@ -229,7 +237,7 @@
     {0,             NULL}
 };
 
-static ACPI_RESOURCE_TAG        AcpiDmExtendedAddressTags[] =
+static const ACPI_RESOURCE_TAG      AcpiDmExtendedAddressTags[] =
 {
     {( 4 * 8) + 1,  ACPI_RESTAG_DECODE},
     {( 4 * 8) + 2,  ACPI_RESTAG_MINTYPE},
@@ -243,9 +251,71 @@
     {0,             NULL}
 };
 
-/* Special-case tables for the type-specific flags */
+/* Subtype tables for GPIO descriptors */
 
-static ACPI_RESOURCE_TAG        AcpiDmMemoryFlagTags[] =
+static const ACPI_RESOURCE_TAG      AcpiDmGpioIntTags[] =
+{
+    {( 7 * 8) + 0,  ACPI_RESTAG_MODE},
+    {( 7 * 8) + 1,  ACPI_RESTAG_POLARITY},
+    {( 7 * 8) + 3,  ACPI_RESTAG_INTERRUPTSHARE},
+    {( 9 * 8),      ACPI_RESTAG_PINCONFIG},
+    {(10 * 8),      ACPI_RESTAG_DRIVESTRENGTH},
+    {(12 * 8),      ACPI_RESTAG_DEBOUNCETIME},
+    {0,             NULL}
+};
+
+static const ACPI_RESOURCE_TAG      AcpiDmGpioIoTags[] =
+{
+    {( 7 * 8) + 0,  ACPI_RESTAG_IORESTRICTION},
+    {( 7 * 8) + 3,  ACPI_RESTAG_INTERRUPTSHARE},
+    {( 9 * 8),      ACPI_RESTAG_PINCONFIG},
+    {(10 * 8),      ACPI_RESTAG_DRIVESTRENGTH},
+    {(12 * 8),      ACPI_RESTAG_DEBOUNCETIME},
+    {0,             NULL}
+};
+
+/* Subtype tables for SerialBus descriptors */
+
+static const ACPI_RESOURCE_TAG      AcpiDmI2cSerialBusTags[] =
+{
+    {( 6 * 8) + 0,  ACPI_RESTAG_SLAVEMODE},
+    {( 7 * 8) + 0,  ACPI_RESTAG_MODE},
+    {(12 * 8),      ACPI_RESTAG_SPEED},
+    {(16 * 8),      ACPI_RESTAG_ADDRESS},
+    {0,             NULL}
+};
+
+static const ACPI_RESOURCE_TAG      AcpiDmSpiSerialBusTags[] =
+{
+    {( 6 * 8) + 0,  ACPI_RESTAG_SLAVEMODE},
+    {( 7 * 8) + 0,  ACPI_RESTAG_MODE},
+    {( 7 * 8) + 1,  ACPI_RESTAG_DEVICEPOLARITY},
+    {(12 * 8),      ACPI_RESTAG_SPEED},
+    {(16 * 8),      ACPI_RESTAG_LENGTH},
+    {(17 * 8),      ACPI_RESTAG_PHASE},
+    {(18 * 8),      ACPI_RESTAG_POLARITY},
+    {(19 * 8),      ACPI_RESTAG_ADDRESS},
+    {0,             NULL}
+};
+
+static const ACPI_RESOURCE_TAG      AcpiDmUartSerialBusTags[] =
+{
+    {( 6 * 8) + 0,  ACPI_RESTAG_SLAVEMODE}, /* Note: not part of original macro */
+    {( 7 * 8) + 0,  ACPI_RESTAG_FLOWCONTROL},
+    {( 7 * 8) + 2,  ACPI_RESTAG_STOPBITS},
+    {( 7 * 8) + 4,  ACPI_RESTAG_LENGTH},
+    {( 7 * 8) + 7,  ACPI_RESTAG_ENDIANNESS},
+    {(12 * 8),      ACPI_RESTAG_SPEED},
+    {(16 * 8),      ACPI_RESTAG_LENGTH_RX},
+    {(18 * 8),      ACPI_RESTAG_LENGTH_TX},
+    {(20 * 8),      ACPI_RESTAG_PARITY},
+    {(21 * 8),      ACPI_RESTAG_LINE},
+    {0,             NULL}
+};
+
+/* Subtype tables for Address descriptor type-specific flags */
+
+static const ACPI_RESOURCE_TAG      AcpiDmMemoryFlagTags[] =
 {
     {( 5 * 8) + 0,  ACPI_RESTAG_READWRITETYPE},
     {( 5 * 8) + 1,  ACPI_RESTAG_MEMTYPE},
@@ -254,7 +324,7 @@
     {0,             NULL}
 };
 
-static ACPI_RESOURCE_TAG        AcpiDmIoFlagTags[] =
+static const ACPI_RESOURCE_TAG      AcpiDmIoFlagTags[] =
 {
     {( 5 * 8) + 0,  ACPI_RESTAG_RANGETYPE},
     {( 5 * 8) + 4,  ACPI_RESTAG_TYPE},
@@ -263,9 +333,15 @@
 };
 
 
-/* Dispatch table used to obtain the correct tag table for a descriptor */
-
-static ACPI_RESOURCE_TAG        *AcpiGbl_ResourceTags [] =
+/*
+ * Dispatch table used to obtain the correct tag table for a descriptor.
+ *
+ * A NULL in this table means one of three things:
+ * 1) The descriptor ID is reserved and invalid
+ * 2) The descriptor has no tags associated with it
+ * 3) The descriptor has subtypes and a separate table will be used.
+ */
+static const ACPI_RESOURCE_TAG      *AcpiGbl_ResourceTags[] =
 {
     /* Small descriptors */
 
@@ -279,7 +355,7 @@
     NULL,                           /* 0x07, ACPI_RESOURCE_NAME_END_DEPENDENT */
     AcpiDmIoTags,                   /* 0x08, ACPI_RESOURCE_NAME_IO_PORT */
     AcpiDmFixedIoTags,              /* 0x09, ACPI_RESOURCE_NAME_FIXED_IO_PORT */
-    NULL,                           /* 0x0A, Reserved */
+    AcpiDmFixedDmaTags,             /* 0x0A, ACPI_RESOURCE_NAME_FIXED_DMA */
     NULL,                           /* 0x0B, Reserved */
     NULL,                           /* 0x0C, Reserved */
     NULL,                           /* 0x0D, Reserved */
@@ -299,9 +375,29 @@
     AcpiDmAddress16Tags,            /* 0x08, ACPI_RESOURCE_NAME_WORD_ADDRESS_SPACE */
     AcpiDmInterruptTags,            /* 0x09, ACPI_RESOURCE_NAME_EXTENDED_XRUPT */
     AcpiDmAddress64Tags,            /* 0x0A, ACPI_RESOURCE_NAME_QWORD_ADDRESS_SPACE */
-    AcpiDmExtendedAddressTags       /* 0x0B, ACPI_RESOURCE_NAME_EXTENDED_ADDRESS_SPACE */
+    AcpiDmExtendedAddressTags,      /* 0x0B, ACPI_RESOURCE_NAME_EXTENDED_ADDRESS_SPACE */
+    NULL,                           /* 0x0C, ACPI_RESOURCE_NAME_GPIO - Use Subtype table below */
+    NULL,                           /* 0x0D, Reserved */
+    NULL                            /* 0x0E, ACPI_RESOURCE_NAME_SERIAL_BUS - Use Subtype table below */
 };
 
+/* GPIO Subtypes */
+
+static const ACPI_RESOURCE_TAG      *AcpiGbl_GpioResourceTags[] =
+{
+    AcpiDmGpioIntTags,              /* 0x00 Interrupt Connection */
+    AcpiDmGpioIoTags                /* 0x01 I/O Connection */
+};
+
+/* Serial Bus Subtypes */
+
+static const ACPI_RESOURCE_TAG      *AcpiGbl_SerialResourceTags[] =
+{
+    NULL,                           /* 0x00 Reserved */
+    AcpiDmI2cSerialBusTags,         /* 0x01 I2C SerialBus */
+    AcpiDmSpiSerialBusTags,         /* 0x02 SPI SerialBus */
+    AcpiDmUartSerialBusTags         /* 0x03 UART SerialBus */
+};
 
 /*
  * Globals used to generate unique resource descriptor names. We use names that
@@ -666,6 +762,9 @@
  *
  * DESCRIPTION: Convert a BitIndex into a symbolic resource tag.
  *
+ * Note: ResourceIndex should be previously validated and guaranteed to ve
+ *       valid.
+ *
  ******************************************************************************/
 
 static char *
@@ -674,23 +773,16 @@
     AML_RESOURCE            *Resource,
     UINT8                   ResourceIndex)
 {
-    ACPI_RESOURCE_TAG       *TagList;
+    const ACPI_RESOURCE_TAG *TagList;
     char                    *Tag = NULL;
 
 
     /* Get the tag list for this resource descriptor type */
 
     TagList = AcpiGbl_ResourceTags[ResourceIndex];
-    if (!TagList)
-    {
-        /* There are no tags for this resource type */
-
-        return (NULL);
-    }
 
     /*
-     * Handle the type-specific flags field for the address descriptors.
-     * Kindof brute force, but just blindly search for an index match.
+     * Handle descriptors that have multiple subtypes
      */
     switch (Resource->DescriptorType)
     {
@@ -699,6 +791,10 @@
     case ACPI_RESOURCE_NAME_ADDRESS64:
     case ACPI_RESOURCE_NAME_EXTENDED_ADDRESS64:
 
+        /*
+         * Subtype differentiation is the flags.
+         * Kindof brute force, but just blindly search for an index match
+         */
         if (Resource->Address.ResourceType == ACPI_ADDRESS_TYPE_MEMORY_RANGE)
         {
             Tag = AcpiDmSearchTagList (BitIndex, AcpiDmMemoryFlagTags);
@@ -716,13 +812,42 @@
         }
         break;
 
+    case ACPI_RESOURCE_NAME_GPIO:
+
+        /* GPIO connection has 2 subtypes: Interrupt and I/O */
+
+        if (Resource->Gpio.ConnectionType > AML_RESOURCE_MAX_GPIOTYPE)
+        {
+            return (NULL);
+        }
+
+        TagList = AcpiGbl_GpioResourceTags[Resource->Gpio.ConnectionType];
+        break;
+
+    case ACPI_RESOURCE_NAME_SERIAL_BUS:
+
+        /* SerialBus has 3 subtypes: I2C, SPI, and UART */
+
+        if ((Resource->CommonSerialBus.Type == 0) ||
+            (Resource->CommonSerialBus.Type > AML_RESOURCE_MAX_SERIALBUSTYPE))
+        {
+            return (NULL);
+        }
+
+        TagList = AcpiGbl_SerialResourceTags[Resource->CommonSerialBus.Type];
+        break;
+
     default:
         break;
     }
 
-    /* Search the tag list for this descriptor type */
+    /* Search for a match against the BitIndex */
 
-    Tag = AcpiDmSearchTagList (BitIndex, TagList);
+    if (TagList)
+    {
+        Tag = AcpiDmSearchTagList (BitIndex, TagList);
+    }
+
     return (Tag);
 }
 
@@ -744,7 +869,7 @@
 static char *
 AcpiDmSearchTagList (
     UINT32                  BitIndex,
-    ACPI_RESOURCE_TAG       *TagList)
+    const ACPI_RESOURCE_TAG *TagList)
 {
 
     /*
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/common/dmtable.c
--- a/head/sys/contrib/dev/acpica/common/dmtable.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/common/dmtable.c	Tue Dec 06 20:26:16 2011 +0200
@@ -196,6 +196,16 @@
     "Platform Interrupt Sources",   /* ACPI_MADT_TYPE_INTERRUPT_SOURCE */
     "Processor Local x2APIC",       /* ACPI_MADT_TYPE_LOCAL_X2APIC */
     "Local x2APIC NMI",             /* ACPI_MADT_TYPE_LOCAL_X2APIC_NMI */
+    "Generic Interrupt Controller", /* ACPI_MADT_GENERIC_INTERRUPT */
+    "Generic Interrupt Distributor",/* ACPI_MADT_GENERIC_DISTRIBUTOR */
+    "Unknown SubTable Type"         /* Reserved */
+};
+
+static const char           *AcpiDmPmttSubnames[] =
+{
+    "Socket",                       /* ACPI_PMTT_TYPE_SOCKET */
+    "Memory Controller",            /* ACPI_PMTT_TYPE_CONTROLLER */
+    "Physical Component (DIMM)",    /* ACPI_PMTT_TYPE_DIMM  */
     "Unknown SubTable Type"         /* Reserved */
 };
 
@@ -268,6 +278,7 @@
     {ACPI_SIG_ASF,  NULL,                   AcpiDmDumpAsf,  DtCompileAsf,   TemplateAsf,    "Alert Standard Format table"},
     {ACPI_SIG_BOOT, AcpiDmTableInfoBoot,    NULL,           NULL,           TemplateBoot,   "Simple Boot Flag Table"},
     {ACPI_SIG_BERT, AcpiDmTableInfoBert,    NULL,           NULL,           TemplateBert,   "Boot Error Record Table"},
+    {ACPI_SIG_BGRT, AcpiDmTableInfoBgrt,    NULL,           NULL,           TemplateBgrt,   "Boot Graphics Resource Table"},
     {ACPI_SIG_CPEP, NULL,                   AcpiDmDumpCpep, DtCompileCpep,  TemplateCpep,   "Corrected Platform Error Polling table"},
     {ACPI_SIG_DBGP, AcpiDmTableInfoDbgp,    NULL,           NULL,           TemplateDbgp,   "Debug Port table"},
     {ACPI_SIG_DMAR, NULL,                   AcpiDmDumpDmar, DtCompileDmar,  TemplateDmar,   "DMA Remapping table"},
@@ -275,14 +286,20 @@
     {ACPI_SIG_EINJ, NULL,                   AcpiDmDumpEinj, DtCompileEinj,  TemplateEinj,   "Error Injection table"},
     {ACPI_SIG_ERST, NULL,                   AcpiDmDumpErst, DtCompileErst,  TemplateErst,   "Error Record Serialization Table"},
     {ACPI_SIG_FADT, NULL,                   AcpiDmDumpFadt, DtCompileFadt,  TemplateFadt,   "Fixed ACPI Description Table"},
+    {ACPI_SIG_FPDT, NULL,                   AcpiDmDumpFpdt, DtCompileFpdt,  TemplateFpdt,   "Firmware Performance Data Table"},
+    {ACPI_SIG_GTDT, AcpiDmTableInfoGtdt,    NULL,           NULL,           TemplateGtdt,   "Generic Timer Description Table"},
     {ACPI_SIG_HEST, NULL,                   AcpiDmDumpHest, DtCompileHest,  TemplateHest,   "Hardware Error Source Table"},
     {ACPI_SIG_HPET, AcpiDmTableInfoHpet,    NULL,           NULL,           TemplateHpet,   "High Precision Event Timer table"},
     {ACPI_SIG_IVRS, NULL,                   AcpiDmDumpIvrs, DtCompileIvrs,  TemplateIvrs,   "I/O Virtualization Reporting Structure"},
     {ACPI_SIG_MADT, NULL,                   AcpiDmDumpMadt, DtCompileMadt,  TemplateMadt,   "Multiple APIC Description Table"},
     {ACPI_SIG_MCFG, NULL,                   AcpiDmDumpMcfg, DtCompileMcfg,  TemplateMcfg,   "Memory Mapped Configuration table"},
     {ACPI_SIG_MCHI, AcpiDmTableInfoMchi,    NULL,           NULL,           TemplateMchi,   "Management Controller Host Interface table"},
+    {ACPI_SIG_MPST, AcpiDmTableInfoMpst,    AcpiDmDumpMpst, DtCompileMpst,  TemplateMpst,   "Memory Power State Table"},
     {ACPI_SIG_MSCT, NULL,                   AcpiDmDumpMsct, DtCompileMsct,  TemplateMsct,   "Maximum System Characteristics Table"},
+    {ACPI_SIG_PCCT, NULL,                   AcpiDmDumpPcct, NULL,           NULL,           "Platform Communications Channel Table"},
+    {ACPI_SIG_PMTT, NULL,                   AcpiDmDumpPmtt, DtCompilePmtt,  TemplatePmtt,   "Platform Memory Topology Table"},
     {ACPI_SIG_RSDT, NULL,                   AcpiDmDumpRsdt, DtCompileRsdt,  TemplateRsdt,   "Root System Description Table"},
+    {ACPI_SIG_S3PT, NULL,                   NULL,           NULL,           TemplateS3pt,   "S3 Performance Table"},
     {ACPI_SIG_SBST, AcpiDmTableInfoSbst,    NULL,           NULL,           TemplateSbst,   "Smart Battery Specification Table"},
     {ACPI_SIG_SLIC, NULL,                   AcpiDmDumpSlic, DtCompileSlic,  TemplateSlic,   "Software Licensing Description Table"},
     {ACPI_SIG_SLIT, NULL,                   AcpiDmDumpSlit, DtCompileSlit,  TemplateSlit,   "System Locality Information Table"},
@@ -400,7 +417,7 @@
 
     /*
      * Handle tables that don't use the common ACPI table header structure.
-     * Currently, these are the FACS and RSDP.
+     * Currently, these are the FACS, RSDP, and S3PT.
      */
     if (ACPI_COMPARE_NAME (Table->Signature, ACPI_SIG_FACS))
     {
@@ -411,6 +428,10 @@
     {
         Length = AcpiDmDumpRsdp (Table);
     }
+    else if (ACPI_COMPARE_NAME (Table->Signature, ACPI_SIG_S3PT))
+    {
+        Length = AcpiDmDumpS3pt (Table);
+    }
     else
     {
         /*
@@ -646,6 +667,7 @@
         case ACPI_DMT_ACCWIDTH:
         case ACPI_DMT_IVRS:
         case ACPI_DMT_MADT:
+        case ACPI_DMT_PMTT:
         case ACPI_DMT_SRAT:
         case ACPI_DMT_ASF:
         case ACPI_DMT_HESTNTYP:
@@ -670,6 +692,10 @@
         case ACPI_DMT_SLIC:
             ByteLength = 4;
             break;
+        case ACPI_DMT_UINT40:
+            ByteLength = 5;
+            break;
+        case ACPI_DMT_UINT48:
         case ACPI_DMT_NAME6:
             ByteLength = 6;
             break;
@@ -718,6 +744,12 @@
             return (AE_BAD_DATA);
         }
 
+        if (Info->Opcode == ACPI_DMT_EXTRA_TEXT)
+        {
+            AcpiOsPrintf ("%s", Info->Name);
+            continue;
+        }
+
         /* Start a new line and decode the opcode */
 
         AcpiDmLineHeader (CurrentOffset, ByteLength, Info->Name);
@@ -745,49 +777,42 @@
             AcpiOsPrintf ("%1.1X\n", *Target & 0x03);
             break;
 
+        case ACPI_DMT_FLAGS1:
+
+            AcpiOsPrintf ("%1.1X\n", (*Target >> 1) & 0x03);
+            break;
+
         case ACPI_DMT_FLAGS2:
 
             AcpiOsPrintf ("%1.1X\n", (*Target >> 2) & 0x03);
             break;
 
-        /* Standard Data Types */
+        case ACPI_DMT_FLAGS4:
+
+            AcpiOsPrintf ("%1.1X\n", (*Target >> 4) & 0x03);
+            break;
+
+        /* Integer Data Types */
 
         case ACPI_DMT_UINT8:
-
-            AcpiOsPrintf ("%2.2X\n", *Target);
-            break;
-
         case ACPI_DMT_UINT16:
-
-            AcpiOsPrintf ("%4.4X\n", ACPI_GET16 (Target));
-            break;
-
         case ACPI_DMT_UINT24:
-
-            AcpiOsPrintf ("%2.2X%2.2X%2.2X\n",
-                *Target, *(Target + 1), *(Target + 2));
-            break;
-
         case ACPI_DMT_UINT32:
-
-            AcpiOsPrintf ("%8.8X\n", ACPI_GET32 (Target));
-            break;
-
+        case ACPI_DMT_UINT40:
+        case ACPI_DMT_UINT48:
         case ACPI_DMT_UINT56:
-
-            for (Temp8 = 0; Temp8 < 7; Temp8++)
+        case ACPI_DMT_UINT64:
+            /*
+             * Dump bytes - high byte first, low byte last.
+             * Note: All ACPI tables are little-endian.
+             */
+            for (Temp8 = (UINT8) ByteLength; Temp8 > 0; Temp8--)
             {
-                AcpiOsPrintf ("%2.2X", Target[Temp8]);
+                AcpiOsPrintf ("%2.2X", Target[Temp8 - 1]);
             }
             AcpiOsPrintf ("\n");
             break;
 
-        case ACPI_DMT_UINT64:
-
-            AcpiOsPrintf ("%8.8X%8.8X\n",
-                ACPI_FORMAT_UINT64 (ACPI_GET64 (Target)));
-            break;
-
         case ACPI_DMT_BUF7:
         case ACPI_DMT_BUF16:
         case ACPI_DMT_BUF128:
@@ -1040,6 +1065,19 @@
             AcpiOsPrintf (UINT8_FORMAT, *Target, AcpiDmMadtSubnames[Temp8]);
             break;
 
+        case ACPI_DMT_PMTT:
+
+            /* PMTT subtable types */
+
+            Temp8 = *Target;
+            if (Temp8 > ACPI_PMTT_TYPE_RESERVED)
+            {
+                Temp8 = ACPI_PMTT_TYPE_RESERVED;
+            }
+
+            AcpiOsPrintf (UINT8_FORMAT, *Target, AcpiDmPmttSubnames[Temp8]);
+            break;
+
         case ACPI_DMT_SLIC:
 
             /* SLIC subtable types */
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/common/dmtbdump.c
--- a/head/sys/contrib/dev/acpica/common/dmtbdump.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/common/dmtbdump.c	Tue Dec 06 20:26:16 2011 +0200
@@ -230,11 +230,18 @@
         AcpiDmDumpTable (Table->Length, 0, Table, 0, AcpiDmTableInfoFadt2);
     }
 
-    /* Check for FADT revision 3 fields and up (ACPI 2.0+ extended data) */
+    /* Check for FADT revision 3/4 fields and up (ACPI 2.0+ extended data) */
 
     else if (Table->Length > ACPI_FADT_V2_SIZE)
     {
         AcpiDmDumpTable (Table->Length, 0, Table, 0, AcpiDmTableInfoFadt3);
+
+        /* Check for FADT revision 5 fields and up (ACPI 5.0+) */
+
+        if (Table->Length > ACPI_FADT_V3_SIZE)
+        {
+            AcpiDmDumpTable (Table->Length, 0, Table, 0, AcpiDmTableInfoFadt5);
+        }
     }
 
     /* Validate various fields in the FADT, including length */
@@ -290,6 +297,10 @@
         ExpectedLength = ACPI_FADT_V3_SIZE;
         break;
 
+    case 5:
+        ExpectedLength = ACPI_FADT_V5_SIZE;
+        break;
+
     default:
         return;
     }
@@ -751,6 +762,84 @@
 
 /*******************************************************************************
  *
+ * FUNCTION:    AcpiDmDumpFpdt
+ *
+ * PARAMETERS:  Table               - A FPDT table
+ *
+ * RETURN:      None
+ *
+ * DESCRIPTION: Format the contents of a FPDT. This table type consists
+ *              of an open-ended number of subtables.
+ *
+ ******************************************************************************/
+
+void
+AcpiDmDumpFpdt (
+    ACPI_TABLE_HEADER       *Table)
+{
+    ACPI_STATUS             Status;
+    ACPI_FPDT_HEADER        *SubTable;
+    UINT32                  Length = Table->Length;
+    UINT32                  Offset = sizeof (ACPI_TABLE_FPDT);
+    ACPI_DMTABLE_INFO       *InfoTable;
+
+
+    /* There is no main table (other than the standard ACPI header) */
+
+    /* Sub-tables */
+
+    SubTable = ACPI_ADD_PTR (ACPI_FPDT_HEADER, Table, Offset);
+    while (Offset < Table->Length)
+    {
+        /* Common sub-table header */
+
+        AcpiOsPrintf ("\n");
+        Status = AcpiDmDumpTable (Length, Offset, SubTable,
+                    SubTable->Length, AcpiDmTableInfoFpdtHdr);
+        if (ACPI_FAILURE (Status))
+        {
+            return;
+        }
+
+        switch (SubTable->Type)
+        {
+        case ACPI_FPDT_TYPE_BOOT:
+            InfoTable = AcpiDmTableInfoFpdt0;
+            break;
+        case ACPI_FPDT_TYPE_S3PERF:
+            InfoTable = AcpiDmTableInfoFpdt1;
+            break;
+        default:
+            AcpiOsPrintf ("\n**** Unknown FPDT sub-table type 0x%X\n\n", SubTable->Type);
+
+            /* Attempt to continue */
+
+            if (!SubTable->Length)
+            {
+                AcpiOsPrintf ("Invalid zero length subtable\n");
+                return;
+            }
+            goto NextSubTable;
+        }
+
+        Status = AcpiDmDumpTable (Length, Offset, SubTable,
+                    SubTable->Length, InfoTable);
+        if (ACPI_FAILURE (Status))
+        {
+            return;
+        }
+
+NextSubTable:
+        /* Point to next sub-table */
+
+        Offset += SubTable->Length;
+        SubTable = ACPI_ADD_PTR (ACPI_FPDT_HEADER, SubTable, SubTable->Length);
+    }
+}
+
+
+/*******************************************************************************
+ *
  * FUNCTION:    AcpiDmDumpHest
  *
  * PARAMETERS:  Table               - A HEST table
@@ -1134,6 +1223,12 @@
         case ACPI_MADT_TYPE_LOCAL_X2APIC_NMI:
             InfoTable = AcpiDmTableInfoMadt10;
             break;
+        case ACPI_MADT_TYPE_GENERIC_INTERRUPT:
+            InfoTable = AcpiDmTableInfoMadt11;
+            break;
+        case ACPI_MADT_TYPE_GENERIC_DISTRIBUTOR:
+            InfoTable = AcpiDmTableInfoMadt12;
+            break;
         default:
             AcpiOsPrintf ("\n**** Unknown MADT sub-table type 0x%X\n\n", SubTable->Type);
 
@@ -1223,6 +1318,150 @@
 
 /*******************************************************************************
  *
+ * FUNCTION:    AcpiDmDumpMpst
+ *
+ * PARAMETERS:  Table               - A MPST Table
+ *
+ * RETURN:      None
+ *
+ * DESCRIPTION: Format the contents of a MPST table
+ *
+ ******************************************************************************/
+
+void
+AcpiDmDumpMpst (
+    ACPI_TABLE_HEADER       *Table)
+{
+    ACPI_STATUS             Status;
+    UINT32                  Offset = sizeof (ACPI_TABLE_MPST);
+    ACPI_MPST_POWER_NODE    *SubTable0;
+    ACPI_MPST_POWER_STATE   *SubTable0A;
+    ACPI_MPST_COMPONENT     *SubTable0B;
+    ACPI_MPST_DATA_HDR      *SubTable1;
+    ACPI_MPST_POWER_DATA    *SubTable2;
+    UINT16                  SubtableCount;
+    UINT8                   PowerStateCount;
+    UINT8                   ComponentCount;
+
+
+    /* Main table */
+
+    Status = AcpiDmDumpTable (Table->Length, 0, Table, 0, AcpiDmTableInfoMpst);
+    if (ACPI_FAILURE (Status))
+    {
+        return;
+    }
+
+    /* Subtable: Memory Power Node(s) */
+
+    SubtableCount = (ACPI_CAST_PTR (ACPI_TABLE_MPST, Table))->PowerNodeCount;
+    SubTable0 = ACPI_ADD_PTR (ACPI_MPST_POWER_NODE, Table, Offset);
+
+    while ((Offset < Table->Length) && SubtableCount)
+    {
+        AcpiOsPrintf ("\n");
+        Status = AcpiDmDumpTable (Table->Length, Offset, SubTable0,
+                    sizeof (ACPI_MPST_POWER_NODE), AcpiDmTableInfoMpst0);
+        if (ACPI_FAILURE (Status))
+        {
+            return;
+        }
+
+        /* Extract the sub-subtable counts */
+
+        PowerStateCount = SubTable0->NumPowerStates;
+        ComponentCount = SubTable0->NumPhysicalComponents;
+        Offset += sizeof (ACPI_MPST_POWER_NODE);
+
+        /* Sub-subtables - Memory Power State Structure(s) */
+
+        SubTable0A = ACPI_ADD_PTR (ACPI_MPST_POWER_STATE, SubTable0,
+            sizeof (ACPI_MPST_POWER_NODE));
+
+        while (PowerStateCount)
+        {
+            AcpiOsPrintf ("\n");
+            Status = AcpiDmDumpTable (Table->Length, Offset, SubTable0A,
+                        sizeof (ACPI_MPST_POWER_STATE), AcpiDmTableInfoMpst0A);
+            if (ACPI_FAILURE (Status))
+            {
+                return;
+            }
+
+            SubTable0A++;
+            PowerStateCount--;
+            Offset += sizeof (ACPI_MPST_POWER_STATE);
+       }
+
+        /* Sub-subtables - Physical Component ID Structure(s) */
+
+        SubTable0B = ACPI_CAST_PTR (ACPI_MPST_COMPONENT, SubTable0A);
+
+        if (ComponentCount)
+        {
+            AcpiOsPrintf ("\n");
+        }
+
+        while (ComponentCount)
+        {
+            Status = AcpiDmDumpTable (Table->Length, Offset, SubTable0B,
+                        sizeof (ACPI_MPST_COMPONENT), AcpiDmTableInfoMpst0B);
+            if (ACPI_FAILURE (Status))
+            {
+                return;
+            }
+
+            SubTable0B++;
+            ComponentCount--;
+            Offset += sizeof (ACPI_MPST_COMPONENT);
+        }
+
+        /* Point to next Memory Power Node subtable */
+
+        SubtableCount--;
+        SubTable0 = ACPI_ADD_PTR (ACPI_MPST_POWER_NODE, SubTable0,
+            sizeof (ACPI_MPST_POWER_NODE) +
+            (sizeof (ACPI_MPST_POWER_STATE) * SubTable0->NumPowerStates) +
+            (sizeof (ACPI_MPST_COMPONENT) * SubTable0->NumPhysicalComponents));
+    }
+
+    /* Subtable: Count of Memory Power State Characteristic structures */
+
+    AcpiOsPrintf ("\n");
+    SubTable1 = ACPI_CAST_PTR (ACPI_MPST_DATA_HDR, SubTable0);
+    Status = AcpiDmDumpTable (Table->Length, Offset, SubTable1,
+                sizeof (ACPI_MPST_DATA_HDR), AcpiDmTableInfoMpst1);
+    if (ACPI_FAILURE (Status))
+    {
+        return;
+    }
+
+    SubtableCount = SubTable1->CharacteristicsCount;
+    Offset += sizeof (ACPI_MPST_DATA_HDR);
+
+    /* Subtable: Memory Power State Characteristics structure(s) */
+
+    SubTable2 = ACPI_ADD_PTR (ACPI_MPST_POWER_DATA, SubTable1, sizeof (ACPI_MPST_DATA_HDR));
+
+    while ((Offset < Table->Length) && SubtableCount)
+    {
+        AcpiOsPrintf ("\n");
+        Status = AcpiDmDumpTable (Table->Length, Offset, SubTable2,
+                    sizeof (ACPI_MPST_POWER_DATA), AcpiDmTableInfoMpst2);
+        if (ACPI_FAILURE (Status))
+        {
+            return;
+        }
+
+        SubTable2++;
+        SubtableCount--;
+        Offset += sizeof (ACPI_MPST_POWER_DATA);
+    }
+}
+
+
+/*******************************************************************************
+ *
  * FUNCTION:    AcpiDmDumpMsct
  *
  * PARAMETERS:  Table               - A MSCT table
@@ -1275,6 +1514,349 @@
 
 /*******************************************************************************
  *
+ * FUNCTION:    AcpiDmDumpPcct
+ *
+ * PARAMETERS:  Table               - A PCCT table
+ *
+ * RETURN:      None
+ *
+ * DESCRIPTION: Format the contents of a PCCT. This table type consists
+ *              of an open-ended number of subtables.
+ *
+ ******************************************************************************/
+
+void
+AcpiDmDumpPcct (
+    ACPI_TABLE_HEADER       *Table)
+{
+    ACPI_STATUS             Status;
+    ACPI_PCCT_SUBSPACE      *SubTable;
+    UINT32                  Length = Table->Length;
+    UINT32                  Offset = sizeof (ACPI_TABLE_PCCT);
+
+
+    /* Main table */
+
+    Status = AcpiDmDumpTable (Length, 0, Table, 0, AcpiDmTableInfoPcct);
+    if (ACPI_FAILURE (Status))
+    {
+        return;
+    }
+
+    /* Sub-tables */
+
+    SubTable = ACPI_ADD_PTR (ACPI_PCCT_SUBSPACE, Table, Offset);
+    while (Offset < Table->Length)
+    {
+        AcpiOsPrintf ("\n");
+        Status = AcpiDmDumpTable (Length, Offset, SubTable,
+                    SubTable->Header.Length, AcpiDmTableInfoPcct0);
+        if (ACPI_FAILURE (Status))
+        {
+            return;
+        }
+
+        /* Point to next sub-table */
+
+        Offset += SubTable->Header.Length;
+        SubTable = ACPI_ADD_PTR (ACPI_PCCT_SUBSPACE, SubTable,
+                    SubTable->Header.Length);
+    }
+}
+
+
+/*******************************************************************************
+ *
+ * FUNCTION:    AcpiDmDumpPmtt
+ *
+ * PARAMETERS:  Table               - A PMTT table
+ *
+ * RETURN:      None
+ *
+ * DESCRIPTION: Format the contents of a PMTT. This table type consists
+ *              of an open-ended number of subtables.
+ *
+ ******************************************************************************/
+
+void
+AcpiDmDumpPmtt (
+    ACPI_TABLE_HEADER       *Table)
+{
+    ACPI_STATUS             Status;
+    ACPI_PMTT_HEADER        *SubTable;
+    ACPI_PMTT_HEADER        *MemSubTable;
+    ACPI_PMTT_HEADER        *DimmSubTable;
+    ACPI_PMTT_DOMAIN        *DomainArray;
+    UINT32                  Length = Table->Length;
+    UINT32                  Offset = sizeof (ACPI_TABLE_PMTT);
+    UINT32                  MemOffset;
+    UINT32                  DimmOffset;
+    UINT32                  DomainOffset;
+    UINT32                  DomainCount;
+
+
+    /* Main table */
+
+    Status = AcpiDmDumpTable (Length, 0, Table, 0, AcpiDmTableInfoPmtt);
+    if (ACPI_FAILURE (Status))
+    {
+        return;
+    }
+
+    /* Subtables */
+
+    SubTable = ACPI_ADD_PTR (ACPI_PMTT_HEADER, Table, Offset);
+    while (Offset < Table->Length)
+    {
+        /* Common subtable header */
+
+        AcpiOsPrintf ("\n");
+        Status = AcpiDmDumpTable (Length, Offset, SubTable,
+                    SubTable->Length, AcpiDmTableInfoPmttHdr);
+        if (ACPI_FAILURE (Status))
+        {
+            return;
+        }
+
+        /* Only Socket subtables are expected at this level */
+
+        if (SubTable->Type != ACPI_PMTT_TYPE_SOCKET)
+        {
+            AcpiOsPrintf (
+                "\n**** Unexpected or unknown PMTT subtable type 0x%X\n\n",
+                SubTable->Type);
+            return;
+        }
+
+        /* Dump the fixed-length portion of the subtable */
+
+        Status = AcpiDmDumpTable (Length, Offset, SubTable,
+                    SubTable->Length, AcpiDmTableInfoPmtt0);
+        if (ACPI_FAILURE (Status))
+        {
+            return;
+        }
+
+        /* Walk the memory controller subtables */
+
+        MemOffset = sizeof (ACPI_PMTT_SOCKET);
+        MemSubTable = ACPI_ADD_PTR (ACPI_PMTT_HEADER, SubTable,
+            sizeof (ACPI_PMTT_SOCKET));
+
+        while (((Offset + MemOffset) < Table->Length) &&
+            (MemOffset < SubTable->Length))
+        {
+            /* Common subtable header */
+
+            AcpiOsPrintf ("\n");
+            Status = AcpiDmDumpTable (Length,
+                        Offset + MemOffset, MemSubTable,
+                        MemSubTable->Length, AcpiDmTableInfoPmttHdr);
+            if (ACPI_FAILURE (Status))
+            {
+                return;
+            }
+
+            /* Only memory controller subtables are expected at this level */
+
+            if (MemSubTable->Type != ACPI_PMTT_TYPE_CONTROLLER)
+            {
+                AcpiOsPrintf (
+                    "\n**** Unexpected or unknown PMTT subtable type 0x%X\n\n",
+                    MemSubTable->Type);
+                return;
+            }
+
+            /* Dump the fixed-length portion of the controller subtable */
+
+            Status = AcpiDmDumpTable (Length,
+                        Offset + MemOffset, MemSubTable,
+                        MemSubTable->Length, AcpiDmTableInfoPmtt1);
+            if (ACPI_FAILURE (Status))
+            {
+                return;
+            }
+
+            /* Walk the variable count of proximity domains */
+
+            DomainCount = ((ACPI_PMTT_CONTROLLER *) MemSubTable)->DomainCount;
+            DomainOffset = sizeof (ACPI_PMTT_CONTROLLER);
+            DomainArray = ACPI_ADD_PTR (ACPI_PMTT_DOMAIN, MemSubTable,
+                sizeof (ACPI_PMTT_CONTROLLER));
+
+            while (((Offset + MemOffset + DomainOffset) < Table->Length) &&
+                ((MemOffset + DomainOffset) < SubTable->Length) &&
+                DomainCount)
+            {
+                Status = AcpiDmDumpTable (Length,
+                            Offset + MemOffset + DomainOffset, DomainArray,
+                            sizeof (ACPI_PMTT_DOMAIN), AcpiDmTableInfoPmtt1a);
+                if (ACPI_FAILURE (Status))
+                {
+                    return;
+                }
+
+                DomainOffset += sizeof (ACPI_PMTT_DOMAIN);
+                DomainArray++;
+                DomainCount--;
+            }
+
+            if (DomainCount)
+            {
+                AcpiOsPrintf (
+                    "\n**** DomainCount exceeds subtable length\n\n",
+                    MemSubTable->Type);
+            }
+
+            /* Walk the physical component (DIMM) subtables */
+
+            DimmOffset = DomainOffset;
+            DimmSubTable = ACPI_ADD_PTR (ACPI_PMTT_HEADER, MemSubTable,
+                DomainOffset);
+
+            while (((Offset + MemOffset + DimmOffset) < Table->Length) &&
+                (DimmOffset < MemSubTable->Length))
+            {
+                /* Common subtable header */
+
+                AcpiOsPrintf ("\n");
+                Status = AcpiDmDumpTable (Length,
+                            Offset + MemOffset + DimmOffset, DimmSubTable,
+                            DimmSubTable->Length, AcpiDmTableInfoPmttHdr);
+                if (ACPI_FAILURE (Status))
+                {
+                    return;
+                }
+
+                /* Only DIMM subtables are expected at this level */
+
+                if (DimmSubTable->Type != ACPI_PMTT_TYPE_DIMM)
+                {
+                    AcpiOsPrintf (
+                        "\n**** Unexpected or unknown PMTT subtable type 0x%X\n\n",
+                        DimmSubTable->Type);
+                    return;
+                }
+
+                /* Dump the fixed-length DIMM subtable */
+
+                Status = AcpiDmDumpTable (Length,
+                            Offset + MemOffset + DimmOffset, DimmSubTable,
+                            DimmSubTable->Length, AcpiDmTableInfoPmtt2);
+                if (ACPI_FAILURE (Status))
+                {
+                    return;
+                }
+
+                /* Point to next DIMM subtable */
+
+                DimmOffset += DimmSubTable->Length;
+                DimmSubTable = ACPI_ADD_PTR (ACPI_PMTT_HEADER,
+                    DimmSubTable, DimmSubTable->Length);
+            }
+
+            /* Point to next Controller subtable */
+
+            MemOffset += MemSubTable->Length;
+            MemSubTable = ACPI_ADD_PTR (ACPI_PMTT_HEADER,
+                MemSubTable, MemSubTable->Length);
+        }
+
+        /* Point to next Socket subtable */
+
+        Offset += SubTable->Length;
+        SubTable = ACPI_ADD_PTR (ACPI_PMTT_HEADER,
+            SubTable, SubTable->Length);
+    }
+}
+
+
+/*******************************************************************************
+ *
+ * FUNCTION:    AcpiDmDumpS3pt
+ *
+ * PARAMETERS:  Table               - A S3PT table
+ *
+ * RETURN:      Length of the table
+ *
+ * DESCRIPTION: Format the contents of a S3PT
+ *
+ ******************************************************************************/
+
+UINT32
+AcpiDmDumpS3pt (
+    ACPI_TABLE_HEADER       *Tables)
+{
+    ACPI_STATUS             Status;
+    UINT32                  Offset = sizeof (ACPI_TABLE_S3PT);
+    ACPI_S3PT_HEADER        *SubTable;
+    ACPI_DMTABLE_INFO       *InfoTable;
+    ACPI_TABLE_S3PT         *S3ptTable = ACPI_CAST_PTR (ACPI_TABLE_S3PT, Tables);
+
+
+    /* Main table */
+
+    Status = AcpiDmDumpTable (Offset, 0, S3ptTable, 0, AcpiDmTableInfoS3pt);
+    if (ACPI_FAILURE (Status))
+    {
+        return 0;
+    }
+
+    SubTable = ACPI_ADD_PTR (ACPI_S3PT_HEADER, S3ptTable, Offset);
+    while (Offset < S3ptTable->Length)
+    {
+        /* Common sub-table header */
+
+        AcpiOsPrintf ("\n");
+        Status = AcpiDmDumpTable (S3ptTable->Length, Offset, SubTable,
+                    SubTable->Length, AcpiDmTableInfoS3ptHdr);
+        if (ACPI_FAILURE (Status))
+        {
+            return 0;
+        }
+
+        switch (SubTable->Type)
+        {
+        case ACPI_S3PT_TYPE_RESUME:
+            InfoTable = AcpiDmTableInfoS3pt0;
+            break;
+        case ACPI_S3PT_TYPE_SUSPEND:
+            InfoTable = AcpiDmTableInfoS3pt1;
+            break;
+        default:
+            AcpiOsPrintf ("\n**** Unknown S3PT sub-table type 0x%X\n", SubTable->Type);
+
+            /* Attempt to continue */
+
+            if (!SubTable->Length)
+            {
+                AcpiOsPrintf ("Invalid zero length subtable\n");
+                return 0;
+            }
+            goto NextSubTable;
+        }
+
+        AcpiOsPrintf ("\n");
+        Status = AcpiDmDumpTable (S3ptTable->Length, Offset, SubTable,
+                    SubTable->Length, InfoTable);
+        if (ACPI_FAILURE (Status))
+        {
+            return 0;
+        }
+
+NextSubTable:
+        /* Point to next sub-table */
+
+        Offset += SubTable->Length;
+        SubTable = ACPI_ADD_PTR (ACPI_S3PT_HEADER, SubTable, SubTable->Length);
+    }
+
+    return (S3ptTable->Length);
+}
+
+
+/*******************************************************************************
+ *
  * FUNCTION:    AcpiDmDumpSlic
  *
  * PARAMETERS:  Table               - A SLIC table
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/common/dmtbinfo.c
--- a/head/sys/contrib/dev/acpica/common/dmtbinfo.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/common/dmtbinfo.c	Tue Dec 06 20:26:16 2011 +0200
@@ -82,21 +82,28 @@
 #define ACPI_GAS_OFFSET(f)              (UINT8) ACPI_OFFSET (ACPI_GENERIC_ADDRESS,f)
 #define ACPI_HDR_OFFSET(f)              (UINT8) ACPI_OFFSET (ACPI_TABLE_HEADER,f)
 #define ACPI_RSDP_OFFSET(f)             (UINT8) ACPI_OFFSET (ACPI_TABLE_RSDP,f)
+#define ACPI_BERT_OFFSET(f)             (UINT8) ACPI_OFFSET (ACPI_TABLE_BERT,f)
+#define ACPI_BGRT_OFFSET(f)             (UINT8) ACPI_OFFSET (ACPI_TABLE_BGRT,f)
 #define ACPI_BOOT_OFFSET(f)             (UINT8) ACPI_OFFSET (ACPI_TABLE_BOOT,f)
-#define ACPI_BERT_OFFSET(f)             (UINT8) ACPI_OFFSET (ACPI_TABLE_BERT,f)
 #define ACPI_CPEP_OFFSET(f)             (UINT8) ACPI_OFFSET (ACPI_TABLE_CPEP,f)
 #define ACPI_DBGP_OFFSET(f)             (UINT8) ACPI_OFFSET (ACPI_TABLE_DBGP,f)
 #define ACPI_DMAR_OFFSET(f)             (UINT8) ACPI_OFFSET (ACPI_TABLE_DMAR,f)
+#define ACPI_DRTM_OFFSET(f)             (UINT8) ACPI_OFFSET (ACPI_TABLE_DRTM,f)
 #define ACPI_ECDT_OFFSET(f)             (UINT8) ACPI_OFFSET (ACPI_TABLE_ECDT,f)
 #define ACPI_EINJ_OFFSET(f)             (UINT8) ACPI_OFFSET (ACPI_TABLE_EINJ,f)
 #define ACPI_ERST_OFFSET(f)             (UINT8) ACPI_OFFSET (ACPI_TABLE_ERST,f)
+#define ACPI_GTDT_OFFSET(f)             (UINT8) ACPI_OFFSET (ACPI_TABLE_GTDT,f)
 #define ACPI_HEST_OFFSET(f)             (UINT8) ACPI_OFFSET (ACPI_TABLE_HEST,f)
 #define ACPI_HPET_OFFSET(f)             (UINT8) ACPI_OFFSET (ACPI_TABLE_HPET,f)
 #define ACPI_IVRS_OFFSET(f)             (UINT8) ACPI_OFFSET (ACPI_TABLE_IVRS,f)
 #define ACPI_MADT_OFFSET(f)             (UINT8) ACPI_OFFSET (ACPI_TABLE_MADT,f)
 #define ACPI_MCFG_OFFSET(f)             (UINT8) ACPI_OFFSET (ACPI_TABLE_MCFG,f)
 #define ACPI_MCHI_OFFSET(f)             (UINT8) ACPI_OFFSET (ACPI_TABLE_MCHI,f)
+#define ACPI_MPST_OFFSET(f)             (UINT8) ACPI_OFFSET (ACPI_TABLE_MPST,f)
 #define ACPI_MSCT_OFFSET(f)             (UINT8) ACPI_OFFSET (ACPI_TABLE_MSCT,f)
+#define ACPI_PCCT_OFFSET(f)             (UINT8) ACPI_OFFSET (ACPI_TABLE_PCCT,f)
+#define ACPI_PMTT_OFFSET(f)             (UINT8) ACPI_OFFSET (ACPI_TABLE_PMTT,f)
+#define ACPI_S3PT_OFFSET(f)             (UINT8) ACPI_OFFSET (ACPI_TABLE_S3PT,f)
 #define ACPI_SBST_OFFSET(f)             (UINT8) ACPI_OFFSET (ACPI_TABLE_SBST,f)
 #define ACPI_SLIT_OFFSET(f)             (UINT8) ACPI_OFFSET (ACPI_TABLE_SLIT,f)
 #define ACPI_SPCR_OFFSET(f)             (UINT8) ACPI_OFFSET (ACPI_TABLE_SPCR,f)
@@ -126,6 +133,9 @@
 #define ACPI_DMAR3_OFFSET(f)            (UINT8) ACPI_OFFSET (ACPI_DMAR_RHSA,f)
 #define ACPI_EINJ0_OFFSET(f)            (UINT8) ACPI_OFFSET (ACPI_WHEA_HEADER,f)
 #define ACPI_ERST0_OFFSET(f)            (UINT8) ACPI_OFFSET (ACPI_WHEA_HEADER,f)
+#define ACPI_FPDTH_OFFSET(f)            (UINT8) ACPI_OFFSET (ACPI_FPDT_HEADER,f)
+#define ACPI_FPDT0_OFFSET(f)            (UINT8) ACPI_OFFSET (ACPI_FPDT_BOOT,f)
+#define ACPI_FPDT1_OFFSET(f)            (UINT8) ACPI_OFFSET (ACPI_FPDT_S3PT_PTR,f)
 #define ACPI_HEST0_OFFSET(f)            (UINT8) ACPI_OFFSET (ACPI_HEST_IA_MACHINE_CHECK,f)
 #define ACPI_HEST1_OFFSET(f)            (UINT8) ACPI_OFFSET (ACPI_HEST_IA_CORRECTED,f)
 #define ACPI_HEST2_OFFSET(f)            (UINT8) ACPI_OFFSET (ACPI_HEST_IA_NMI,f)
@@ -153,9 +163,25 @@
 #define ACPI_MADT8_OFFSET(f)            (UINT8) ACPI_OFFSET (ACPI_MADT_INTERRUPT_SOURCE,f)
 #define ACPI_MADT9_OFFSET(f)            (UINT8) ACPI_OFFSET (ACPI_MADT_LOCAL_X2APIC,f)
 #define ACPI_MADT10_OFFSET(f)           (UINT8) ACPI_OFFSET (ACPI_MADT_LOCAL_X2APIC_NMI,f)
+#define ACPI_MADT11_OFFSET(f)           (UINT8) ACPI_OFFSET (ACPI_MADT_GENERIC_INTERRUPT,f)
+#define ACPI_MADT12_OFFSET(f)           (UINT8) ACPI_OFFSET (ACPI_MADT_GENERIC_DISTRIBUTOR,f)
 #define ACPI_MADTH_OFFSET(f)            (UINT8) ACPI_OFFSET (ACPI_SUBTABLE_HEADER,f)
 #define ACPI_MCFG0_OFFSET(f)            (UINT8) ACPI_OFFSET (ACPI_MCFG_ALLOCATION,f)
+#define ACPI_MPST0_OFFSET(f)            (UINT8) ACPI_OFFSET (ACPI_MPST_POWER_NODE,f)
+#define ACPI_MPST0A_OFFSET(f)           (UINT8) ACPI_OFFSET (ACPI_MPST_POWER_STATE,f)
+#define ACPI_MPST0B_OFFSET(f)           (UINT8) ACPI_OFFSET (ACPI_MPST_COMPONENT,f)
+#define ACPI_MPST1_OFFSET(f)            (UINT8) ACPI_OFFSET (ACPI_MPST_DATA_HDR,f)
+#define ACPI_MPST2_OFFSET(f)            (UINT8) ACPI_OFFSET (ACPI_MPST_POWER_DATA,f)
 #define ACPI_MSCT0_OFFSET(f)            (UINT8) ACPI_OFFSET (ACPI_MSCT_PROXIMITY,f)
+#define ACPI_PCCT0_OFFSET(f)            (UINT8) ACPI_OFFSET (ACPI_PCCT_SUBSPACE,f)
+#define ACPI_PMTT0_OFFSET(f)            (UINT8) ACPI_OFFSET (ACPI_PMTT_SOCKET,f)
+#define ACPI_PMTT1_OFFSET(f)            (UINT8) ACPI_OFFSET (ACPI_PMTT_CONTROLLER,f)
+#define ACPI_PMTT1A_OFFSET(f)           (UINT8) ACPI_OFFSET (ACPI_PMTT_DOMAIN,f)
+#define ACPI_PMTT2_OFFSET(f)            (UINT8) ACPI_OFFSET (ACPI_PMTT_PHYSICAL_COMPONENT,f)
+#define ACPI_PMTTH_OFFSET(f)            (UINT8) ACPI_OFFSET (ACPI_PMTT_HEADER,f)
+#define ACPI_S3PTH_OFFSET(f)            (UINT8) ACPI_OFFSET (ACPI_S3PT_HEADER,f)
+#define ACPI_S3PT0_OFFSET(f)            (UINT8) ACPI_OFFSET (ACPI_S3PT_RESUME,f)
+#define ACPI_S3PT1_OFFSET(f)            (UINT8) ACPI_OFFSET (ACPI_S3PT_SUSPEND,f)
 #define ACPI_SLICH_OFFSET(f)            (UINT8) ACPI_OFFSET (ACPI_SLIC_HEADER,f)
 #define ACPI_SLIC0_OFFSET(f)            (UINT8) ACPI_OFFSET (ACPI_SLIC_KEY,f)
 #define ACPI_SLIC1_OFFSET(f)            (UINT8) ACPI_OFFSET (ACPI_SLIC_MARKER,f)
@@ -178,6 +204,7 @@
 #define ACPI_SRAT0_FLAG_OFFSET(f,o)     ACPI_FLAG_OFFSET (ACPI_SRAT_CPU_AFFINITY,f,o)
 #define ACPI_SRAT1_FLAG_OFFSET(f,o)     ACPI_FLAG_OFFSET (ACPI_SRAT_MEM_AFFINITY,f,o)
 #define ACPI_SRAT2_FLAG_OFFSET(f,o)     ACPI_FLAG_OFFSET (ACPI_SRAT_X2APIC_CPU_AFFINITY,f,o)
+#define ACPI_GTDT_FLAG_OFFSET(f,o)      ACPI_FLAG_OFFSET (ACPI_TABLE_GTDT,f,o)
 #define ACPI_MADT_FLAG_OFFSET(f,o)      ACPI_FLAG_OFFSET (ACPI_TABLE_MADT,f,o)
 #define ACPI_MADT0_FLAG_OFFSET(f,o)     ACPI_FLAG_OFFSET (ACPI_MADT_LOCAL_APIC,f,o)
 #define ACPI_MADT2_FLAG_OFFSET(f,o)     ACPI_FLAG_OFFSET (ACPI_MADT_INTERRUPT_OVERRIDE,f,o)
@@ -187,6 +214,11 @@
 #define ACPI_MADT8_FLAG_OFFSET(f,o)     ACPI_FLAG_OFFSET (ACPI_MADT_INTERRUPT_SOURCE,f,o)
 #define ACPI_MADT9_FLAG_OFFSET(f,o)     ACPI_FLAG_OFFSET (ACPI_MADT_LOCAL_X2APIC,f,o)
 #define ACPI_MADT10_FLAG_OFFSET(f,o)    ACPI_FLAG_OFFSET (ACPI_MADT_LOCAL_X2APIC_NMI,f,o)
+#define ACPI_MADT11_FLAG_OFFSET(f,o)    ACPI_FLAG_OFFSET (ACPI_MADT_GENERIC_INTERRUPT,f,o)
+#define ACPI_MPST0_FLAG_OFFSET(f,o)     ACPI_FLAG_OFFSET (ACPI_MPST_POWER_NODE,f,o)
+#define ACPI_MPST2_FLAG_OFFSET(f,o)     ACPI_FLAG_OFFSET (ACPI_MPST_POWER_DATA,f,o)
+#define ACPI_PCCT_FLAG_OFFSET(f,o)      ACPI_FLAG_OFFSET (ACPI_TABLE_PCCT,f,o)
+#define ACPI_PMTTH_FLAG_OFFSET(f,o)     ACPI_FLAG_OFFSET (ACPI_PMTT_HEADER,f,o)
 #define ACPI_WDDT_FLAG_OFFSET(f,o)      ACPI_FLAG_OFFSET (ACPI_TABLE_WDDT,f,o)
 #define ACPI_EINJ0_FLAG_OFFSET(f,o)     ACPI_FLAG_OFFSET (ACPI_WHEA_HEADER,f,o)
 #define ACPI_ERST0_FLAG_OFFSET(f,o)     ACPI_FLAG_OFFSET (ACPI_WHEA_HEADER,f,o)
@@ -198,6 +230,7 @@
  * Required terminator for all tables below
  */
 #define ACPI_DMT_TERMINATOR             {ACPI_DMT_EXIT, 0, NULL, 0}
+#define ACPI_DMT_NEW_LINE               {ACPI_DMT_EXTRA_TEXT, 0, "\n", 0}
 
 
 /*
@@ -383,6 +416,9 @@
     {ACPI_DMT_FLAG1,    ACPI_FADT_FLAG_OFFSET (Flags,2),            "Remote Power-on capable (V4)", 0},
     {ACPI_DMT_FLAG2,    ACPI_FADT_FLAG_OFFSET (Flags,2),            "Use APIC Cluster Model (V4)", 0},
     {ACPI_DMT_FLAG3,    ACPI_FADT_FLAG_OFFSET (Flags,2),            "Use APIC Physical Destination Mode (V4)", 0},
+    {ACPI_DMT_FLAG4,    ACPI_FADT_FLAG_OFFSET (Flags,2),            "Hardware Reduced (V5)", 0},
+    {ACPI_DMT_FLAG5,    ACPI_FADT_FLAG_OFFSET (Flags,2),            "Prefer S0 Idle (V5)", 0},
+    {ACPI_DMT_FLAG6,    ACPI_FADT_FLAG_OFFSET (Flags,2),            "Use Sleep Register (V5)", 0},
     ACPI_DMT_TERMINATOR
 };
 
@@ -396,7 +432,7 @@
     ACPI_DMT_TERMINATOR
 };
 
-/* ACPI 2.0+ Extensions (FADT version 3+) */
+/* ACPI 2.0+ Extensions (FADT version 3 and 4) */
 
 ACPI_DMTABLE_INFO           AcpiDmTableInfoFadt3[] =
 {
@@ -416,6 +452,14 @@
     ACPI_DMT_TERMINATOR
 };
 
+/* ACPI 5.0 Extensions (FADT version 5) */
+
+ACPI_DMTABLE_INFO           AcpiDmTableInfoFadt5[] =
+{
+    {ACPI_DMT_GAS,      ACPI_FADT_OFFSET (SleepRegister),           "Sleep Register", 0},
+    ACPI_DMT_TERMINATOR
+};
+
 
 /*
  * Remaining tables are not consumed directly by the ACPICA subsystem
@@ -541,6 +585,24 @@
 
 /*******************************************************************************
  *
+ * BGRT -  Boot Graphics Resource Table (ACPI 5.0)
+ *
+ ******************************************************************************/
+
+ACPI_DMTABLE_INFO           AcpiDmTableInfoBgrt[] =
+{
+    {ACPI_DMT_UINT16,   ACPI_BGRT_OFFSET (Version),                 "Version", 0},
+    {ACPI_DMT_UINT8,    ACPI_BGRT_OFFSET (Status),                  "Status", 0},
+    {ACPI_DMT_UINT8,    ACPI_BGRT_OFFSET (ImageType),               "Image Type", 0},
+    {ACPI_DMT_UINT64,   ACPI_BGRT_OFFSET (ImageAddress),            "Image Address", 0},
+    {ACPI_DMT_UINT32,   ACPI_BGRT_OFFSET (ImageOffsetX),            "Image OffsetX", 0},
+    {ACPI_DMT_UINT32,   ACPI_BGRT_OFFSET (ImageOffsetY),            "Image OffsetY", 0},
+    ACPI_DMT_TERMINATOR
+};
+
+
+/*******************************************************************************
+ *
  * BOOT - Simple Boot Flag Table
  *
  ******************************************************************************/
@@ -672,6 +734,19 @@
 
 /*******************************************************************************
  *
+ * DRTM - Dynamic Root of Trust for Measurement table
+ *
+ ******************************************************************************/
+
+ACPI_DMTABLE_INFO           AcpiDmTableInfoDrtm[] =
+{
+
+    ACPI_DMT_TERMINATOR
+};
+
+
+/*******************************************************************************
+ *
  * ECDT - Embedded Controller Boot Resources Table
  *
  ******************************************************************************/
@@ -748,6 +823,82 @@
 
 /*******************************************************************************
  *
+ * FPDT - Firmware Performance Data Table (ACPI 5.0)
+ *
+ ******************************************************************************/
+
+/* Main table consists of only the standard ACPI header - subtables follow */
+
+/* FPDT subtable header */
+
+ACPI_DMTABLE_INFO           AcpiDmTableInfoFpdtHdr[] =
+{
+    {ACPI_DMT_UINT16,   ACPI_FPDTH_OFFSET (Type),                   "Subtable Type", 0},
+    {ACPI_DMT_UINT8,    ACPI_FPDTH_OFFSET (Length),                 "Length", DT_LENGTH},
+    {ACPI_DMT_UINT8,    ACPI_FPDTH_OFFSET (Revision),               "Revision", 0},
+    ACPI_DMT_TERMINATOR
+};
+
+/* 0: Firmware Basic Boot Performance Record */
+
+ACPI_DMTABLE_INFO           AcpiDmTableInfoFpdt0[] =
+{
+    {ACPI_DMT_UINT32,   ACPI_FPDT0_OFFSET (Reserved),               "Reserved", 0},
+    {ACPI_DMT_UINT64,   ACPI_FPDT0_OFFSET (ResetEnd),               "Reset End", 0},
+    {ACPI_DMT_UINT64,   ACPI_FPDT0_OFFSET (LoadStart),              "Load Image Start", 0},
+    {ACPI_DMT_UINT64,   ACPI_FPDT0_OFFSET (StartupStart),           "Start Image Start", 0},
+    {ACPI_DMT_UINT64,   ACPI_FPDT0_OFFSET (ExitServicesEntry),      "Exit Services Entry", 0},
+    {ACPI_DMT_UINT64,   ACPI_FPDT0_OFFSET (ExitServicesExit),       "Exit Services Exit", 0},
+    ACPI_DMT_TERMINATOR
+};
+
+/* 1: S3 Performance Table Pointer Record */
+
+ACPI_DMTABLE_INFO           AcpiDmTableInfoFpdt1[] =
+{
+    {ACPI_DMT_UINT32,   ACPI_FPDT1_OFFSET (Reserved),               "Reserved", 0},
+    {ACPI_DMT_UINT64,   ACPI_FPDT1_OFFSET (Address),                "S3PT Address", 0},
+    ACPI_DMT_TERMINATOR
+};
+
+
+/*******************************************************************************
+ *
+ * GTDT - Generic Timer Description Table
+ *
+ ******************************************************************************/
+
+ACPI_DMTABLE_INFO           AcpiDmTableInfoGtdt[] =
+{
+    {ACPI_DMT_UINT64,   ACPI_GTDT_OFFSET (Address),                 "Timer Address", 0},
+    {ACPI_DMT_UINT32,   ACPI_GTDT_OFFSET (Flags),                   "Flags (decoded below)", DT_FLAG},
+    {ACPI_DMT_FLAG0,    ACPI_GTDT_FLAG_OFFSET (Flags,0),            "Memory Present", 0},
+    ACPI_DMT_NEW_LINE,
+    {ACPI_DMT_UINT32,   ACPI_GTDT_OFFSET (SecurePl1Interrupt),      "Secure PL1 Interrupt", 0},
+    {ACPI_DMT_UINT32,   ACPI_GTDT_OFFSET (SecurePl1Flags),          "SPL1 Flags (decoded below)", DT_FLAG},
+    {ACPI_DMT_FLAG0,    ACPI_GTDT_FLAG_OFFSET (SecurePl1Flags,0),   "Trigger Mode", 0},
+    {ACPI_DMT_FLAG1,    ACPI_GTDT_FLAG_OFFSET (SecurePl1Flags,0),   "Polarity", 0},
+    ACPI_DMT_NEW_LINE,
+    {ACPI_DMT_UINT32,   ACPI_GTDT_OFFSET (NonSecurePl1Interrupt),   "Non-Secure PL1 Interrupt", 0},
+    {ACPI_DMT_UINT32,   ACPI_GTDT_OFFSET (NonSecurePl1Flags),       "NSPL1 Flags (decoded below)", DT_FLAG},
+    {ACPI_DMT_FLAG0,    ACPI_GTDT_FLAG_OFFSET (NonSecurePl1Flags,0),"Trigger Mode", 0},
+    {ACPI_DMT_FLAG1,    ACPI_GTDT_FLAG_OFFSET (NonSecurePl1Flags,0),"Polarity", 0},
+    ACPI_DMT_NEW_LINE,
+    {ACPI_DMT_UINT32,   ACPI_GTDT_OFFSET (VirtualTimerInterrupt),   "Virtual Timer Interrupt", 0},
+    {ACPI_DMT_UINT32,   ACPI_GTDT_OFFSET (VirtualTimerFlags),       "VT Flags (decoded below)", DT_FLAG},
+    {ACPI_DMT_FLAG0,    ACPI_GTDT_FLAG_OFFSET (VirtualTimerFlags,0),"Trigger Mode", 0},
+    {ACPI_DMT_FLAG1,    ACPI_GTDT_FLAG_OFFSET (VirtualTimerFlags,0),"Polarity", 0},
+    ACPI_DMT_NEW_LINE,
+    {ACPI_DMT_UINT32,   ACPI_GTDT_OFFSET (NonSecurePl2Interrupt),   "Non-Secure PL2 Interrupt", 0},
+    {ACPI_DMT_UINT32,   ACPI_GTDT_OFFSET (NonSecurePl2Flags),       "NSPL2 Flags (decoded below)", DT_FLAG},
+    {ACPI_DMT_FLAG0,    ACPI_GTDT_FLAG_OFFSET (NonSecurePl2Flags,0),"Trigger Mode", 0},
+    {ACPI_DMT_FLAG1,    ACPI_GTDT_FLAG_OFFSET (NonSecurePl2Flags,0),"Polarity", 0},
+    ACPI_DMT_TERMINATOR
+};
+
+
+/*******************************************************************************
+ *
  * HEST - Hardware Error Source table
  *
  ******************************************************************************/
@@ -1190,6 +1341,34 @@
     ACPI_DMT_TERMINATOR
 };
 
+/* 11: Generic Interrupt Controller (ACPI 5.0) */
+
+ACPI_DMTABLE_INFO           AcpiDmTableInfoMadt11[] =
+{
+    {ACPI_DMT_UINT16,   ACPI_MADT11_OFFSET (Reserved),              "Reserved", 0},
+    {ACPI_DMT_UINT32,   ACPI_MADT11_OFFSET (GicId),                 "Local GIC Hardware ID", 0},
+    {ACPI_DMT_UINT32,   ACPI_MADT11_OFFSET (Uid),                   "Processor UID", 0},
+    {ACPI_DMT_UINT32,   ACPI_MADT11_OFFSET (Flags),                 "Flags (decoded below)", DT_FLAG},
+    {ACPI_DMT_FLAG0,    ACPI_MADT11_FLAG_OFFSET (Flags,0),          "Processor Enabled", 0},
+    {ACPI_DMT_UINT32,   ACPI_MADT11_OFFSET (ParkingVersion),        "Parking Protocol Version", 0},
+    {ACPI_DMT_UINT32,   ACPI_MADT11_OFFSET (PerformanceInterrupt),  "Performance Interrupt", 0},
+    {ACPI_DMT_UINT64,   ACPI_MADT11_OFFSET (ParkedAddress),         "Parked Address", 0},
+    {ACPI_DMT_UINT64,   ACPI_MADT11_OFFSET (BaseAddress),           "Base Address", 0},
+    ACPI_DMT_TERMINATOR
+};
+
+/* 12: Generic Interrupt Distributor (ACPI 5.0) */
+
+ACPI_DMTABLE_INFO           AcpiDmTableInfoMadt12[] =
+{
+    {ACPI_DMT_UINT16,   ACPI_MADT12_OFFSET (Reserved),              "Reserved", 0},
+    {ACPI_DMT_UINT32,   ACPI_MADT12_OFFSET (GicId),                 "Local GIC Hardware ID", 0},
+    {ACPI_DMT_UINT64,   ACPI_MADT12_OFFSET (BaseAddress),           "Base Address", 0},
+    {ACPI_DMT_UINT32,   ACPI_MADT12_OFFSET (GlobalIrqBase),         "Interrupt Base", 0},
+    {ACPI_DMT_UINT32,   ACPI_MADT12_OFFSET (Reserved2),             "Reserved", 0},
+   ACPI_DMT_TERMINATOR
+};
+
 
 /*******************************************************************************
  *
@@ -1240,6 +1419,87 @@
 
 /*******************************************************************************
  *
+ * MPST - Memory Power State Table
+ *
+ ******************************************************************************/
+
+ACPI_DMTABLE_INFO           AcpiDmTableInfoMpst[] =
+{
+    {ACPI_DMT_UINT16,   ACPI_MPST_OFFSET (Reserved1),               "Reserved", 0},
+    {ACPI_DMT_UINT8,    ACPI_MPST_OFFSET (ChannelId),               "Channel ID", 0},
+    {ACPI_DMT_UINT8,    ACPI_MPST_OFFSET (Reserved2),               "Reserved", 0},
+    {ACPI_DMT_UINT16,   ACPI_MPST_OFFSET (PowerNodeCount),          "Power Node Count", 0},
+    ACPI_DMT_TERMINATOR
+};
+
+/* MPST subtables */
+
+/* 0: Memory Power Node Structure */
+
+ACPI_DMTABLE_INFO           AcpiDmTableInfoMpst0[] =
+{
+    {ACPI_DMT_UINT8,    ACPI_MPST0_OFFSET (Flags),                  "Flags (decoded below)", DT_FLAG},
+    {ACPI_DMT_FLAG0,    ACPI_MPST0_FLAG_OFFSET (Flags,0),           "Node Enabled", 0},
+    {ACPI_DMT_FLAG1,    ACPI_MPST0_FLAG_OFFSET (Flags,0),           "Power Managed", 0},
+    {ACPI_DMT_FLAG2,    ACPI_MPST0_FLAG_OFFSET (Flags,0),           "Hot Plug Capable", 0},
+
+    {ACPI_DMT_UINT8,    ACPI_MPST0_OFFSET (Reserved1),              "Reserved", 0},
+    {ACPI_DMT_UINT16,   ACPI_MPST0_OFFSET (NodeId),                 "Node ID", 0},
+    {ACPI_DMT_UINT32,   ACPI_MPST0_OFFSET (Length),                 "Length", DT_LENGTH},
+    {ACPI_DMT_UINT64,   ACPI_MPST0_OFFSET (RangeAddress),           "Range Address", 0},
+    {ACPI_DMT_UINT64,   ACPI_MPST0_OFFSET (RangeLength),            "Range Length", 0},
+    {ACPI_DMT_UINT8,    ACPI_MPST0_OFFSET (NumPowerStates),         "Num Power States", 0},
+    {ACPI_DMT_UINT8,    ACPI_MPST0_OFFSET (NumPhysicalComponents),  "Num Physical Components", 0},
+    {ACPI_DMT_UINT16,   ACPI_MPST0_OFFSET (Reserved2),              "Reserved", 0},
+    ACPI_DMT_TERMINATOR
+};
+
+/* 0A: Sub-subtable - Memory Power State Structure (follows Memory Power Node above) */
+
+ACPI_DMTABLE_INFO           AcpiDmTableInfoMpst0A[] =
+{
+    {ACPI_DMT_UINT8,    ACPI_MPST0A_OFFSET (PowerState),            "Power State", 0},
+    {ACPI_DMT_UINT8,    ACPI_MPST0A_OFFSET (InfoIndex),             "InfoIndex", 0},
+    ACPI_DMT_TERMINATOR
+};
+
+/* 0B: Sub-subtable - Physical Component ID Structure (follows Memory Power State(s) above) */
+
+ACPI_DMTABLE_INFO           AcpiDmTableInfoMpst0B[] =
+{
+    {ACPI_DMT_UINT16,   ACPI_MPST0B_OFFSET (ComponentId),           "Component Id", 0},
+    ACPI_DMT_TERMINATOR
+};
+
+/* 01: Power Characteristics Count (follows all Power Node(s) above) */
+
+ACPI_DMTABLE_INFO           AcpiDmTableInfoMpst1[] =
+{
+    {ACPI_DMT_UINT16,   ACPI_MPST1_OFFSET (CharacteristicsCount),   "Characteristics Count", 0},
+    ACPI_DMT_TERMINATOR
+};
+
+/* 02: Memory Power State Characteristics Structure */
+
+ACPI_DMTABLE_INFO           AcpiDmTableInfoMpst2[] =
+{
+    {ACPI_DMT_UINT8,    ACPI_MPST2_OFFSET (Revision),               "Revision", 0},
+    {ACPI_DMT_UINT8,    ACPI_MPST2_OFFSET (Flags),                  "Flags (decoded below)", DT_FLAG},
+    {ACPI_DMT_FLAG0,    ACPI_MPST2_FLAG_OFFSET (Flags,0),           "Memory Preserved", 0},
+    {ACPI_DMT_FLAG1,    ACPI_MPST2_FLAG_OFFSET (Flags,0),           "Auto Entry", 0},
+    {ACPI_DMT_FLAG2,    ACPI_MPST2_FLAG_OFFSET (Flags,0),           "Auto Exit", 0},
+
+    {ACPI_DMT_UINT16,   ACPI_MPST2_OFFSET (Reserved1),              "Reserved", 0},
+    {ACPI_DMT_UINT32,   ACPI_MPST2_OFFSET (AveragePower),           "Average Power", 0},
+    {ACPI_DMT_UINT32,   ACPI_MPST2_OFFSET (PowerSaving),            "Power Saving", 0},
+    {ACPI_DMT_UINT64,   ACPI_MPST2_OFFSET (ExitLatency),            "Exit Latency", 0},
+    {ACPI_DMT_UINT64,   ACPI_MPST2_OFFSET (Reserved2),              "Reserved", 0},
+    ACPI_DMT_TERMINATOR
+};
+
+
+/*******************************************************************************
+ *
  * MSCT - Maximum System Characteristics Table (ACPI 4.0)
  *
  ******************************************************************************/
@@ -1269,6 +1529,155 @@
 
 /*******************************************************************************
  *
+ * PCCT - Platform Communications Channel Table (ACPI 5.0)
+ *
+ ******************************************************************************/
+
+ACPI_DMTABLE_INFO           AcpiDmTableInfoPcct[] =
+{
+    {ACPI_DMT_UINT32,   ACPI_PCCT_OFFSET (Flags),                   "Flags (decoded below)", DT_FLAG},
+    {ACPI_DMT_FLAG0,    ACPI_PCCT_FLAG_OFFSET (Flags,0),            "Doorbell", 0},
+    {ACPI_DMT_UINT32,   ACPI_PCCT_OFFSET (Latency),                 "Command Latency", 0},
+    {ACPI_DMT_UINT32,   ACPI_PCCT_OFFSET (Reserved),                "Reserved", 0},
+    ACPI_DMT_TERMINATOR
+};
+
+/* PCCT subtables */
+
+/* 0: Generic Communications Subspace */
+
+ACPI_DMTABLE_INFO           AcpiDmTableInfoPcct0[] =
+{
+    {ACPI_DMT_UINT8,    ACPI_PCCT0_OFFSET (Header.Type),            "Subtable Type", 0},
+    {ACPI_DMT_UINT8,    ACPI_PCCT0_OFFSET (Header.Length),          "Length", DT_LENGTH},
+    {ACPI_DMT_UINT48,   ACPI_PCCT0_OFFSET (Reserved[0]),            "Reserved", 0},
+    {ACPI_DMT_UINT64,   ACPI_PCCT0_OFFSET (BaseAddress),            "Base Address", 0},
+    {ACPI_DMT_UINT64,   ACPI_PCCT0_OFFSET (Length),                 "Address Length", 0},
+    {ACPI_DMT_GAS,      ACPI_PCCT0_OFFSET (DoorbellRegister),       "Doorbell Register", 0},
+    {ACPI_DMT_UINT64,   ACPI_PCCT0_OFFSET (PreserveMask),           "Preserve Mask", 0},
+    {ACPI_DMT_UINT64,   ACPI_PCCT0_OFFSET (WriteMask),              "Write Mask", 0},
+    ACPI_DMT_TERMINATOR
+};
+
+
+/*******************************************************************************
+ *
+ * PMTT - Platform Memory Topology Table
+ *
+ ******************************************************************************/
+
+ACPI_DMTABLE_INFO           AcpiDmTableInfoPmtt[] =
+{
+    {ACPI_DMT_UINT32,   ACPI_PMTT_OFFSET (Reserved),                "Reserved", 0},
+    ACPI_DMT_TERMINATOR
+};
+
+/* Common Subtable header (one per Subtable) */
+
+ACPI_DMTABLE_INFO           AcpiDmTableInfoPmttHdr[] =
+{
+    {ACPI_DMT_PMTT,     ACPI_PMTTH_OFFSET (Type),                   "Subtable Type", 0},
+    {ACPI_DMT_UINT8,    ACPI_PMTTH_OFFSET (Reserved1),              "Reserved", 0},
+    {ACPI_DMT_UINT16,   ACPI_PMTTH_OFFSET (Length),                 "Length", DT_LENGTH},
+    {ACPI_DMT_UINT16,   ACPI_PMTTH_OFFSET (Flags),                  "Flags (decoded below)", DT_FLAG},
+    {ACPI_DMT_FLAG0,    ACPI_PMTTH_FLAG_OFFSET (Flags,0),           "Top-level Device", 0},
+    {ACPI_DMT_FLAG1,    ACPI_PMTTH_FLAG_OFFSET (Flags,0),           "Physical Element", 0},
+    {ACPI_DMT_FLAGS2,   ACPI_PMTTH_FLAG_OFFSET (Flags,0),           "Memory Type", 0},
+    {ACPI_DMT_UINT16,   ACPI_PMTTH_OFFSET (Reserved2),              "Reserved", 0},
+    ACPI_DMT_TERMINATOR
+};
+
+/* PMTT Subtables */
+
+/* 0: Socket */
+
+ACPI_DMTABLE_INFO           AcpiDmTableInfoPmtt0[] =
+{
+    {ACPI_DMT_UINT16,   ACPI_PMTT0_OFFSET (SocketId),               "Socket ID", 0},
+    {ACPI_DMT_UINT16,   ACPI_PMTT0_OFFSET (Reserved),               "Reserved", 0},
+    ACPI_DMT_TERMINATOR
+};
+
+/* 1: Memory Controller */
+
+ACPI_DMTABLE_INFO           AcpiDmTableInfoPmtt1[] =
+{
+    {ACPI_DMT_UINT32,   ACPI_PMTT1_OFFSET (ReadLatency),            "Read Latency", 0},
+    {ACPI_DMT_UINT32,   ACPI_PMTT1_OFFSET (WriteLatency),           "Write Latency", 0},
+    {ACPI_DMT_UINT32,   ACPI_PMTT1_OFFSET (ReadBandwidth),          "Read Bandwidth", 0},
+    {ACPI_DMT_UINT32,   ACPI_PMTT1_OFFSET (WriteBandwidth),         "Write Bandwidth", 0},
+    {ACPI_DMT_UINT16,   ACPI_PMTT1_OFFSET (AccessWidth),            "Access Width", 0},
+    {ACPI_DMT_UINT16,   ACPI_PMTT1_OFFSET (Alignment),              "Alignment", 0},
+    {ACPI_DMT_UINT16,   ACPI_PMTT1_OFFSET (Reserved),               "Reserved", 0},
+    {ACPI_DMT_UINT16,   ACPI_PMTT1_OFFSET (DomainCount),            "Domain Count", 0},
+    ACPI_DMT_TERMINATOR
+};
+
+/* 1a: Proximity Domain */
+
+ACPI_DMTABLE_INFO           AcpiDmTableInfoPmtt1a[] =
+{
+    {ACPI_DMT_UINT32,   ACPI_PMTT1A_OFFSET (ProximityDomain),       "Proximity Domain", 0},
+    ACPI_DMT_TERMINATOR
+};
+
+/* 2: Physical Component */
+
+ACPI_DMTABLE_INFO           AcpiDmTableInfoPmtt2[] =
+{
+    {ACPI_DMT_UINT16,   ACPI_PMTT2_OFFSET (ComponentId),            "Component ID", 0},
+    {ACPI_DMT_UINT16,   ACPI_PMTT2_OFFSET (Reserved),               "Reserved", 0},
+    {ACPI_DMT_UINT32,   ACPI_PMTT2_OFFSET (MemorySize),             "Memory Size", 0},
+    {ACPI_DMT_UINT32,   ACPI_PMTT2_OFFSET (BiosHandle),             "Bios Handle", 0},
+    ACPI_DMT_TERMINATOR
+};
+
+
+/*******************************************************************************
+ *
+ * S3PT - S3 Performance Table
+ *
+ ******************************************************************************/
+
+ACPI_DMTABLE_INFO           AcpiDmTableInfoS3pt[] =
+{
+    {ACPI_DMT_SIG,     ACPI_S3PT_OFFSET (Signature[0]),             "Signature", 0},
+    {ACPI_DMT_UINT32,  ACPI_S3PT_OFFSET (Length),                   "Length", DT_LENGTH},
+    ACPI_DMT_TERMINATOR
+};
+
+/* S3PT subtable header */
+
+ACPI_DMTABLE_INFO           AcpiDmTableInfoS3ptHdr[] =
+{
+    {ACPI_DMT_UINT16,  ACPI_S3PTH_OFFSET (Type),                    "Type", 0},
+    {ACPI_DMT_UINT8,   ACPI_S3PTH_OFFSET (Length),                  "Length", DT_LENGTH},
+    {ACPI_DMT_UINT8,   ACPI_S3PTH_OFFSET (Revision),                "Revision", 0},
+    ACPI_DMT_TERMINATOR
+};
+
+/* 0: Basic S3 Resume Performance Record */
+
+ACPI_DMTABLE_INFO           AcpiDmTableInfoS3pt0[] =
+{
+    {ACPI_DMT_UINT32,  ACPI_S3PT0_OFFSET (ResumeCount),             "Resume Count", 0},
+    {ACPI_DMT_UINT64,  ACPI_S3PT0_OFFSET (FullResume),              "Full Resume", 0},
+    {ACPI_DMT_UINT64,  ACPI_S3PT0_OFFSET (AverageResume),           "Average Resume", 0},
+    ACPI_DMT_TERMINATOR
+};
+
+/* 1: Basic S3 Suspend Performance Record */
+
+ACPI_DMTABLE_INFO           AcpiDmTableInfoS3pt1[] =
+{
+    {ACPI_DMT_UINT64,  ACPI_S3PT1_OFFSET (SuspendStart),            "Suspend Start", 0},
+    {ACPI_DMT_UINT64,  ACPI_S3PT1_OFFSET (SuspendEnd),              "Suspend End", 0},
+    ACPI_DMT_TERMINATOR
+};
+
+
+/*******************************************************************************
+ *
  * SBST - Smart Battery Specification Table
  *
  ******************************************************************************/
@@ -1609,8 +2018,10 @@
     ACPI_DMT_TERMINATOR
 };
 
+/*! [Begin] no source code translation */
+
 /*
- * Generic types (used in UEFI)
+ * Generic types (used in UEFI and custom tables)
  *
  * Examples:
  *
@@ -1629,7 +2040,7 @@
  * DevicePath : "\PciRoot(0)\Pci(0x1f,1)\Usb(0,0)"
  */
 
-#define ACPI_DM_GENERIC_ENTRY(FieldType, FieldName)\
+#define ACPI_DM_GENERIC_ENTRY(FieldType, FieldName) \
     {{FieldType, 0, FieldName, 0}, ACPI_DMT_TERMINATOR}
 
 ACPI_DMTABLE_INFO           AcpiDmTableInfoGeneric[][2] =
@@ -1638,6 +2049,8 @@
     ACPI_DM_GENERIC_ENTRY (ACPI_DMT_UINT16,     "UINT16"),
     ACPI_DM_GENERIC_ENTRY (ACPI_DMT_UINT24,     "UINT24"),
     ACPI_DM_GENERIC_ENTRY (ACPI_DMT_UINT32,     "UINT32"),
+    ACPI_DM_GENERIC_ENTRY (ACPI_DMT_UINT40,     "UINT40"),
+    ACPI_DM_GENERIC_ENTRY (ACPI_DMT_UINT48,     "UINT48"),
     ACPI_DM_GENERIC_ENTRY (ACPI_DMT_UINT56,     "UINT56"),
     ACPI_DM_GENERIC_ENTRY (ACPI_DMT_UINT64,     "UINT64"),
     ACPI_DM_GENERIC_ENTRY (ACPI_DMT_STRING,     "String"),
@@ -1648,3 +2061,4 @@
     ACPI_DM_GENERIC_ENTRY (ACPI_DMT_LABEL,      "Label"),
     {ACPI_DMT_TERMINATOR}
 };
+/*! [End] no source code translation !*/
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/compiler/aslanalyze.c
--- a/head/sys/contrib/dev/acpica/compiler/aslanalyze.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/compiler/aslanalyze.c	Tue Dec 06 20:26:16 2011 +0200
@@ -126,7 +126,6 @@
 {
     UINT32                  i;
     ACPI_SIZE               Length;
-    UINT32                  AlphaPrefixLength;
 
 
     /* Only care about string versions of _HID/_CID (integers are legal) */
@@ -174,12 +173,18 @@
         {
             AslError (ASL_ERROR, ASL_MSG_ALPHANUMERIC_STRING,
                 Op, Op->Asl.Value.String);
-            break;
+            return;
         }
     }
 
-    /* _HID String must be of the form "XXX####" or "ACPI####" */
-
+    /*
+     * _HID String must be one of these forms:
+     *
+     * "AAA####"    A is an uppercase letter and # is a hex digit
+     * "ACPI####"   # is a hex digit
+     * "NNNN####"   N is an uppercase letter or decimal digit (0-9)
+     *              # is a hex digit (ACPI 5.0)
+     */
     if ((Length < 7) || (Length > 8))
     {
         AslError (ASL_ERROR, ASL_MSG_HID_LENGTH,
@@ -187,22 +192,48 @@
         return;
     }
 
-    /* _HID Length is valid, now check for uppercase (first 3 or 4 chars) */
+    /* _HID Length is valid (7 or 8), now check the prefix (first 3 or 4 chars) */
 
-    AlphaPrefixLength = 3;
-    if (Length >= 8)
+    if (Length == 7)
     {
-        AlphaPrefixLength = 4;
+        /* AAA####: Ensure the alphabetic prefix is all uppercase */
+
+        for (i = 0; i < 3; i++)
+        {
+            if (!isupper ((int) Op->Asl.Value.String[i]))
+            {
+                AslError (ASL_ERROR, ASL_MSG_UPPER_CASE,
+                    Op, &Op->Asl.Value.String[i]);
+                return;
+            }
+        }
+    }
+    else /* Length == 8 */
+    {
+        /*
+         * ACPI#### or NNNN####:
+         * Ensure the prefix contains only uppercase alpha or decimal digits
+         */
+        for (i = 0; i < 4; i++)
+        {
+            if (!isupper ((int) Op->Asl.Value.String[i]) &&
+                !isdigit ((int) Op->Asl.Value.String[i]))
+            {
+                AslError (ASL_ERROR, ASL_MSG_HID_PREFIX,
+                    Op, &Op->Asl.Value.String[i]);
+                return;
+            }
+        }
     }
 
-    /* Ensure the alphabetic prefix is all uppercase */
+    /* Remaining characters (suffix) must be hex digits */
 
-    for (i = 0; (i < AlphaPrefixLength) && Op->Asl.Value.String[i]; i++)
+    for (; i < Length; i++)
     {
-        if (!isupper ((int) Op->Asl.Value.String[i]))
+        if (!isxdigit ((int) Op->Asl.Value.String[i]))
         {
-            AslError (ASL_ERROR, ASL_MSG_UPPER_CASE,
-                Op, &Op->Asl.Value.String[i]);
+         AslError (ASL_ERROR, ASL_MSG_HID_SUFFIX,
+            Op, &Op->Asl.Value.String[i]);
             break;
         }
     }
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/compiler/aslcodegen.c
--- a/head/sys/contrib/dev/acpica/compiler/aslcodegen.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/compiler/aslcodegen.c	Tue Dec 06 20:26:16 2011 +0200
@@ -271,12 +271,17 @@
 
         /* Special opcodes for within a field definition */
 
-        Aml.Opcode = 0x00;
+        Aml.Opcode = AML_FIELD_OFFSET_OP;
         break;
 
     case AML_INT_ACCESSFIELD_OP:
 
-        Aml.Opcode = 0x01;
+        Aml.Opcode = AML_FIELD_ACCESS_OP;
+        break;
+
+    case AML_INT_CONNECTION_OP:
+
+        Aml.Opcode = AML_FIELD_CONNECTION_OP;
         break;
 
     default:
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/compiler/aslcompile.c
--- a/head/sys/contrib/dev/acpica/compiler/aslcompile.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/compiler/aslcompile.c	Tue Dec 06 20:26:16 2011 +0200
@@ -472,6 +472,8 @@
 
     if (!RootNode)
     {
+        AslError (ASL_ERROR, ASL_MSG_COMPILER_INTERNAL,
+            NULL, "- Could not resolve parse tree root node");
         CmCleanupAndExit ();
         return -1;
     }
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/compiler/aslcompiler.h
--- a/head/sys/contrib/dev/acpica/compiler/aslcompiler.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/compiler/aslcompiler.h	Tue Dec 06 20:26:16 2011 +0200
@@ -289,7 +289,7 @@
 
 int
 AslCompilererror(
-    char                    *s);
+    const char              *s);
 
 void
 AslCommonError (
@@ -829,17 +829,12 @@
     UINT32                  Size);
 
 void
-RsCreateBitField (
+RsCreateResourceField (
     ACPI_PARSE_OBJECT       *Op,
     char                    *Name,
     UINT32                  ByteOffset,
-    UINT32                  BitOffset);
-
-void
-RsCreateByteField (
-    ACPI_PARSE_OBJECT       *Op,
-    char                    *Name,
-    UINT32                  ByteOffset);
+    UINT32                  BitOffset,
+    UINT32                  BitLength);
 
 void
 RsSetFlagBits (
@@ -848,6 +843,13 @@
     UINT8                   Position,
     UINT8                   DefaultBit);
 
+void
+RsSetFlagBits16 (
+    UINT16                  *Flags,
+    ACPI_PARSE_OBJECT       *Op,
+    UINT8                   Position,
+    UINT8                   DefaultBit);
+
 ACPI_PARSE_OBJECT *
 RsCompleteNodeAndGetNext (
     ACPI_PARSE_OBJECT       *Op);
@@ -931,6 +933,11 @@
     UINT32                  CurrentByteOffset);
 
 ASL_RESOURCE_NODE *
+RsDoFixedDmaDescriptor (
+    ACPI_PARSE_OBJECT       *Op,
+    UINT32                  CurrentByteOffset);
+
+ASL_RESOURCE_NODE *
 RsDoFixedIoDescriptor (
     ACPI_PARSE_OBJECT       *Op,
     UINT32                  CurrentByteOffset);
@@ -969,6 +976,30 @@
     ACPI_PARSE_OBJECT       *Op,
     UINT32                  CurrentByteOffset);
 
+ASL_RESOURCE_NODE *
+RsDoGpioIntDescriptor (
+    ACPI_PARSE_OBJECT       *Op,
+    UINT32                  CurrentByteOffset);
+
+ASL_RESOURCE_NODE *
+RsDoGpioIoDescriptor (
+    ACPI_PARSE_OBJECT       *Op,
+    UINT32                  CurrentByteOffset);
+
+ASL_RESOURCE_NODE *
+RsDoI2cSerialBusDescriptor (
+    ACPI_PARSE_OBJECT       *Op,
+    UINT32                  CurrentByteOffset);
+
+ASL_RESOURCE_NODE *
+RsDoSpiSerialBusDescriptor (
+    ACPI_PARSE_OBJECT       *Op,
+    UINT32                  CurrentByteOffset);
+
+ASL_RESOURCE_NODE *
+RsDoUartSerialBusDescriptor (
+    ACPI_PARSE_OBJECT       *Op,
+    UINT32                  CurrentByteOffset);
 
 /*
  * aslrestype2d - DWord address descriptors
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/compiler/aslcompiler.l
--- a/head/sys/contrib/dev/acpica/compiler/aslcompiler.l	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/compiler/aslcompiler.l	Tue Dec 06 20:26:16 2011 +0200
@@ -1,8 +1,7 @@
-
 %{
 /******************************************************************************
  *
- * Module Name: aslcompiler.l - Flex input file
+ * Module Name: aslcompiler.l - Flex/lex input file
  *
  *****************************************************************************/
 
@@ -60,6 +59,9 @@
 
 #define _COMPONENT          ACPI_COMPILER
         ACPI_MODULE_NAME    ("aslscan")
+
+/* Local prototypes */
+
 char
 comment (void);
 char
@@ -74,7 +76,7 @@
 /*! [Begin] no source code translation */
 
 %}
-
+    /* Definitions */
 
 LeadNameChar                [A-Za-z_]
 DigitChar                   [0-9]
@@ -94,6 +96,7 @@
 NamePathTail                [.]{NameSeg}
 
 %%
+    /* Rules */
 
 [ ]                         { count (0); }
 [\n]                        { count (0); } /* Handle files with both LF and CR/LF */
@@ -105,6 +108,7 @@
 "//"                        { if (!comment2 ()) yyterminate (); }
 
 "\""                        { if (literal ()) return (PARSEOP_STRING_LITERAL); else yyterminate (); }
+";"                         { count (0); return(';'); }
 
 
 0[xX]{HexDigitChar}+ |
@@ -116,15 +120,28 @@
 "#line"						{ count (1); return (PARSEOP_LINE_CSTYLE); }
 "External"                  { count (1); return (PARSEOP_EXTERNAL); }
 
+ /****************************************************************************
+  *
+  * Main ASL operators
+  *
+  ****************************************************************************/
 
-"Ones"                      { count (1); return (PARSEOP_ONES); }
-"One"                       { count (1); return (PARSEOP_ONE); }
-"Zero"                      { count (1); return (PARSEOP_ZERO); }
-"Revision"                  { count (1); return (PARSEOP_REVISION); }
-
-"Offset"                    { count (1); return (PARSEOP_OFFSET); }
 "AccessAs"                  { count (1); return (PARSEOP_ACCESSAS); }
+"Acquire"                   { count (3); return (PARSEOP_ACQUIRE); }
+"Add"                       { count (3); return (PARSEOP_ADD); }
+"Alias"                     { count (2); return (PARSEOP_ALIAS); }
+"And"                       { count (3); return (PARSEOP_AND); }
 "BankField"                 { count (2); return (PARSEOP_BANKFIELD); }
+"Break"                     { count (3); return (PARSEOP_BREAK); }
+"BreakPoint"                { count (3); return (PARSEOP_BREAKPOINT); }
+"Buffer"                    { count (1); return (PARSEOP_BUFFER); }
+"Case"                      { count (3); return (PARSEOP_CASE); }
+"Concatenate"               { count (3); return (PARSEOP_CONCATENATE); }
+"ConcatenateResTemplate"    { count (3); return (PARSEOP_CONCATENATERESTEMPLATE); }
+"CondRefOf"                 { count (3); return (PARSEOP_CONDREFOF); }
+"Connection"                { count (2); return (PARSEOP_CONNECTION); }
+"Continue"                  { count (3); return (PARSEOP_CONTINUE); }
+"CopyObject"                { count (3); return (PARSEOP_COPYOBJECT); }
 "CreateBitField"            { count (2); return (PARSEOP_CREATEBITFIELD); }
 "CreateByteField"           { count (2); return (PARSEOP_CREATEBYTEFIELD); }
 "CreateDWordField"          { count (2); return (PARSEOP_CREATEDWORDFIELD); }
@@ -132,57 +149,27 @@
 "CreateQWordField"          { count (2); return (PARSEOP_CREATEQWORDFIELD); }
 "CreateWordField"           { count (2); return (PARSEOP_CREATEWORDFIELD); }
 "DataTableRegion"           { count (2); return (PARSEOP_DATATABLEREGION); }
+"Debug"                     { count (1); return (PARSEOP_DEBUG); }
+"Decrement"                 { count (3); return (PARSEOP_DECREMENT); }
+"Default"                   { count (3); return (PARSEOP_DEFAULT); }
+"DefinitionBlock"           { count (1); return (PARSEOP_DEFINITIONBLOCK); }
+"DeRefOf"                   { count (3); return (PARSEOP_DEREFOF); }
 "Device"                    { count (2); return (PARSEOP_DEVICE); }
-"Event"                     { count (2); return (PARSEOP_EVENT); }
-"Field"                     { count (2); return (PARSEOP_FIELD); }
-"Function"                  { count (2); return (PARSEOP_FUNCTION); }
-"IndexField"                { count (2); return (PARSEOP_INDEXFIELD); }
-"Method"                    { count (2); return (PARSEOP_METHOD); }
-"Mutex"                     { count (2); return (PARSEOP_MUTEX); }
-"OperationRegion"           { count (2); return (PARSEOP_OPERATIONREGION); }
-"PowerResource"             { count (2); return (PARSEOP_POWERRESOURCE); }
-"Processor"                 { count (2); return (PARSEOP_PROCESSOR); }
-"ThermalZone"               { count (2); return (PARSEOP_THERMALZONE); }
-"Alias"                     { count (2); return (PARSEOP_ALIAS); }
-"Name"                      { count (2); return (PARSEOP_NAME); }
-"Scope"                     { count (2); return (PARSEOP_SCOPE); }
-"Break"                     { count (3); return (PARSEOP_BREAK); }
-"BreakPoint"                { count (3); return (PARSEOP_BREAKPOINT); }
-"Continue"                  { count (3); return (PARSEOP_CONTINUE); }
-"Fatal"                     { count (3); return (PARSEOP_FATAL); }
-"If"                        { count (3); return (PARSEOP_IF); }
+"Divide"                    { count (3); return (PARSEOP_DIVIDE); }
+"Eisaid"                    { count (1); return (PARSEOP_EISAID); }
 "Else"                      { count (3); return (PARSEOP_ELSE); }
 "ElseIf"                    { count (3); return (PARSEOP_ELSEIF); }
-"Load"                      { count (3); return (PARSEOP_LOAD); }
-"Noop"                      { count (3); return (PARSEOP_NOOP); }
-"Notify"                    { count (3); return (PARSEOP_NOTIFY); }
-"Release"                   { count (3); return (PARSEOP_RELEASE); }
-"Reset"                     { count (3); return (PARSEOP_RESET); }
-"Return"                    { count (3); return (PARSEOP_RETURN); }
-"Signal"                    { count (3); return (PARSEOP_SIGNAL); }
-"Sleep"                     { count (3); return (PARSEOP_SLEEP); }
-"Stall"                     { count (3); return (PARSEOP_STALL); }
-"Switch"                    { count (3); return (PARSEOP_SWITCH); }
-"Case"                      { count (3); return (PARSEOP_CASE); }
-"Default"                   { count (3); return (PARSEOP_DEFAULT); }
-"Unload"                    { count (3); return (PARSEOP_UNLOAD); }
-"While"                     { count (3); return (PARSEOP_WHILE); }
-
-"Acquire"                   { count (3); return (PARSEOP_ACQUIRE); }
-"Add"                       { count (3); return (PARSEOP_ADD); }
-"And"                       { count (3); return (PARSEOP_AND); }
-"Concatenate"               { count (3); return (PARSEOP_CONCATENATE); }
-"ConcatenateResTemplate"    { count (3); return (PARSEOP_CONCATENATERESTEMPLATE); }
-"CondRefOf"                 { count (3); return (PARSEOP_CONDREFOF); }
-"CopyObject"                { count (3); return (PARSEOP_COPYOBJECT); }
-"Decrement"                 { count (3); return (PARSEOP_DECREMENT); }
-"DeRefOf"                   { count (3); return (PARSEOP_DEREFOF); }
-"Divide"                    { count (3); return (PARSEOP_DIVIDE); }
+"Event"                     { count (2); return (PARSEOP_EVENT); }
+"Fatal"                     { count (3); return (PARSEOP_FATAL); }
+"Field"                     { count (2); return (PARSEOP_FIELD); }
 "FindSetLeftBit"            { count (3); return (PARSEOP_FINDSETLEFTBIT); }
 "FindSetRightBit"           { count (3); return (PARSEOP_FINDSETRIGHTBIT); }
-"FromBCD"                   { count (3); return (PARSEOP_FROMBCD); }
+"FromBcd"                   { count (3); return (PARSEOP_FROMBCD); }
+"Function"                  { count (2); return (PARSEOP_FUNCTION); }
+"If"                        { count (3); return (PARSEOP_IF); }
 "Increment"                 { count (3); return (PARSEOP_INCREMENT); }
 "Index"                     { count (3); return (PARSEOP_INDEX); }
+"IndexField"                { count (2); return (PARSEOP_INDEXFIELD); }
 "LAnd"                      { count (3); return (PARSEOP_LAND); }
 "LEqual"                    { count (3); return (PARSEOP_LEQUAL); }
 "LGreater"                  { count (3); return (PARSEOP_LGREATER); }
@@ -191,32 +178,62 @@
 "LLessEqual"                { count (3); return (PARSEOP_LLESSEQUAL); }
 "LNot"                      { count (3); return (PARSEOP_LNOT); }
 "LNotEqual"                 { count (3); return (PARSEOP_LNOTEQUAL); }
+"Load"                      { count (3); return (PARSEOP_LOAD); }
 "LoadTable"                 { count (3); return (PARSEOP_LOADTABLE); }
 "LOr"                       { count (3); return (PARSEOP_LOR); }
 "Match"                     { count (3); return (PARSEOP_MATCH); }
+"Method"                    { count (2); return (PARSEOP_METHOD); }
 "Mid"                       { count (3); return (PARSEOP_MID); }
 "Mod"                       { count (3); return (PARSEOP_MOD); }
 "Multiply"                  { count (3); return (PARSEOP_MULTIPLY); }
+"Mutex"                     { count (2); return (PARSEOP_MUTEX); }
+"Name"                      { count (2); return (PARSEOP_NAME); }
 "NAnd"                      { count (3); return (PARSEOP_NAND); }
+"Noop"                      { count (3); return (PARSEOP_NOOP); }
 "NOr"                       { count (3); return (PARSEOP_NOR); }
 "Not"                       { count (3); return (PARSEOP_NOT); }
+"Notify"                    { count (3); return (PARSEOP_NOTIFY); }
 "ObjectType"                { count (3); return (PARSEOP_OBJECTTYPE); }
+"Offset"                    { count (1); return (PARSEOP_OFFSET); }
+"One"                       { count (1); return (PARSEOP_ONE); }
+"Ones"                      { count (1); return (PARSEOP_ONES); }
+"OperationRegion"           { count (2); return (PARSEOP_OPERATIONREGION); }
 "Or"                        { count (3); return (PARSEOP_OR); }
+"Package"                   { count (1); return (PARSEOP_PACKAGE); }
+"PowerResource"             { count (2); return (PARSEOP_POWERRESOURCE); }
+"Processor"                 { count (2); return (PARSEOP_PROCESSOR); }
 "RefOf"                     { count (3); return (PARSEOP_REFOF); }
+"Release"                   { count (3); return (PARSEOP_RELEASE); }
+"Reset"                     { count (3); return (PARSEOP_RESET); }
+"Return"                    { count (3); return (PARSEOP_RETURN); }
+"Revision"                  { count (1); return (PARSEOP_REVISION); }
+"Scope"                     { count (2); return (PARSEOP_SCOPE); }
 "ShiftLeft"                 { count (3); return (PARSEOP_SHIFTLEFT); }
 "ShiftRight"                { count (3); return (PARSEOP_SHIFTRIGHT); }
+"Signal"                    { count (3); return (PARSEOP_SIGNAL); }
 "SizeOf"                    { count (3); return (PARSEOP_SIZEOF); }
+"Sleep"                     { count (3); return (PARSEOP_SLEEP); }
+"Stall"                     { count (3); return (PARSEOP_STALL); }
 "Store"                     { count (3); return (PARSEOP_STORE); }
 "Subtract"                  { count (3); return (PARSEOP_SUBTRACT); }
+"Switch"                    { count (3); return (PARSEOP_SWITCH); }
+"ThermalZone"               { count (2); return (PARSEOP_THERMALZONE); }
 "Timer"                     { count (3); return (PARSEOP_TIMER); }
-"ToBCD"                     { count (3); return (PARSEOP_TOBCD); }
+"ToBcd"                     { count (3); return (PARSEOP_TOBCD); }
 "ToBuffer"                  { count (3); return (PARSEOP_TOBUFFER); }
 "ToDecimalString"           { count (3); return (PARSEOP_TODECIMALSTRING); }
 "ToHexString"               { count (3); return (PARSEOP_TOHEXSTRING); }
 "ToInteger"                 { count (3); return (PARSEOP_TOINTEGER); }
 "ToString"                  { count (3); return (PARSEOP_TOSTRING); }
+"ToUuid"                    { count (1); return (PARSEOP_TOUUID); }
+"Unicode"                   { count (1); return (PARSEOP_UNICODE); }
+"Unload"                    { count (3); return (PARSEOP_UNLOAD); }
 "Wait"                      { count (3); return (PARSEOP_WAIT); }
+"While"                     { count (3); return (PARSEOP_WHILE); }
 "XOr"                       { count (3); return (PARSEOP_XOR); }
+"Zero"                      { count (1); return (PARSEOP_ZERO); }
+
+    /* Control method arguments and locals */
 
 "Arg0"                      { count (1); return (PARSEOP_ARG0); }
 "Arg1"                      { count (1); return (PARSEOP_ARG1); }
@@ -225,7 +242,6 @@
 "Arg4"                      { count (1); return (PARSEOP_ARG4); }
 "Arg5"                      { count (1); return (PARSEOP_ARG5); }
 "Arg6"                      { count (1); return (PARSEOP_ARG6); }
-
 "Local0"                    { count (1); return (PARSEOP_LOCAL0); }
 "Local1"                    { count (1); return (PARSEOP_LOCAL1); }
 "Local2"                    { count (1); return (PARSEOP_LOCAL2); }
@@ -235,16 +251,16 @@
 "Local6"                    { count (1); return (PARSEOP_LOCAL6); }
 "Local7"                    { count (1); return (PARSEOP_LOCAL7); }
 
-"Debug"                     { count (1); return (PARSEOP_DEBUG); }
 
-"DefinitionBlock"           { count (1); return (PARSEOP_DEFINITIONBLOCK); }
-"Buffer"                    { count (1); return (PARSEOP_BUFFER); }
-"Package"                   { count (1); return (PARSEOP_PACKAGE); }
+ /****************************************************************************
+  *
+  * Resource Descriptor macros
+  *
+  ****************************************************************************/
 
-"EISAID"                    { count (1); return (PARSEOP_EISAID); }
 "ResourceTemplate"          { count (1); return (PARSEOP_RESOURCETEMPLATE); }
-"ToUUID"                    { count (1); return (PARSEOP_TOUUID); }
-"Unicode"                   { count (1); return (PARSEOP_UNICODE); }
+"RawDataBuffer"             { count (1); return (PARSEOP_DATABUFFER); }
+
 "DMA"                       { count (1); return (PARSEOP_DMA); }
 "DWordIO"                   { count (1); return (PARSEOP_DWORDIO); }
 "DWordMemory"               { count (1); return (PARSEOP_DWORDMEMORY); }
@@ -253,26 +269,188 @@
 "ExtendedIO"                { count (1); return (PARSEOP_EXTENDEDIO); }
 "ExtendedMemory"            { count (1); return (PARSEOP_EXTENDEDMEMORY); }
 "ExtendedSpace"             { count (1); return (PARSEOP_EXTENDEDSPACE); }
+"FixedDma"                  { count (1); return (PARSEOP_FIXEDDMA); }
 "FixedIO"                   { count (1); return (PARSEOP_FIXEDIO); }
+"GpioInt"                   { count (1); return (PARSEOP_GPIO_INT); }
+"GpioIo"                    { count (1); return (PARSEOP_GPIO_IO); }
+"I2cSerialBus"              { count (1); return (PARSEOP_I2C_SERIALBUS); }
 "Interrupt"                 { count (1); return (PARSEOP_INTERRUPT); }
 "IO"                        { count (1); return (PARSEOP_IO); }
+"IRQ"                       { count (1); return (PARSEOP_IRQ); }
 "IRQNoFlags"                { count (1); return (PARSEOP_IRQNOFLAGS); }
-"IRQ"                       { count (1); return (PARSEOP_IRQ); }
 "Memory24"                  { count (1); return (PARSEOP_MEMORY24); }
+"Memory32"                  { count (1); return (PARSEOP_MEMORY32); }
 "Memory32Fixed"             { count (1); return (PARSEOP_MEMORY32FIXED); }
-"Memory32"                  { count (1); return (PARSEOP_MEMORY32); }
 "QWordIO"                   { count (1); return (PARSEOP_QWORDIO); }
 "QWordMemory"               { count (1); return (PARSEOP_QWORDMEMORY); }
 "QWordSpace"                { count (1); return (PARSEOP_QWORDSPACE); }
 "Register"                  { count (1); return (PARSEOP_REGISTER); }
+"SpiSerialBus"              { count (1); return (PARSEOP_SPI_SERIALBUS); }
 "StartDependentFn"          { count (1); return (PARSEOP_STARTDEPENDENTFN); }
 "StartDependentFnNoPri"     { count (1); return (PARSEOP_STARTDEPENDENTFN_NOPRI); }
+"UartSerialBus"             { count (1); return (PARSEOP_UART_SERIALBUS); }
 "VendorLong"                { count (1); return (PARSEOP_VENDORLONG); }
 "VendorShort"               { count (1); return (PARSEOP_VENDORSHORT); }
 "WordBusNumber"             { count (1); return (PARSEOP_WORDBUSNUMBER); }
 "WordIO"                    { count (1); return (PARSEOP_WORDIO); }
 "WordSpace"                 { count (1); return (PARSEOP_WORDSPACE); }
 
+
+ /****************************************************************************
+  *
+  * Keywords used as arguments to ASL operators and macros
+  *
+  ****************************************************************************/
+
+    /*  AccessAttribKeyword: Serial Bus Attributes (ACPI 5.0) */
+
+"AttribQuick"               { count (0); return (PARSEOP_ACCESSATTRIB_QUICK); }
+"AttribSendReceive"         { count (0); return (PARSEOP_ACCESSATTRIB_SND_RCV); }
+"AttribByte"                { count (0); return (PARSEOP_ACCESSATTRIB_BYTE); }
+"AttribWord"                { count (0); return (PARSEOP_ACCESSATTRIB_WORD); }
+"AttribBlock"               { count (0); return (PARSEOP_ACCESSATTRIB_BLOCK); }
+"AttribProcessCall"         { count (0); return (PARSEOP_ACCESSATTRIB_WORD_CALL); }
+"AttribBlockProcessCall"    { count (0); return (PARSEOP_ACCESSATTRIB_BLOCK_CALL); }
+
+    /* AccessAttribKeyword: Legacy synonyms for above (pre-ACPI 5.0) */
+
+"SMBQuick"                  { count (0); return (PARSEOP_ACCESSATTRIB_QUICK); }
+"SMBSendReceive"            { count (0); return (PARSEOP_ACCESSATTRIB_SND_RCV); }
+"SMBByte"                   { count (0); return (PARSEOP_ACCESSATTRIB_BYTE); }
+"SMBWord"                   { count (0); return (PARSEOP_ACCESSATTRIB_WORD); }
+"SMBBlock"                  { count (0); return (PARSEOP_ACCESSATTRIB_BLOCK); }
+"SMBProcessCall"            { count (0); return (PARSEOP_ACCESSATTRIB_WORD_CALL); }
+"SMBBlockProcessCall"       { count (0); return (PARSEOP_ACCESSATTRIB_BLOCK_CALL); }
+
+    /* AccessTypeKeyword: Field Access Types */
+
+"AnyAcc"                    { count (0); return (PARSEOP_ACCESSTYPE_ANY); }
+"ByteAcc"                   { count (0); return (PARSEOP_ACCESSTYPE_BYTE); }
+"WordAcc"                   { count (0); return (PARSEOP_ACCESSTYPE_WORD); }
+"DWordAcc"                  { count (0); return (PARSEOP_ACCESSTYPE_DWORD); }
+"QWordAcc"                  { count (0); return (PARSEOP_ACCESSTYPE_QWORD); }
+"BufferAcc"                 { count (0); return (PARSEOP_ACCESSTYPE_BUF); }
+
+    /* AddressingModeKeyword: Mode - Resource Descriptors (ACPI 5.0) */
+
+"AddressingMode7Bit"        { count (0); return (PARSEOP_ADDRESSINGMODE_7BIT); }
+"AddressingMode10Bit"       { count (0); return (PARSEOP_ADDRESSINGMODE_10BIT); }
+
+    /* AddressKeyword: ACPI memory range types */
+
+"AddressRangeMemory"        { count (0); return (PARSEOP_ADDRESSTYPE_MEMORY); }
+"AddressRangeReserved"      { count (0); return (PARSEOP_ADDRESSTYPE_RESERVED); }
+"AddressRangeNVS"           { count (0); return (PARSEOP_ADDRESSTYPE_NVS); }
+"AddressRangeACPI"          { count (0); return (PARSEOP_ADDRESSTYPE_ACPI); }
+
+    /* BusMasterKeyword: DMA Bus Mastering */
+
+"BusMaster"                 { count (0); return (PARSEOP_BUSMASTERTYPE_MASTER); }
+"NotBusMaster"              { count (0); return (PARSEOP_BUSMASTERTYPE_NOTMASTER); }
+
+    /* ByteLengthKeyword: Bits per Byte - Resource Descriptors (ACPI 5.0) */
+
+"DataBitsFive"              { count (0); return (PARSEOP_BITSPERBYTE_FIVE); }
+"DataBitsSix"               { count (0); return (PARSEOP_BITSPERBYTE_SIX); }
+"DataBitsSeven"             { count (0); return (PARSEOP_BITSPERBYTE_SEVEN); }
+"DataBitsEight"             { count (0); return (PARSEOP_BITSPERBYTE_EIGHT); }
+"DataBitsNine"              { count (0); return (PARSEOP_BITSPERBYTE_NINE); }
+
+    /* ClockPhaseKeyword: Resource Descriptors (ACPI 5.0) */
+
+"ClockPhaseFirst"           { count (0); return (PARSEOP_CLOCKPHASE_FIRST); }
+"ClockPhaseSecond"          { count (0); return (PARSEOP_CLOCKPHASE_SECOND); }
+
+    /* ClockPolarityKeyword: Resource Descriptors (ACPI 5.0) */
+
+"ClockPolarityLow"          { count (0); return (PARSEOP_CLOCKPOLARITY_LOW); }
+"ClockPolarityHigh"         { count (0); return (PARSEOP_CLOCKPOLARITY_HIGH); }
+
+    /* DecodeKeyword: Type of Memory Decoding - Resource Descriptors */
+
+"PosDecode"                 { count (0); return (PARSEOP_DECODETYPE_POS); }
+"SubDecode"                 { count (0); return (PARSEOP_DECODETYPE_SUB); }
+
+    /* DmaTypeKeyword: DMA Types - DMA Resource Descriptor */
+
+"Compatibility"             { count (0); return (PARSEOP_DMATYPE_COMPATIBILITY); }
+"TypeA"                     { count (0); return (PARSEOP_DMATYPE_A); }
+"TypeB"                     { count (0); return (PARSEOP_DMATYPE_B); }
+"TypeF"                     { count (0); return (PARSEOP_DMATYPE_F); }
+
+    /* EndianKeyword: Endian type - Resource Descriptor (ACPI 5.0) */
+
+"LittleEndian"              { count (0); return (PARSEOP_ENDIAN_LITTLE); }
+"BigEndian"                 { count (0); return (PARSEOP_ENDIAN_BIG); }
+
+    /* ExtendedAttribKeyword: Bus attributes, AccessAs operator (ACPI 5.0) */
+
+"AttribBytes"               { count (0); return (PARSEOP_ACCESSATTRIB_MULTIBYTE); }
+"AttribRawBytes"            { count (0); return (PARSEOP_ACCESSATTRIB_RAW_BYTES); }
+"AttribRawProcessBytes"     { count (0); return (PARSEOP_ACCESSATTRIB_RAW_PROCESS); }
+
+    /* FlowControlKeyword: Resource Descriptors (ACPI 5.0) */
+
+"FlowControlHardware"       { count (0); return (PARSEOP_FLOWCONTROL_HW); }
+"FlowControlNone"           { count (0); return (PARSEOP_FLOWCONTROL_NONE); }
+"FlowControlXon"            { count (0); return (PARSEOP_FLOWCONTROL_SW); }
+
+    /* InterruptLevelKeyword: Interrupt Active Types */
+
+"ActiveBoth"                { count (0); return (PARSEOP_INTLEVEL_ACTIVEBOTH); }
+"ActiveHigh"                { count (0); return (PARSEOP_INTLEVEL_ACTIVEHIGH); }
+"ActiveLow"                 { count (0); return (PARSEOP_INTLEVEL_ACTIVELOW); }
+
+    /* InterruptTypeKeyword: Interrupt Types */
+
+"Edge"                      { count (0); return (PARSEOP_INTTYPE_EDGE); }
+"Level"                     { count (0); return (PARSEOP_INTTYPE_LEVEL); }
+
+    /* IoDecodeKeyword: Type of Memory Decoding - Resource Descriptors */
+
+"Decode10"                  { count (0); return (PARSEOP_IODECODETYPE_10); }
+"Decode16"                  { count (0); return (PARSEOP_IODECODETYPE_16); }
+
+    /* IoRestrictionKeyword: I/O Restriction - GPIO Resource Descriptors (ACPI 5.0) */
+
+"IoRestrictionNone"         { count (0); return (PARSEOP_IORESTRICT_NONE); }
+"IoRestrictionInputOnly"    { count (0); return (PARSEOP_IORESTRICT_IN); }
+"IoRestrictionOutputOnly"   { count (0); return (PARSEOP_IORESTRICT_OUT); }
+"IoRestrictionNoneAndPreserve"   { count (0); return (PARSEOP_IORESTRICT_PRESERVE); }
+
+    /* LockRuleKeyword: Global Lock use for Field Operator */
+
+"Lock"                      { count (0); return (PARSEOP_LOCKRULE_LOCK); }
+"NoLock"                    { count (0); return (PARSEOP_LOCKRULE_NOLOCK); }
+
+    /* MatchOpKeyword: Types for Match Operator */
+
+"MTR"                       { count (0); return (PARSEOP_MATCHTYPE_MTR); }
+"MEQ"                       { count (0); return (PARSEOP_MATCHTYPE_MEQ); }
+"MLE"                       { count (0); return (PARSEOP_MATCHTYPE_MLE); }
+"MLT"                       { count (0); return (PARSEOP_MATCHTYPE_MLT); }
+"MGE"                       { count (0); return (PARSEOP_MATCHTYPE_MGE); }
+"MGT"                       { count (0); return (PARSEOP_MATCHTYPE_MGT); }
+
+    /* MaxKeyword: Max Range Type - Resource Descriptors */
+
+"MaxFixed"                  { count (0); return (PARSEOP_MAXTYPE_FIXED); }
+"MaxNotFixed"               { count (0); return (PARSEOP_MAXTYPE_NOTFIXED); }
+
+    /* MemTypeKeyword: Memory Types - Resource Descriptors */
+
+"Cacheable"                 { count (0); return (PARSEOP_MEMTYPE_CACHEABLE); }
+"WriteCombining"            { count (0); return (PARSEOP_MEMTYPE_WRITECOMBINING); }
+"Prefetchable"              { count (0); return (PARSEOP_MEMTYPE_PREFETCHABLE); }
+"NonCacheable"              { count (0); return (PARSEOP_MEMTYPE_NONCACHEABLE); }
+
+    /* MinKeyword: Min Range Type - Resource Descriptors */
+
+"MinFixed"                  { count (0); return (PARSEOP_MINTYPE_FIXED); }
+"MinNotFixed"               { count (0); return (PARSEOP_MINTYPE_NOTFIXED); }
+
+    /* ObjectTypeKeyword: ACPI Object Types */
+
 "UnknownObj"                { count (0); return (PARSEOP_OBJECTTYPE_UNK); }
 "IntObj"                    { count (0); return (PARSEOP_OBJECTTYPE_INT); }
 "StrObj"                    { count (0); return (PARSEOP_OBJECTTYPE_STR); }
@@ -290,22 +468,38 @@
 "BuffFieldObj"              { count (0); return (PARSEOP_OBJECTTYPE_BFF); }
 "DDBHandleObj"              { count (0); return (PARSEOP_OBJECTTYPE_DDB); }
 
-"AnyAcc"                    { count (0); return (PARSEOP_ACCESSTYPE_ANY); }
-"ByteAcc"                   { count (0); return (PARSEOP_ACCESSTYPE_BYTE); }
-"WordAcc"                   { count (0); return (PARSEOP_ACCESSTYPE_WORD); }
-"DWordAcc"                  { count (0); return (PARSEOP_ACCESSTYPE_DWORD); }
-"QWordAcc"                  { count (0); return (PARSEOP_ACCESSTYPE_QWORD); }
-"BufferAcc"                 { count (0); return (PARSEOP_ACCESSTYPE_BUF); }
+    /* ParityKeyword: Resource Descriptors (ACPI 5.0) */
 
-"Lock"                      { count (0); return (PARSEOP_LOCKRULE_LOCK); }
-"NoLock"                    { count (0); return (PARSEOP_LOCKRULE_NOLOCK); }
+"ParityTypeSpace"           { count (0); return (PARSEOP_PARITYTYPE_SPACE); }
+"ParityTypeMark"            { count (0); return (PARSEOP_PARITYTYPE_MARK); }
+"ParityTypeOdd"             { count (0); return (PARSEOP_PARITYTYPE_ODD); }
+"ParityTypeEven"            { count (0); return (PARSEOP_PARITYTYPE_EVEN); }
+"ParityTypeNone"            { count (0); return (PARSEOP_PARITYTYPE_NONE); }
 
-"Preserve"                  { count (0); return (PARSEOP_UPDATERULE_PRESERVE); }
-"WriteAsOnes"               { count (0); return (PARSEOP_UPDATERULE_ONES); }
-"WriteAsZeros"              { count (0); return (PARSEOP_UPDATERULE_ZEROS); }
+    /* PinConfigKeyword: Pin Configuration - GPIO Resource Descriptors (ACPI 5.0) */
 
-"Serialized"                { count (0); return (PARSEOP_SERIALIZERULE_SERIAL); }
-"NotSerialized"             { count (0); return (PARSEOP_SERIALIZERULE_NOTSERIAL); }
+"PullDefault"               { count (0); return (PARSEOP_PIN_PULLDEFAULT); }
+"PullUp"                    { count (0); return (PARSEOP_PIN_PULLUP); }
+"PullDown"                  { count (0); return (PARSEOP_PIN_PULLDOWN); }
+"PullNone"                  { count (0); return (PARSEOP_PIN_NOPULL); }
+
+    /* PolarityKeyword: Resource Descriptors (ACPI 5.0) */
+
+"PolarityLow"               { count (0); return (PARSEOP_DEVICEPOLARITY_LOW); }
+"PolarityHigh"              { count (0); return (PARSEOP_DEVICEPOLARITY_HIGH); }
+
+    /* RangeTypeKeyword: I/O Range Types - Resource Descriptors */
+
+"ISAOnlyRanges"             { count (0); return (PARSEOP_RANGETYPE_ISAONLY); }
+"NonISAOnlyRanges"          { count (0); return (PARSEOP_RANGETYPE_NONISAONLY); }
+"EntireRange"               { count (0); return (PARSEOP_RANGETYPE_ENTIRE); }
+
+    /* ReadWriteKeyword: Memory Access Types - Resource Descriptors */
+
+"ReadWrite"                 { count (0); return (PARSEOP_READWRITETYPE_BOTH); }
+"ReadOnly"                  { count (0); return (PARSEOP_READWRITETYPE_READONLY); }
+
+    /* RegionSpaceKeyword: Operation Region Address Space Types */
 
 "SystemIO"                  { count (0); return (PARSEOP_REGIONSPACE_IO); }
 "SystemMemory"              { count (0); return (PARSEOP_REGIONSPACE_MEM); }
@@ -315,86 +509,82 @@
 "SystemCMOS"                { count (0); return (PARSEOP_REGIONSPACE_CMOS); }
 "PciBarTarget"              { count (0); return (PARSEOP_REGIONSPACE_PCIBAR); }
 "IPMI"                      { count (0); return (PARSEOP_REGIONSPACE_IPMI); }
+"GeneralPurposeIo"          { count (0); return (PARSEOP_REGIONSPACE_GPIO); }       /* ACPI 5.0 */
+"GenericSerialBus"          { count (0); return (PARSEOP_REGIONSPACE_GSBUS); }      /* ACPI 5.0 */
+"FFixedHW"                  { count (0); return (PARSEOP_REGIONSPACE_FFIXEDHW); }
 
-"FFixedHW"                  { count (0); return (PARSEOP_ADDRESSSPACE_FFIXEDHW); }
+    /* ResourceTypeKeyword: Resource Usage - Resource Descriptors */
 
-"SMBQuick"                  { count (0); return (PARSEOP_ACCESSATTRIB_QUICK); }
-"SMBSendReceive"            { count (0); return (PARSEOP_ACCESSATTRIB_SND_RCV); }
-"SMBByte"                   { count (0); return (PARSEOP_ACCESSATTRIB_BYTE); }
-"SMBWord"                   { count (0); return (PARSEOP_ACCESSATTRIB_WORD); }
-"SMBBlock"                  { count (0); return (PARSEOP_ACCESSATTRIB_BLOCK); }
-"SMBProcessCall"            { count (0); return (PARSEOP_ACCESSATTRIB_WORD_CALL); }
-"SMBBlockProcessCall"       { count (0); return (PARSEOP_ACCESSATTRIB_BLOCK_CALL); }
+"ResourceConsumer"          { count (0); return (PARSEOP_RESOURCETYPE_CONSUMER); }
+"ResourceProducer"          { count (0); return (PARSEOP_RESOURCETYPE_PRODUCER); }
 
-"MTR"                       { count (0); return (PARSEOP_MATCHTYPE_MTR); }
-"MEQ"                       { count (0); return (PARSEOP_MATCHTYPE_MEQ); }
-"MLE"                       { count (0); return (PARSEOP_MATCHTYPE_MLE); }
-"MLT"                       { count (0); return (PARSEOP_MATCHTYPE_MLT); }
-"MGE"                       { count (0); return (PARSEOP_MATCHTYPE_MGE); }
-"MGT"                       { count (0); return (PARSEOP_MATCHTYPE_MGT); }
+    /* SerializeRuleKeyword: Control Method Serialization */
 
-"Compatibility"             { count (0); return (PARSEOP_DMATYPE_COMPATIBILITY); }
-"TypeA"                     { count (0); return (PARSEOP_DMATYPE_A); }
-"TypeB"                     { count (0); return (PARSEOP_DMATYPE_B); }
-"TypeF"                     { count (0); return (PARSEOP_DMATYPE_F); }
+"Serialized"                { count (0); return (PARSEOP_SERIALIZERULE_SERIAL); }
+"NotSerialized"             { count (0); return (PARSEOP_SERIALIZERULE_NOTSERIAL); }
 
-"BusMaster"                 { count (0); return (PARSEOP_BUSMASTERTYPE_MASTER); }
-"NotBusMaster"              { count (0); return (PARSEOP_BUSMASTERTYPE_NOTMASTER); }
+    /* ShareTypeKeyword: Interrupt Sharing - Resource Descriptors */
+
+"Shared"                    { count (0); return (PARSEOP_SHARETYPE_SHARED); }
+"Exclusive"                 { count (0); return (PARSEOP_SHARETYPE_EXCLUSIVE); }
+"SharedAndWake"             { count (0); return (PARSEOP_SHARETYPE_SHAREDWAKE); }       /* ACPI 5.0 */
+"ExclusiveAndWake"          { count (0); return (PARSEOP_SHARETYPE_EXCLUSIVEWAKE); }    /* ACPI 5.0 */
+
+    /* SlaveModeKeyword: Resource Descriptors (ACPI 5.0) */
+
+"ControllerInitiated"       { count (0); return (PARSEOP_SLAVEMODE_CONTROLLERINIT); }
+"DeviceInitiated"           { count (0); return (PARSEOP_SLAVEMODE_DEVICEINIT); }
+
+    /* StopBitsKeyword: Resource Descriptors (ACPI 5.0) */
+
+"StopBitsOne"               { count (0); return (PARSEOP_STOPBITS_ONE); }
+"StopBitsOnePlusHalf"       { count (0); return (PARSEOP_STOPBITS_ONEPLUSHALF); }
+"StopBitsTwo"               { count (0); return (PARSEOP_STOPBITS_TWO); }
+"StopBitsZero"              { count (0); return (PARSEOP_STOPBITS_ZERO); }
+
+    /* TransferWidthKeyword: DMA Widths - Fixed DMA Resource Descriptor (ACPI 5.0) */
+
+"Width8bit"                 { count (0); return (PARSEOP_XFERSIZE_8); }
+"Width16bit"                { count (0); return (PARSEOP_XFERSIZE_16); }
+"Width32bit"                { count (0); return (PARSEOP_XFERSIZE_32); }
+"Width64bit"                { count (0); return (PARSEOP_XFERSIZE_64); }
+"Width128bit"               { count (0); return (PARSEOP_XFERSIZE_128); }
+"Width256bit"               { count (0); return (PARSEOP_XFERSIZE_256); }
+
+    /* TranslationKeyword: Translation Density Types - Resource Descriptors */
+
+"SparseTranslation"         { count (0); return (PARSEOP_TRANSLATIONTYPE_SPARSE); }
+"DenseTranslation"          { count (0); return (PARSEOP_TRANSLATIONTYPE_DENSE); }
+
+    /* TypeKeyword: Translation Types - Resource Descriptors */
+
+"TypeTranslation"           { count (0); return (PARSEOP_TYPE_TRANSLATION); }
+"TypeStatic"                { count (0); return (PARSEOP_TYPE_STATIC); }
+
+    /* UpdateRuleKeyword: Field Update Rules */
+
+"Preserve"                  { count (0); return (PARSEOP_UPDATERULE_PRESERVE); }
+"WriteAsOnes"               { count (0); return (PARSEOP_UPDATERULE_ONES); }
+"WriteAsZeros"              { count (0); return (PARSEOP_UPDATERULE_ZEROS); }
+
+    /* WireModeKeyword: SPI Wire Mode - Resource Descriptors (ACPI 5.0) */
+
+"FourWireMode"              { count (0); return (PARSEOP_WIREMODE_FOUR); }
+"ThreeWireMode"             { count (0); return (PARSEOP_WIREMODE_THREE); }
+
+    /* XferTypeKeyword: DMA Transfer Types */
 
 "Transfer8"                 { count (0); return (PARSEOP_XFERTYPE_8); }
 "Transfer8_16"              { count (0); return (PARSEOP_XFERTYPE_8_16); }
 "Transfer16"                { count (0); return (PARSEOP_XFERTYPE_16); }
 
-"ResourceConsumer"          { count (0); return (PARSEOP_RESOURCETYPE_CONSUMER); }
-"ResourceProducer"          { count (0); return (PARSEOP_RESOURCETYPE_PRODUCER); }
-
-"MinFixed"                  { count (0); return (PARSEOP_MINTYPE_FIXED); }
-"MinNotFixed"               { count (0); return (PARSEOP_MINTYPE_NOTFIXED); }
-
-"MaxFixed"                  { count (0); return (PARSEOP_MAXTYPE_FIXED); }
-"MaxNotFixed"               { count (0); return (PARSEOP_MAXTYPE_NOTFIXED); }
-
-"PosDecode"                 { count (0); return (PARSEOP_DECODETYPE_POS); }
-"SubDecode"                 { count (0); return (PARSEOP_DECODETYPE_SUB); }
-
-"ISAOnlyRanges"             { count (0); return (PARSEOP_RANGETYPE_ISAONLY); }
-"NonISAOnlyRanges"          { count (0); return (PARSEOP_RANGETYPE_NONISAONLY); }
-"EntireRange"               { count (0); return (PARSEOP_RANGETYPE_ENTIRE); }
-
-"Cacheable"                 { count (0); return (PARSEOP_MEMTYPE_CACHEABLE); }
-"WriteCombining"            { count (0); return (PARSEOP_MEMTYPE_WRITECOMBINING); }
-"Prefetchable"              { count (0); return (PARSEOP_MEMTYPE_PREFETCHABLE); }
-"NonCacheable"              { count (0); return (PARSEOP_MEMTYPE_NONCACHEABLE); }
-
-"ReadWrite"                 { count (0); return (PARSEOP_READWRITETYPE_BOTH); }
-"ReadOnly"                  { count (0); return (PARSEOP_READWRITETYPE_READONLY); }
-
-"Edge"                      { count (0); return (PARSEOP_INTTYPE_EDGE); }
-"Level"                     { count (0); return (PARSEOP_INTTYPE_LEVEL); }
-
-"ActiveHigh"                { count (0); return (PARSEOP_INTLEVEL_ACTIVEHIGH); }
-"ActiveLow"                 { count (0); return (PARSEOP_INTLEVEL_ACTIVELOW); }
-
-"Shared"                    { count (0); return (PARSEOP_SHARETYPE_SHARED); }
-"Exclusive"                 { count (0); return (PARSEOP_SHARETYPE_EXCLUSIVE); }
-
-"Decode10"                  { count (0); return (PARSEOP_IODECODETYPE_10); }
-"Decode16"                  { count (0); return (PARSEOP_IODECODETYPE_16); }
-
-"TypeTranslation"           { count (0); return (PARSEOP_TYPE_TRANSLATION); }
-"TypeStatic"                { count (0); return (PARSEOP_TYPE_STATIC); }
-
-"SparseTranslation"         { count (0); return (PARSEOP_TRANSLATIONTYPE_SPARSE); }
-"DenseTranslation"          { count (0); return (PARSEOP_TRANSLATIONTYPE_DENSE); }
-
-"AddressRangeMemory"        { count (0); return (PARSEOP_ADDRESSTYPE_MEMORY); }
-"AddressRangeReserved"      { count (0); return (PARSEOP_ADDRESSTYPE_RESERVED); }
-"AddressRangeNVS"           { count (0); return (PARSEOP_ADDRESSTYPE_NVS); }
-"AddressRangeACPI"          { count (0); return (PARSEOP_ADDRESSTYPE_ACPI); }
+    /* Predefined compiler names */
 
 "__DATE__"                  { count (0); return (PARSEOP___DATE__); }
 "__FILE__"                  { count (0); return (PARSEOP___FILE__); }
 "__LINE__"                  { count (0); return (PARSEOP___LINE__); }
+"__PATH__"                  { count (0); return (PARSEOP___PATH__); }
+
 
 "{"                         { count (0); return('{'); }
 "}"                         { count (0); return('}'); }
@@ -402,7 +592,6 @@
 "("                         { count (0); return('('); }
 ")"                         { count (0); return(')'); }
 
-
 {NameSeg}                   { char *s;
                                 count (0);
                                 s=malloc (ACPI_NAME_SIZE + 1);
@@ -478,7 +667,6 @@
     void)
 {
     ASL_FILE_NODE           *Fnode;
-    FILE                    *InputFile = NULL;
 
 
     Fnode = InputStack;
@@ -497,7 +685,6 @@
     /* Update the top-of-stack */
 
     InputStack = Fnode->Next;
-    InputFile = Fnode->File;
 
     /* Reset global line counter and filename */
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/compiler/aslcompiler.y
--- a/head/sys/contrib/dev/acpica/compiler/aslcompiler.y	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/compiler/aslcompiler.y	Tue Dec 06 20:26:16 2011 +0200
@@ -1,8 +1,7 @@
-
 %{
 /******************************************************************************
  *
- * Module Name: aslcompiler.y - Bison input file (ASL grammar and actions)
+ * Module Name: aslcompiler.y - Bison/Yacc input file (ASL grammar and actions)
  *
  *****************************************************************************/
 
@@ -106,22 +105,28 @@
  * These shift/reduce conflicts are expected. There should be zero
  * reduce/reduce conflicts.
  */
-%expect 60
-
-/*
+%expect 86
+
+/******************************************************************************
+ *
  * Token types: These are returned by the lexer
  *
  * NOTE: This list MUST match the AslKeywordMapping table found
  *       in aslmap.c EXACTLY!  Double check any changes!
- */
+ *
+ *****************************************************************************/
+
 %token <i> PARSEOP_ACCESSAS
 %token <i> PARSEOP_ACCESSATTRIB_BLOCK
 %token <i> PARSEOP_ACCESSATTRIB_BLOCK_CALL
 %token <i> PARSEOP_ACCESSATTRIB_BYTE
-%token <i> PARSEOP_ACCESSATTRIB_WORD_CALL
+%token <i> PARSEOP_ACCESSATTRIB_MULTIBYTE
 %token <i> PARSEOP_ACCESSATTRIB_QUICK
+%token <i> PARSEOP_ACCESSATTRIB_RAW_BYTES
+%token <i> PARSEOP_ACCESSATTRIB_RAW_PROCESS
 %token <i> PARSEOP_ACCESSATTRIB_SND_RCV
 %token <i> PARSEOP_ACCESSATTRIB_WORD
+%token <i> PARSEOP_ACCESSATTRIB_WORD_CALL
 %token <i> PARSEOP_ACCESSTYPE_ANY
 %token <i> PARSEOP_ACCESSTYPE_BUF
 %token <i> PARSEOP_ACCESSTYPE_BYTE
@@ -130,7 +135,8 @@
 %token <i> PARSEOP_ACCESSTYPE_WORD
 %token <i> PARSEOP_ACQUIRE
 %token <i> PARSEOP_ADD
-%token <i> PARSEOP_ADDRESSSPACE_FFIXEDHW
+%token <i> PARSEOP_ADDRESSINGMODE_7BIT
+%token <i> PARSEOP_ADDRESSINGMODE_10BIT
 %token <i> PARSEOP_ADDRESSTYPE_ACPI
 %token <i> PARSEOP_ADDRESSTYPE_MEMORY
 %token <i> PARSEOP_ADDRESSTYPE_NVS
@@ -145,6 +151,11 @@
 %token <i> PARSEOP_ARG5
 %token <i> PARSEOP_ARG6
 %token <i> PARSEOP_BANKFIELD
+%token <i> PARSEOP_BITSPERBYTE_EIGHT
+%token <i> PARSEOP_BITSPERBYTE_FIVE
+%token <i> PARSEOP_BITSPERBYTE_NINE
+%token <i> PARSEOP_BITSPERBYTE_SEVEN
+%token <i> PARSEOP_BITSPERBYTE_SIX
 %token <i> PARSEOP_BREAK
 %token <i> PARSEOP_BREAKPOINT
 %token <i> PARSEOP_BUFFER
@@ -152,9 +163,14 @@
 %token <i> PARSEOP_BUSMASTERTYPE_NOTMASTER
 %token <i> PARSEOP_BYTECONST
 %token <i> PARSEOP_CASE
+%token <i> PARSEOP_CLOCKPHASE_FIRST
+%token <i> PARSEOP_CLOCKPHASE_SECOND
+%token <i> PARSEOP_CLOCKPOLARITY_HIGH
+%token <i> PARSEOP_CLOCKPOLARITY_LOW
 %token <i> PARSEOP_CONCATENATE
 %token <i> PARSEOP_CONCATENATERESTEMPLATE
 %token <i> PARSEOP_CONDREFOF
+%token <i> PARSEOP_CONNECTION
 %token <i> PARSEOP_CONTINUE
 %token <i> PARSEOP_COPYOBJECT
 %token <i> PARSEOP_CREATEBITFIELD
@@ -163,6 +179,7 @@
 %token <i> PARSEOP_CREATEFIELD
 %token <i> PARSEOP_CREATEQWORDFIELD
 %token <i> PARSEOP_CREATEWORDFIELD
+%token <i> PARSEOP_DATABUFFER
 %token <i> PARSEOP_DATATABLEREGION
 %token <i> PARSEOP_DEBUG
 %token <i> PARSEOP_DECODETYPE_POS
@@ -173,6 +190,8 @@
 %token <i> PARSEOP_DEFINITIONBLOCK
 %token <i> PARSEOP_DEREFOF
 %token <i> PARSEOP_DEVICE
+%token <i> PARSEOP_DEVICEPOLARITY_HIGH
+%token <i> PARSEOP_DEVICEPOLARITY_LOW
 %token <i> PARSEOP_DIVIDE
 %token <i> PARSEOP_DMA
 %token <i> PARSEOP_DMATYPE_A
@@ -187,6 +206,8 @@
 %token <i> PARSEOP_ELSE
 %token <i> PARSEOP_ELSEIF
 %token <i> PARSEOP_ENDDEPENDENTFN
+%token <i> PARSEOP_ENDIAN_BIG
+%token <i> PARSEOP_ENDIAN_LITTLE
 %token <i> PARSEOP_ENDTAG
 %token <i> PARSEOP_ERRORNODE
 %token <i> PARSEOP_EVENT
@@ -198,9 +219,16 @@
 %token <i> PARSEOP_FIELD
 %token <i> PARSEOP_FINDSETLEFTBIT
 %token <i> PARSEOP_FINDSETRIGHTBIT
+%token <i> PARSEOP_FIXEDDMA
 %token <i> PARSEOP_FIXEDIO
+%token <i> PARSEOP_FLOWCONTROL_HW
+%token <i> PARSEOP_FLOWCONTROL_NONE
+%token <i> PARSEOP_FLOWCONTROL_SW
 %token <i> PARSEOP_FROMBCD
 %token <i> PARSEOP_FUNCTION
+%token <i> PARSEOP_GPIO_INT
+%token <i> PARSEOP_GPIO_IO
+%token <i> PARSEOP_I2C_SERIALBUS
 %token <i> PARSEOP_IF
 %token <i> PARSEOP_INCLUDE
 %token <i> PARSEOP_INCLUDE_CSTYLE
@@ -210,6 +238,7 @@
 %token <i> PARSEOP_INDEXFIELD
 %token <i> PARSEOP_INTEGER
 %token <i> PARSEOP_INTERRUPT
+%token <i> PARSEOP_INTLEVEL_ACTIVEBOTH
 %token <i> PARSEOP_INTLEVEL_ACTIVEHIGH
 %token <i> PARSEOP_INTLEVEL_ACTIVELOW
 %token <i> PARSEOP_INTTYPE_EDGE
@@ -217,6 +246,10 @@
 %token <i> PARSEOP_IO
 %token <i> PARSEOP_IODECODETYPE_10
 %token <i> PARSEOP_IODECODETYPE_16
+%token <i> PARSEOP_IORESTRICT_IN
+%token <i> PARSEOP_IORESTRICT_NONE
+%token <i> PARSEOP_IORESTRICT_OUT
+%token <i> PARSEOP_IORESTRICT_PRESERVE
 %token <i> PARSEOP_IRQ
 %token <i> PARSEOP_IRQNOFLAGS
 %token <i> PARSEOP_LAND
@@ -297,6 +330,15 @@
 %token <i> PARSEOP_OR
 %token <i> PARSEOP_PACKAGE
 %token <i> PARSEOP_PACKAGE_LENGTH
+%token <i> PARSEOP_PARITYTYPE_EVEN
+%token <i> PARSEOP_PARITYTYPE_MARK
+%token <i> PARSEOP_PARITYTYPE_NONE
+%token <i> PARSEOP_PARITYTYPE_ODD
+%token <i> PARSEOP_PARITYTYPE_SPACE
+%token <i> PARSEOP_PIN_NOPULL
+%token <i> PARSEOP_PIN_PULLDEFAULT
+%token <i> PARSEOP_PIN_PULLDOWN
+%token <i> PARSEOP_PIN_PULLUP
 %token <i> PARSEOP_POWERRESOURCE
 %token <i> PARSEOP_PROCESSOR
 %token <i> PARSEOP_QWORDCONST
@@ -312,6 +354,9 @@
 %token <i> PARSEOP_REFOF
 %token <i> PARSEOP_REGIONSPACE_CMOS
 %token <i> PARSEOP_REGIONSPACE_EC
+%token <i> PARSEOP_REGIONSPACE_FFIXEDHW
+%token <i> PARSEOP_REGIONSPACE_GPIO
+%token <i> PARSEOP_REGIONSPACE_GSBUS
 %token <i> PARSEOP_REGIONSPACE_IO
 %token <i> PARSEOP_REGIONSPACE_IPMI
 %token <i> PARSEOP_REGIONSPACE_MEM
@@ -331,15 +376,24 @@
 %token <i> PARSEOP_SERIALIZERULE_NOTSERIAL
 %token <i> PARSEOP_SERIALIZERULE_SERIAL
 %token <i> PARSEOP_SHARETYPE_EXCLUSIVE
+%token <i> PARSEOP_SHARETYPE_EXCLUSIVEWAKE
 %token <i> PARSEOP_SHARETYPE_SHARED
+%token <i> PARSEOP_SHARETYPE_SHAREDWAKE
 %token <i> PARSEOP_SHIFTLEFT
 %token <i> PARSEOP_SHIFTRIGHT
 %token <i> PARSEOP_SIGNAL
 %token <i> PARSEOP_SIZEOF
+%token <i> PARSEOP_SLAVEMODE_CONTROLLERINIT
+%token <i> PARSEOP_SLAVEMODE_DEVICEINIT
 %token <i> PARSEOP_SLEEP
+%token <i> PARSEOP_SPI_SERIALBUS
 %token <i> PARSEOP_STALL
 %token <i> PARSEOP_STARTDEPENDENTFN
 %token <i> PARSEOP_STARTDEPENDENTFN_NOPRI
+%token <i> PARSEOP_STOPBITS_ONE
+%token <i> PARSEOP_STOPBITS_ONEPLUSHALF
+%token <i> PARSEOP_STOPBITS_TWO
+%token <i> PARSEOP_STOPBITS_ZERO
 %token <i> PARSEOP_STORE
 %token <s> PARSEOP_STRING_LITERAL
 %token <i> PARSEOP_SUBTRACT
@@ -357,6 +411,7 @@
 %token <i> PARSEOP_TRANSLATIONTYPE_SPARSE
 %token <i> PARSEOP_TYPE_STATIC
 %token <i> PARSEOP_TYPE_TRANSLATION
+%token <i> PARSEOP_UART_SERIALBUS
 %token <i> PARSEOP_UNICODE
 %token <i> PARSEOP_UNLOAD
 %token <i> PARSEOP_UPDATERULE_ONES
@@ -367,10 +422,18 @@
 %token <i> PARSEOP_VENDORSHORT
 %token <i> PARSEOP_WAIT
 %token <i> PARSEOP_WHILE
+%token <i> PARSEOP_WIREMODE_FOUR
+%token <i> PARSEOP_WIREMODE_THREE
 %token <i> PARSEOP_WORDBUSNUMBER
 %token <i> PARSEOP_WORDCONST
 %token <i> PARSEOP_WORDIO
 %token <i> PARSEOP_WORDSPACE
+%token <i> PARSEOP_XFERSIZE_8
+%token <i> PARSEOP_XFERSIZE_16
+%token <i> PARSEOP_XFERSIZE_32
+%token <i> PARSEOP_XFERSIZE_64
+%token <i> PARSEOP_XFERSIZE_128
+%token <i> PARSEOP_XFERSIZE_256
 %token <i> PARSEOP_XFERTYPE_8
 %token <i> PARSEOP_XFERTYPE_8_16
 %token <i> PARSEOP_XFERTYPE_16
@@ -384,64 +447,64 @@
 %token <i> PARSEOP___DATE__
 %token <i> PARSEOP___FILE__
 %token <i> PARSEOP___LINE__
-
-/*
+%token <i> PARSEOP___PATH__
+
+
+/******************************************************************************
+ *
  * Production names
- */
-
+ *
+ *****************************************************************************/
+
+%type <n> ArgList
 %type <n> ASLCode
+%type <n> BufferData
+%type <n> BufferTermData
+%type <n> CompilerDirective
+%type <n> DataObject
 %type <n> DefinitionBlockTerm
-%type <n> TermList
-%type <n> Term
-%type <n> CompilerDirective
-%type <n> ObjectList
-%type <n> Object
-%type <n> DataObject
-%type <n> BufferData
-%type <n> PackageData
 %type <n> IntegerData
-%type <n> StringData
 %type <n> NamedObject
 %type <n> NameSpaceModifier
-%type <n> UserTerm
-%type <n> ArgList
-%type <n> TermArg
-%type <n> Target
-%type <n> RequiredTarget
-%type <n> SimpleTarget
-%type <n> BufferTermData
+%type <n> Object
+%type <n> ObjectList
+%type <n> PackageData
 %type <n> ParameterTypePackage
 %type <n> ParameterTypePackageList
 %type <n> ParameterTypesPackage
 %type <n> ParameterTypesPackageList
+%type <n> RequiredTarget
+%type <n> SimpleTarget
+%type <n> StringData
+%type <n> Target
+%type <n> Term
+%type <n> TermArg
+%type <n> TermList
+%type <n> UserTerm
+
+/* Type4Opcode is obsolete */
 
 %type <n> Type1Opcode
-%type <n> Type2Opcode
-%type <n> Type2IntegerOpcode
-%type <n> Type2StringOpcode
 %type <n> Type2BufferOpcode
 %type <n> Type2BufferOrStringOpcode
+%type <n> Type2IntegerOpcode
+%type <n> Type2Opcode
+%type <n> Type2StringOpcode
 %type <n> Type3Opcode
-
-/* Obsolete %type <n> Type4Opcode */
-
 %type <n> Type5Opcode
 %type <n> Type6Opcode
 
-%type <n> LineTerm
-%type <n> IncludeTerm
-%type <n> IncludeCStyleTerm
+%type <n> AccessAsTerm
 %type <n> ExternalTerm
-
-%type <n> FieldUnitList
 %type <n> FieldUnit
 %type <n> FieldUnitEntry
-
+%type <n> FieldUnitList
+%type <n> IncludeCStyleTerm
+%type <n> IncludeTerm
+%type <n> LineTerm
 %type <n> OffsetTerm
-%type <n> AccessAsTerm
 %type <n> OptionalAccessAttribTerm
 
-
 /* Named Objects */
 
 %type <n> BankFieldTerm
@@ -465,7 +528,6 @@
 %type <n> ProcessorTerm
 %type <n> ThermalZoneTerm
 
-
 /* Namespace modifiers */
 
 %type <n> AliasTerm
@@ -474,13 +536,16 @@
 
 /* Type 1 opcodes */
 
+%type <n> BreakPointTerm
 %type <n> BreakTerm
-%type <n> BreakPointTerm
+%type <n> CaseDefaultTermList
+%type <n> CaseTerm
 %type <n> ContinueTerm
+%type <n> DefaultTerm
+%type <n> ElseTerm
 %type <n> FatalTerm
 %type <n> IfElseTerm
 %type <n> IfTerm
-%type <n> ElseTerm
 %type <n> LoadTerm
 %type <n> NoOpTerm
 %type <n> NotifyTerm
@@ -491,20 +556,17 @@
 %type <n> SleepTerm
 %type <n> StallTerm
 %type <n> SwitchTerm
-%type <n> CaseDefaultTermList
-//%type <n> CaseTermList
-%type <n> CaseTerm
-%type <n> DefaultTerm
 %type <n> UnloadTerm
 %type <n> WhileTerm
+//%type <n> CaseTermList
 
 /* Type 2 opcodes */
 
 %type <n> AcquireTerm
 %type <n> AddTerm
 %type <n> AndTerm
+%type <n> ConcatResTerm
 %type <n> ConcatTerm
-%type <n> ConcatResTerm
 %type <n> CondRefOfTerm
 %type <n> CopyObjectTerm
 %type <n> DecTerm
@@ -517,12 +579,12 @@
 %type <n> IndexTerm
 %type <n> LAndTerm
 %type <n> LEqualTerm
+%type <n> LGreaterEqualTerm
 %type <n> LGreaterTerm
-%type <n> LGreaterEqualTerm
+%type <n> LLessEqualTerm
 %type <n> LLessTerm
-%type <n> LLessEqualTerm
+%type <n> LNotEqualTerm
 %type <n> LNotTerm
-%type <n> LNotEqualTerm
 %type <n> LoadTableTerm
 %type <n> LOrTerm
 %type <n> MatchTerm
@@ -550,39 +612,49 @@
 %type <n> WaitTerm
 %type <n> XOrTerm
 
-%type <n> OptionalTermArg
-%type <n> OptionalReturnArg
-%type <n> OptionalListString
-
-
 /* Keywords */
 
+%type <n> AccessAttribKeyword
+%type <n> AccessTypeKeyword
+%type <n> AddressingModeKeyword
+%type <n> AddressKeyword
+%type <n> AddressSpaceKeyword
+%type <n> BitsPerByteKeyword
+%type <n> ClockPhaseKeyword
+%type <n> ClockPolarityKeyword
+%type <n> DecodeKeyword
+%type <n> DevicePolarityKeyword
+%type <n> DMATypeKeyword
+%type <n> EndianKeyword
+%type <n> FlowControlKeyword
+%type <n> InterruptLevel
+%type <n> InterruptTypeKeyword
+%type <n> IODecodeKeyword
+%type <n> IoRestrictionKeyword
+%type <n> LockRuleKeyword
+%type <n> MatchOpKeyword
+%type <n> MaxKeyword
+%type <n> MemTypeKeyword
+%type <n> MinKeyword
 %type <n> ObjectTypeKeyword
-%type <n> AccessTypeKeyword
-%type <n> AccessAttribKeyword
-%type <n> LockRuleKeyword
+%type <n> OptionalBusMasterKeyword
+%type <n> OptionalReadWriteKeyword
+%type <n> ParityTypeKeyword
+%type <n> PinConfigByte
+%type <n> PinConfigKeyword
+%type <n> RangeTypeKeyword
+%type <n> RegionSpaceKeyword
+%type <n> ResourceTypeKeyword
+%type <n> SerializeRuleKeyword
+%type <n> ShareTypeKeyword
+%type <n> SlaveModeKeyword
+%type <n> StopBitsKeyword
+%type <n> TranslationKeyword
+%type <n> TypeKeyword
 %type <n> UpdateRuleKeyword
-%type <n> RegionSpaceKeyword
-%type <n> AddressSpaceKeyword
-%type <n> MatchOpKeyword
-%type <n> SerializeRuleKeyword
-%type <n> DMATypeKeyword
-%type <n> OptionalBusMasterKeyword
+%type <n> WireModeKeyword
+%type <n> XferSizeKeyword
 %type <n> XferTypeKeyword
-%type <n> ResourceTypeKeyword
-%type <n> MinKeyword
-%type <n> MaxKeyword
-%type <n> DecodeKeyword
-%type <n> RangeTypeKeyword
-%type <n> MemTypeKeyword
-%type <n> OptionalReadWriteKeyword
-%type <n> InterruptTypeKeyword
-%type <n> InterruptLevel
-%type <n> ShareTypeKeyword
-%type <n> IODecodeKeyword
-%type <n> TypeKeyword
-%type <n> TranslationKeyword
-%type <n> AddressKeyword
 
 /* Types */
 
@@ -599,31 +671,34 @@
 %type <n> String
 
 %type <n> ConstTerm
+%type <n> ConstExprTerm
 %type <n> ByteConstExpr
 %type <n> WordConstExpr
 %type <n> DWordConstExpr
 %type <n> QWordConstExpr
-%type <n> ConstExprTerm
-
+
+%type <n> DWordList
 %type <n> BufferTerm
 %type <n> ByteList
-%type <n> DWordList
-
+
+%type <n> PackageElement
+%type <n> PackageList
 %type <n> PackageTerm
-%type <n> PackageList
-%type <n> PackageElement
-
 %type <n> VarPackageLengthTerm
 
 /* Macros */
 
 %type <n> EISAIDTerm
+%type <n> ResourceMacroList
+%type <n> ResourceMacroTerm
 %type <n> ResourceTemplateTerm
 %type <n> ToUUIDTerm
 %type <n> UnicodeTerm
-%type <n> ResourceMacroList
-%type <n> ResourceMacroTerm
-
+
+/* Resource Descriptors */
+
+%type <n> ConnectionTerm
+%type <n> DataBufferTerm
 %type <n> DMATerm
 %type <n> DWordIOTerm
 %type <n> DWordMemoryTerm
@@ -632,7 +707,11 @@
 %type <n> ExtendedIOTerm
 %type <n> ExtendedMemoryTerm
 %type <n> ExtendedSpaceTerm
+%type <n> FixedDmaTerm
 %type <n> FixedIOTerm
+%type <n> GpioIntTerm
+%type <n> GpioIoTerm
+%type <n> I2cSerialBusTerm
 %type <n> InterruptTerm
 %type <n> IOTerm
 %type <n> IRQNoFlagsTerm
@@ -640,59 +719,75 @@
 %type <n> Memory24Term
 %type <n> Memory32FixedTerm
 %type <n> Memory32Term
+%type <n> NameSeg
+%type <n> NameString
 %type <n> QWordIOTerm
 %type <n> QWordMemoryTerm
 %type <n> QWordSpaceTerm
 %type <n> RegisterTerm
+%type <n> SpiSerialBusTerm
+%type <n> StartDependentFnNoPriTerm
 %type <n> StartDependentFnTerm
-%type <n> StartDependentFnNoPriTerm
+%type <n> UartSerialBusTerm
 %type <n> VendorLongTerm
 %type <n> VendorShortTerm
 %type <n> WordBusNumberTerm
 %type <n> WordIOTerm
 %type <n> WordSpaceTerm
 
-%type <n> NameString
-%type <n> NameSeg
-
-
 /* Local types that help construct the AML, not in ACPI spec */
 
+%type <n> AmlPackageLengthTerm
 %type <n> IncludeEndTerm
-%type <n> AmlPackageLengthTerm
+%type <n> NameStringItem
+%type <n> TermArgItem
+
+%type <n> OptionalAccessSize
+%type <n> OptionalAddressingMode
+%type <n> OptionalAddressRange
+%type <n> OptionalBitsPerByte
+%type <n> OptionalBuffer_Last
 %type <n> OptionalByteConstExpr
+%type <n> OptionalCount
+%type <n> OptionalDecodeType
+%type <n> OptionalDevicePolarity
 %type <n> OptionalDWordConstExpr
-%type <n> OptionalQWordConstExpr
-%type <n> OptionalSerializeRuleKeyword
-%type <n> OptionalResourceType_First
-%type <n> OptionalResourceType
-%type <n> OptionalMinType
+%type <n> OptionalEndian
+%type <n> OptionalFlowControl
+%type <n> OptionalIoRestriction
+%type <n> OptionalListString
 %type <n> OptionalMaxType
 %type <n> OptionalMemType
-%type <n> OptionalCount
-%type <n> OptionalDecodeType
-%type <n> OptionalRangeType
-%type <n> OptionalShareType
-%type <n> OptionalType
-%type <n> OptionalType_Last
-%type <n> OptionalTranslationType_Last
-%type <n> OptionalStringData
+%type <n> OptionalMinType
 %type <n> OptionalNameString
 %type <n> OptionalNameString_First
 %type <n> OptionalNameString_Last
-%type <n> OptionalAddressRange
 %type <n> OptionalObjectTypeKeyword
 %type <n> OptionalParameterTypePackage
 %type <n> OptionalParameterTypesPackage
+%type <n> OptionalParityType
+%type <n> OptionalQWordConstExpr
+%type <n> OptionalRangeType
 %type <n> OptionalReference
-%type <n> OptionalAccessSize
-
-%type <n> TermArgItem
-%type <n> NameStringItem
+%type <n> OptionalResourceType
+%type <n> OptionalResourceType_First
+%type <n> OptionalReturnArg
+%type <n> OptionalSerializeRuleKeyword
+%type <n> OptionalShareType
+%type <n> OptionalShareType_First
+%type <n> OptionalSlaveMode
+%type <n> OptionalStopBits
+%type <n> OptionalStringData
+%type <n> OptionalTermArg
+%type <n> OptionalTranslationType_Last
+%type <n> OptionalType
+%type <n> OptionalType_Last
+%type <n> OptionalWireMode
+%type <n> OptionalWordConst
+%type <n> OptionalWordConstExpr
+%type <n> OptionalXferSize
 
 %%
-
-
 /*******************************************************************************
  *
  * Production rules start here
@@ -745,7 +840,9 @@
 TermList
     :                               {$$ = NULL;}
     | TermList Term                 {$$ = TrLinkPeerNode (TrSetNodeFlags ($1, NODE_RESULT_NOT_USED),$2);}
+    | TermList Term ';'             {$$ = TrLinkPeerNode (TrSetNodeFlags ($1, NODE_RESULT_NOT_USED),$2);}
     | TermList ';' Term             {$$ = TrLinkPeerNode (TrSetNodeFlags ($1, NODE_RESULT_NOT_USED),$3);}
+    | TermList ';' Term ';'         {$$ = TrLinkPeerNode (TrSetNodeFlags ($1, NODE_RESULT_NOT_USED),$3);}
     ;
 
 Term
@@ -1107,6 +1204,7 @@
     : FieldUnitEntry                {}
     | OffsetTerm                    {}
     | AccessAsTerm                  {}
+    | ConnectionTerm                {}
     ;
 
 FieldUnitEntry
@@ -1132,6 +1230,21 @@
         error ')'                   {$$ = AslDoError(); yyclearin;}
     ;
 
+ConnectionTerm
+    : PARSEOP_CONNECTION '('
+        NameString
+        ')'                         {$$ = TrCreateNode (PARSEOP_CONNECTION,1,$3);}
+    | PARSEOP_CONNECTION '('        {$<n>$ = TrCreateLeafNode (PARSEOP_CONNECTION);}
+        ResourceMacroTerm
+        ')'                         {$$ = TrLinkChildren ($<n>3, 1,
+                                            TrLinkChildren (TrCreateLeafNode (PARSEOP_RESOURCETEMPLATE), 3,
+                                                TrCreateLeafNode (PARSEOP_DEFAULT_ARG),
+                                                TrCreateLeafNode (PARSEOP_DEFAULT_ARG),
+                                                $4));}
+    | PARSEOP_CONNECTION '('
+        error ')'                   {$$ = AslDoError(); yyclearin;}
+    ;
+
 CreateBitFieldTerm
     : PARSEOP_CREATEBITFIELD '('	{$<n>$ = TrCreateLeafNode (PARSEOP_CREATEBITFIELD);}
         TermArg
@@ -2052,6 +2165,151 @@
 /******* Keywords *************************************************************/
 
 
+AccessAttribKeyword
+    : PARSEOP_ACCESSATTRIB_BLOCK            {$$ = TrCreateLeafNode (PARSEOP_ACCESSATTRIB_BLOCK);}
+    | PARSEOP_ACCESSATTRIB_BLOCK_CALL       {$$ = TrCreateLeafNode (PARSEOP_ACCESSATTRIB_BLOCK_CALL);}
+    | PARSEOP_ACCESSATTRIB_BYTE             {$$ = TrCreateLeafNode (PARSEOP_ACCESSATTRIB_BYTE);}
+    | PARSEOP_ACCESSATTRIB_QUICK            {$$ = TrCreateLeafNode (PARSEOP_ACCESSATTRIB_QUICK );}
+    | PARSEOP_ACCESSATTRIB_SND_RCV          {$$ = TrCreateLeafNode (PARSEOP_ACCESSATTRIB_SND_RCV);}
+    | PARSEOP_ACCESSATTRIB_WORD             {$$ = TrCreateLeafNode (PARSEOP_ACCESSATTRIB_WORD);}
+    | PARSEOP_ACCESSATTRIB_WORD_CALL        {$$ = TrCreateLeafNode (PARSEOP_ACCESSATTRIB_WORD_CALL);}
+    | PARSEOP_ACCESSATTRIB_MULTIBYTE '('    {$<n>$ = TrCreateLeafNode (PARSEOP_ACCESSATTRIB_MULTIBYTE);}
+        ByteConst
+        ')'                                 {$$ = TrLinkChildren ($<n>3,1,$4);}
+    | PARSEOP_ACCESSATTRIB_RAW_BYTES '('    {$<n>$ = TrCreateLeafNode (PARSEOP_ACCESSATTRIB_RAW_BYTES);}
+        ByteConst
+        ')'                                 {$$ = TrLinkChildren ($<n>3,1,$4);}
+    | PARSEOP_ACCESSATTRIB_RAW_PROCESS '('  {$<n>$ = TrCreateLeafNode (PARSEOP_ACCESSATTRIB_RAW_PROCESS);}
+        ByteConst
+        ')'                                 {$$ = TrLinkChildren ($<n>3,1,$4);}
+    ;
+
+AccessTypeKeyword
+    : PARSEOP_ACCESSTYPE_ANY                {$$ = TrCreateLeafNode (PARSEOP_ACCESSTYPE_ANY);}
+    | PARSEOP_ACCESSTYPE_BYTE               {$$ = TrCreateLeafNode (PARSEOP_ACCESSTYPE_BYTE);}
+    | PARSEOP_ACCESSTYPE_WORD               {$$ = TrCreateLeafNode (PARSEOP_ACCESSTYPE_WORD);}
+    | PARSEOP_ACCESSTYPE_DWORD              {$$ = TrCreateLeafNode (PARSEOP_ACCESSTYPE_DWORD);}
+    | PARSEOP_ACCESSTYPE_QWORD              {$$ = TrCreateLeafNode (PARSEOP_ACCESSTYPE_QWORD);}
+    | PARSEOP_ACCESSTYPE_BUF                {$$ = TrCreateLeafNode (PARSEOP_ACCESSTYPE_BUF);}
+    ;
+
+AddressingModeKeyword
+    : PARSEOP_ADDRESSINGMODE_7BIT           {$$ = TrCreateLeafNode (PARSEOP_ADDRESSINGMODE_7BIT);}
+    | PARSEOP_ADDRESSINGMODE_10BIT          {$$ = TrCreateLeafNode (PARSEOP_ADDRESSINGMODE_10BIT);}
+    ;
+
+AddressKeyword
+    : PARSEOP_ADDRESSTYPE_MEMORY            {$$ = TrCreateLeafNode (PARSEOP_ADDRESSTYPE_MEMORY);}
+    | PARSEOP_ADDRESSTYPE_RESERVED          {$$ = TrCreateLeafNode (PARSEOP_ADDRESSTYPE_RESERVED);}
+    | PARSEOP_ADDRESSTYPE_NVS               {$$ = TrCreateLeafNode (PARSEOP_ADDRESSTYPE_NVS);}
+    | PARSEOP_ADDRESSTYPE_ACPI              {$$ = TrCreateLeafNode (PARSEOP_ADDRESSTYPE_ACPI);}
+    ;
+
+AddressSpaceKeyword
+    : ByteConst								{$$ = UtCheckIntegerRange ($1, 0x80, 0xFF);}
+    | RegionSpaceKeyword					{}
+    ;
+
+BitsPerByteKeyword
+    : PARSEOP_BITSPERBYTE_FIVE              {$$ = TrCreateLeafNode (PARSEOP_BITSPERBYTE_FIVE);}
+    | PARSEOP_BITSPERBYTE_SIX               {$$ = TrCreateLeafNode (PARSEOP_BITSPERBYTE_SIX);}
+    | PARSEOP_BITSPERBYTE_SEVEN             {$$ = TrCreateLeafNode (PARSEOP_BITSPERBYTE_SEVEN);}
+    | PARSEOP_BITSPERBYTE_EIGHT             {$$ = TrCreateLeafNode (PARSEOP_BITSPERBYTE_EIGHT);}
+    | PARSEOP_BITSPERBYTE_NINE              {$$ = TrCreateLeafNode (PARSEOP_BITSPERBYTE_NINE);}
+    ;
+
+ClockPhaseKeyword
+    : PARSEOP_CLOCKPHASE_FIRST              {$$ = TrCreateLeafNode (PARSEOP_CLOCKPHASE_FIRST);}
+    | PARSEOP_CLOCKPHASE_SECOND             {$$ = TrCreateLeafNode (PARSEOP_CLOCKPHASE_SECOND);}
+    ;
+
+ClockPolarityKeyword
+    : PARSEOP_CLOCKPOLARITY_LOW             {$$ = TrCreateLeafNode (PARSEOP_CLOCKPOLARITY_LOW);}
+    | PARSEOP_CLOCKPOLARITY_HIGH            {$$ = TrCreateLeafNode (PARSEOP_CLOCKPOLARITY_HIGH);}
+    ;
+
+DecodeKeyword
+    : PARSEOP_DECODETYPE_POS                {$$ = TrCreateLeafNode (PARSEOP_DECODETYPE_POS);}
+    | PARSEOP_DECODETYPE_SUB                {$$ = TrCreateLeafNode (PARSEOP_DECODETYPE_SUB);}
+    ;
+
+DevicePolarityKeyword
+    : PARSEOP_DEVICEPOLARITY_LOW            {$$ = TrCreateLeafNode (PARSEOP_DEVICEPOLARITY_LOW);}
+    | PARSEOP_DEVICEPOLARITY_HIGH           {$$ = TrCreateLeafNode (PARSEOP_DEVICEPOLARITY_HIGH);}
+    ;
+
+DMATypeKeyword
+    : PARSEOP_DMATYPE_A                     {$$ = TrCreateLeafNode (PARSEOP_DMATYPE_A);}
+    | PARSEOP_DMATYPE_COMPATIBILITY         {$$ = TrCreateLeafNode (PARSEOP_DMATYPE_COMPATIBILITY);}
+    | PARSEOP_DMATYPE_B                     {$$ = TrCreateLeafNode (PARSEOP_DMATYPE_B);}
+    | PARSEOP_DMATYPE_F                     {$$ = TrCreateLeafNode (PARSEOP_DMATYPE_F);}
+    ;
+
+EndianKeyword
+    : PARSEOP_ENDIAN_LITTLE                 {$$ = TrCreateLeafNode (PARSEOP_ENDIAN_LITTLE);}
+    | PARSEOP_ENDIAN_BIG                    {$$ = TrCreateLeafNode (PARSEOP_ENDIAN_BIG);}
+    ;
+
+FlowControlKeyword
+    : PARSEOP_FLOWCONTROL_HW                {$$ = TrCreateLeafNode (PARSEOP_FLOWCONTROL_HW);}
+    | PARSEOP_FLOWCONTROL_NONE              {$$ = TrCreateLeafNode (PARSEOP_FLOWCONTROL_NONE);}
+    | PARSEOP_FLOWCONTROL_SW                {$$ = TrCreateLeafNode (PARSEOP_FLOWCONTROL_SW);}
+    ;
+
+InterruptLevel
+    : PARSEOP_INTLEVEL_ACTIVEBOTH           {$$ = TrCreateLeafNode (PARSEOP_INTLEVEL_ACTIVEBOTH);}
+    | PARSEOP_INTLEVEL_ACTIVEHIGH           {$$ = TrCreateLeafNode (PARSEOP_INTLEVEL_ACTIVEHIGH);}
+    | PARSEOP_INTLEVEL_ACTIVELOW            {$$ = TrCreateLeafNode (PARSEOP_INTLEVEL_ACTIVELOW);}
+    ;
+
+InterruptTypeKeyword
+    : PARSEOP_INTTYPE_EDGE                  {$$ = TrCreateLeafNode (PARSEOP_INTTYPE_EDGE);}
+    | PARSEOP_INTTYPE_LEVEL                 {$$ = TrCreateLeafNode (PARSEOP_INTTYPE_LEVEL);}
+    ;
+
+IODecodeKeyword
+    : PARSEOP_IODECODETYPE_16               {$$ = TrCreateLeafNode (PARSEOP_IODECODETYPE_16);}
+    | PARSEOP_IODECODETYPE_10               {$$ = TrCreateLeafNode (PARSEOP_IODECODETYPE_10);}
+    ;
+
+IoRestrictionKeyword
+    : PARSEOP_IORESTRICT_IN                 {$$ = TrCreateLeafNode (PARSEOP_IORESTRICT_IN);}
+    | PARSEOP_IORESTRICT_OUT                {$$ = TrCreateLeafNode (PARSEOP_IORESTRICT_OUT);}
+    | PARSEOP_IORESTRICT_NONE               {$$ = TrCreateLeafNode (PARSEOP_IORESTRICT_NONE);}
+    | PARSEOP_IORESTRICT_PRESERVE           {$$ = TrCreateLeafNode (PARSEOP_IORESTRICT_PRESERVE);}
+    ;
+
+LockRuleKeyword
+    : PARSEOP_LOCKRULE_LOCK                 {$$ = TrCreateLeafNode (PARSEOP_LOCKRULE_LOCK);}
+    | PARSEOP_LOCKRULE_NOLOCK               {$$ = TrCreateLeafNode (PARSEOP_LOCKRULE_NOLOCK);}
+    ;
+
+MatchOpKeyword
+    : PARSEOP_MATCHTYPE_MTR                 {$$ = TrCreateLeafNode (PARSEOP_MATCHTYPE_MTR);}
+    | PARSEOP_MATCHTYPE_MEQ                 {$$ = TrCreateLeafNode (PARSEOP_MATCHTYPE_MEQ);}
+    | PARSEOP_MATCHTYPE_MLE                 {$$ = TrCreateLeafNode (PARSEOP_MATCHTYPE_MLE);}
+    | PARSEOP_MATCHTYPE_MLT                 {$$ = TrCreateLeafNode (PARSEOP_MATCHTYPE_MLT);}
+    | PARSEOP_MATCHTYPE_MGE                 {$$ = TrCreateLeafNode (PARSEOP_MATCHTYPE_MGE);}
+    | PARSEOP_MATCHTYPE_MGT                 {$$ = TrCreateLeafNode (PARSEOP_MATCHTYPE_MGT);}
+    ;
+
+MaxKeyword
+    : PARSEOP_MAXTYPE_FIXED                 {$$ = TrCreateLeafNode (PARSEOP_MAXTYPE_FIXED);}
+    | PARSEOP_MAXTYPE_NOTFIXED              {$$ = TrCreateLeafNode (PARSEOP_MAXTYPE_NOTFIXED);}
+    ;
+
+MemTypeKeyword
+    : PARSEOP_MEMTYPE_CACHEABLE             {$$ = TrCreateLeafNode (PARSEOP_MEMTYPE_CACHEABLE);}
+    | PARSEOP_MEMTYPE_WRITECOMBINING        {$$ = TrCreateLeafNode (PARSEOP_MEMTYPE_WRITECOMBINING);}
+    | PARSEOP_MEMTYPE_PREFETCHABLE          {$$ = TrCreateLeafNode (PARSEOP_MEMTYPE_PREFETCHABLE);}
+    | PARSEOP_MEMTYPE_NONCACHEABLE          {$$ = TrCreateLeafNode (PARSEOP_MEMTYPE_NONCACHEABLE);}
+    ;
+
+MinKeyword
+    : PARSEOP_MINTYPE_FIXED                 {$$ = TrCreateLeafNode (PARSEOP_MINTYPE_FIXED);}
+    | PARSEOP_MINTYPE_NOTFIXED              {$$ = TrCreateLeafNode (PARSEOP_MINTYPE_NOTFIXED);}
+    ;
+
 ObjectTypeKeyword
     : PARSEOP_OBJECTTYPE_UNK                {$$ = TrCreateLeafNode (PARSEOP_OBJECTTYPE_UNK);}
     | PARSEOP_OBJECTTYPE_INT                {$$ = TrCreateLeafNode (PARSEOP_OBJECTTYPE_INT);}
@@ -2071,36 +2329,31 @@
     | PARSEOP_OBJECTTYPE_DDB                {$$ = TrCreateLeafNode (PARSEOP_OBJECTTYPE_DDB);}
     ;
 
-AccessTypeKeyword
-    : PARSEOP_ACCESSTYPE_ANY                {$$ = TrCreateLeafNode (PARSEOP_ACCESSTYPE_ANY);}
-    | PARSEOP_ACCESSTYPE_BYTE               {$$ = TrCreateLeafNode (PARSEOP_ACCESSTYPE_BYTE);}
-    | PARSEOP_ACCESSTYPE_WORD               {$$ = TrCreateLeafNode (PARSEOP_ACCESSTYPE_WORD);}
-    | PARSEOP_ACCESSTYPE_DWORD              {$$ = TrCreateLeafNode (PARSEOP_ACCESSTYPE_DWORD);}
-    | PARSEOP_ACCESSTYPE_QWORD              {$$ = TrCreateLeafNode (PARSEOP_ACCESSTYPE_QWORD);}
-    | PARSEOP_ACCESSTYPE_BUF                {$$ = TrCreateLeafNode (PARSEOP_ACCESSTYPE_BUF);}
-    ;
-
-AccessAttribKeyword
-    : PARSEOP_ACCESSATTRIB_QUICK            {$$ = TrCreateLeafNode (PARSEOP_ACCESSATTRIB_QUICK );}
-    | PARSEOP_ACCESSATTRIB_SND_RCV          {$$ = TrCreateLeafNode (PARSEOP_ACCESSATTRIB_SND_RCV);}
-    | PARSEOP_ACCESSATTRIB_BYTE             {$$ = TrCreateLeafNode (PARSEOP_ACCESSATTRIB_BYTE);}
-    | PARSEOP_ACCESSATTRIB_WORD             {$$ = TrCreateLeafNode (PARSEOP_ACCESSATTRIB_WORD);}
-    | PARSEOP_ACCESSATTRIB_BLOCK            {$$ = TrCreateLeafNode (PARSEOP_ACCESSATTRIB_BLOCK);}
-    | PARSEOP_ACCESSATTRIB_WORD_CALL        {$$ = TrCreateLeafNode (PARSEOP_ACCESSATTRIB_WORD_CALL);}
-    | PARSEOP_ACCESSATTRIB_BLOCK_CALL       {$$ = TrCreateLeafNode (PARSEOP_ACCESSATTRIB_BLOCK_CALL);}
-    ;
-
-LockRuleKeyword
-    : PARSEOP_LOCKRULE_LOCK                 {$$ = TrCreateLeafNode (PARSEOP_LOCKRULE_LOCK);}
-    | PARSEOP_LOCKRULE_NOLOCK               {$$ = TrCreateLeafNode (PARSEOP_LOCKRULE_NOLOCK);}
-    ;
-
-UpdateRuleKeyword
-    : PARSEOP_UPDATERULE_PRESERVE           {$$ = TrCreateLeafNode (PARSEOP_UPDATERULE_PRESERVE);}
-    | PARSEOP_UPDATERULE_ONES               {$$ = TrCreateLeafNode (PARSEOP_UPDATERULE_ONES);}
-    | PARSEOP_UPDATERULE_ZEROS              {$$ = TrCreateLeafNode (PARSEOP_UPDATERULE_ZEROS);}
-    ;
-
+ParityTypeKeyword
+    : PARSEOP_PARITYTYPE_SPACE              {$$ = TrCreateLeafNode (PARSEOP_PARITYTYPE_SPACE);}
+    | PARSEOP_PARITYTYPE_MARK               {$$ = TrCreateLeafNode (PARSEOP_PARITYTYPE_MARK);}
+    | PARSEOP_PARITYTYPE_ODD                {$$ = TrCreateLeafNode (PARSEOP_PARITYTYPE_ODD);}
+    | PARSEOP_PARITYTYPE_EVEN               {$$ = TrCreateLeafNode (PARSEOP_PARITYTYPE_EVEN);}
+    | PARSEOP_PARITYTYPE_NONE               {$$ = TrCreateLeafNode (PARSEOP_PARITYTYPE_NONE);}
+    ;
+
+PinConfigByte
+    : PinConfigKeyword                      {$$ = $1;}
+    | ByteConstExpr                         {$$ = UtCheckIntegerRange ($1, 0x80, 0xFF);}
+    ;
+
+PinConfigKeyword
+    : PARSEOP_PIN_NOPULL                    {$$ = TrCreateLeafNode (PARSEOP_PIN_NOPULL);}
+    | PARSEOP_PIN_PULLDOWN                  {$$ = TrCreateLeafNode (PARSEOP_PIN_PULLDOWN);}
+    | PARSEOP_PIN_PULLUP                    {$$ = TrCreateLeafNode (PARSEOP_PIN_PULLUP);}
+    | PARSEOP_PIN_PULLDEFAULT               {$$ = TrCreateLeafNode (PARSEOP_PIN_PULLDEFAULT);}
+    ;
+
+RangeTypeKeyword
+    : PARSEOP_RANGETYPE_ISAONLY             {$$ = TrCreateLeafNode (PARSEOP_RANGETYPE_ISAONLY);}
+    | PARSEOP_RANGETYPE_NONISAONLY          {$$ = TrCreateLeafNode (PARSEOP_RANGETYPE_NONISAONLY);}
+    | PARSEOP_RANGETYPE_ENTIRE              {$$ = TrCreateLeafNode (PARSEOP_RANGETYPE_ENTIRE);}
+    ;
 
 RegionSpaceKeyword
     : PARSEOP_REGIONSPACE_IO                {$$ = TrCreateLeafNode (PARSEOP_REGIONSPACE_IO);}
@@ -2111,34 +2364,68 @@
     | PARSEOP_REGIONSPACE_CMOS              {$$ = TrCreateLeafNode (PARSEOP_REGIONSPACE_CMOS);}
     | PARSEOP_REGIONSPACE_PCIBAR            {$$ = TrCreateLeafNode (PARSEOP_REGIONSPACE_PCIBAR);}
     | PARSEOP_REGIONSPACE_IPMI              {$$ = TrCreateLeafNode (PARSEOP_REGIONSPACE_IPMI);}
-    ;
-
-AddressSpaceKeyword
-    : ByteConst								{$$ = UtCheckIntegerRange ($1, 0x80, 0xFF);}
-    | RegionSpaceKeyword					{}
-    | PARSEOP_ADDRESSSPACE_FFIXEDHW         {$$ = TrCreateLeafNode (PARSEOP_ADDRESSSPACE_FFIXEDHW);}
-    ;
-
+    | PARSEOP_REGIONSPACE_GPIO              {$$ = TrCreateLeafNode (PARSEOP_REGIONSPACE_GPIO);}
+    | PARSEOP_REGIONSPACE_GSBUS             {$$ = TrCreateLeafNode (PARSEOP_REGIONSPACE_GSBUS);}
+    | PARSEOP_REGIONSPACE_FFIXEDHW          {$$ = TrCreateLeafNode (PARSEOP_REGIONSPACE_FFIXEDHW);}
+    ;
+
+ResourceTypeKeyword
+    : PARSEOP_RESOURCETYPE_CONSUMER         {$$ = TrCreateLeafNode (PARSEOP_RESOURCETYPE_CONSUMER);}
+    | PARSEOP_RESOURCETYPE_PRODUCER         {$$ = TrCreateLeafNode (PARSEOP_RESOURCETYPE_PRODUCER);}
+    ;
 
 SerializeRuleKeyword
     : PARSEOP_SERIALIZERULE_SERIAL          {$$ = TrCreateLeafNode (PARSEOP_SERIALIZERULE_SERIAL);}
     | PARSEOP_SERIALIZERULE_NOTSERIAL       {$$ = TrCreateLeafNode (PARSEOP_SERIALIZERULE_NOTSERIAL);}
     ;
 
-MatchOpKeyword
-    : PARSEOP_MATCHTYPE_MTR                 {$$ = TrCreateLeafNode (PARSEOP_MATCHTYPE_MTR);}
-    | PARSEOP_MATCHTYPE_MEQ                 {$$ = TrCreateLeafNode (PARSEOP_MATCHTYPE_MEQ);}
-    | PARSEOP_MATCHTYPE_MLE                 {$$ = TrCreateLeafNode (PARSEOP_MATCHTYPE_MLE);}
-    | PARSEOP_MATCHTYPE_MLT                 {$$ = TrCreateLeafNode (PARSEOP_MATCHTYPE_MLT);}
-    | PARSEOP_MATCHTYPE_MGE                 {$$ = TrCreateLeafNode (PARSEOP_MATCHTYPE_MGE);}
-    | PARSEOP_MATCHTYPE_MGT                 {$$ = TrCreateLeafNode (PARSEOP_MATCHTYPE_MGT);}
-    ;
-
-DMATypeKeyword
-    : PARSEOP_DMATYPE_A                     {$$ = TrCreateLeafNode (PARSEOP_DMATYPE_A);}
-    | PARSEOP_DMATYPE_COMPATIBILITY         {$$ = TrCreateLeafNode (PARSEOP_DMATYPE_COMPATIBILITY);}
-    | PARSEOP_DMATYPE_B                     {$$ = TrCreateLeafNode (PARSEOP_DMATYPE_B);}
-    | PARSEOP_DMATYPE_F                     {$$ = TrCreateLeafNode (PARSEOP_DMATYPE_F);}
+ShareTypeKeyword
+    : PARSEOP_SHARETYPE_SHARED              {$$ = TrCreateLeafNode (PARSEOP_SHARETYPE_SHARED);}
+    | PARSEOP_SHARETYPE_EXCLUSIVE           {$$ = TrCreateLeafNode (PARSEOP_SHARETYPE_EXCLUSIVE);}
+    | PARSEOP_SHARETYPE_SHAREDWAKE          {$$ = TrCreateLeafNode (PARSEOP_SHARETYPE_SHAREDWAKE);}
+    | PARSEOP_SHARETYPE_EXCLUSIVEWAKE       {$$ = TrCreateLeafNode (PARSEOP_SHARETYPE_EXCLUSIVEWAKE);}
+   ;
+
+SlaveModeKeyword
+    : PARSEOP_SLAVEMODE_CONTROLLERINIT      {$$ = TrCreateLeafNode (PARSEOP_SLAVEMODE_CONTROLLERINIT);}
+    | PARSEOP_SLAVEMODE_DEVICEINIT          {$$ = TrCreateLeafNode (PARSEOP_SLAVEMODE_DEVICEINIT);}
+    ;
+
+StopBitsKeyword
+    : PARSEOP_STOPBITS_TWO                  {$$ = TrCreateLeafNode (PARSEOP_STOPBITS_TWO);}
+    | PARSEOP_STOPBITS_ONEPLUSHALF          {$$ = TrCreateLeafNode (PARSEOP_STOPBITS_ONEPLUSHALF);}
+    | PARSEOP_STOPBITS_ONE                  {$$ = TrCreateLeafNode (PARSEOP_STOPBITS_ONE);}
+    | PARSEOP_STOPBITS_ZERO                 {$$ = TrCreateLeafNode (PARSEOP_STOPBITS_ZERO);}
+    ;
+
+TranslationKeyword
+    : PARSEOP_TRANSLATIONTYPE_SPARSE        {$$ = TrCreateLeafNode (PARSEOP_TRANSLATIONTYPE_SPARSE);}
+    | PARSEOP_TRANSLATIONTYPE_DENSE         {$$ = TrCreateLeafNode (PARSEOP_TRANSLATIONTYPE_DENSE);}
+    ;
+
+TypeKeyword
+    : PARSEOP_TYPE_TRANSLATION              {$$ = TrCreateLeafNode (PARSEOP_TYPE_TRANSLATION);}
+    | PARSEOP_TYPE_STATIC                   {$$ = TrCreateLeafNode (PARSEOP_TYPE_STATIC);}
+    ;
+
+UpdateRuleKeyword
+    : PARSEOP_UPDATERULE_PRESERVE           {$$ = TrCreateLeafNode (PARSEOP_UPDATERULE_PRESERVE);}
+    | PARSEOP_UPDATERULE_ONES               {$$ = TrCreateLeafNode (PARSEOP_UPDATERULE_ONES);}
+    | PARSEOP_UPDATERULE_ZEROS              {$$ = TrCreateLeafNode (PARSEOP_UPDATERULE_ZEROS);}
+    ;
+
+WireModeKeyword
+    : PARSEOP_WIREMODE_FOUR                 {$$ = TrCreateLeafNode (PARSEOP_WIREMODE_FOUR);}
+    | PARSEOP_WIREMODE_THREE                {$$ = TrCreateLeafNode (PARSEOP_WIREMODE_THREE);}
+    ;
+
+XferSizeKeyword
+    : PARSEOP_XFERSIZE_8                    {$$ = TrCreateValuedLeafNode (PARSEOP_XFERSIZE_8,   0);}
+    | PARSEOP_XFERSIZE_16                   {$$ = TrCreateValuedLeafNode (PARSEOP_XFERSIZE_16,  1);}
+    | PARSEOP_XFERSIZE_32                   {$$ = TrCreateValuedLeafNode (PARSEOP_XFERSIZE_32,  2);}
+    | PARSEOP_XFERSIZE_64                   {$$ = TrCreateValuedLeafNode (PARSEOP_XFERSIZE_64,  3);}
+    | PARSEOP_XFERSIZE_128                  {$$ = TrCreateValuedLeafNode (PARSEOP_XFERSIZE_128, 4);}
+    | PARSEOP_XFERSIZE_256                  {$$ = TrCreateValuedLeafNode (PARSEOP_XFERSIZE_256, 5);}
     ;
 
 XferTypeKeyword
@@ -2147,82 +2434,6 @@
     | PARSEOP_XFERTYPE_16                   {$$ = TrCreateLeafNode (PARSEOP_XFERTYPE_16);}
     ;
 
-ResourceTypeKeyword
-    : PARSEOP_RESOURCETYPE_CONSUMER         {$$ = TrCreateLeafNode (PARSEOP_RESOURCETYPE_CONSUMER);}
-    | PARSEOP_RESOURCETYPE_PRODUCER         {$$ = TrCreateLeafNode (PARSEOP_RESOURCETYPE_PRODUCER);}
-    ;
-
-MinKeyword
-    : PARSEOP_MINTYPE_FIXED                 {$$ = TrCreateLeafNode (PARSEOP_MINTYPE_FIXED);}
-    | PARSEOP_MINTYPE_NOTFIXED              {$$ = TrCreateLeafNode (PARSEOP_MINTYPE_NOTFIXED);}
-    ;
-
-MaxKeyword
-    : PARSEOP_MAXTYPE_FIXED                 {$$ = TrCreateLeafNode (PARSEOP_MAXTYPE_FIXED);}
-    | PARSEOP_MAXTYPE_NOTFIXED              {$$ = TrCreateLeafNode (PARSEOP_MAXTYPE_NOTFIXED);}
-    ;
-
-DecodeKeyword
-    : PARSEOP_DECODETYPE_POS                {$$ = TrCreateLeafNode (PARSEOP_DECODETYPE_POS);}
-    | PARSEOP_DECODETYPE_SUB                {$$ = TrCreateLeafNode (PARSEOP_DECODETYPE_SUB);}
-    ;
-
-RangeTypeKeyword
-    : PARSEOP_RANGETYPE_ISAONLY             {$$ = TrCreateLeafNode (PARSEOP_RANGETYPE_ISAONLY);}
-    | PARSEOP_RANGETYPE_NONISAONLY          {$$ = TrCreateLeafNode (PARSEOP_RANGETYPE_NONISAONLY);}
-    | PARSEOP_RANGETYPE_ENTIRE              {$$ = TrCreateLeafNode (PARSEOP_RANGETYPE_ENTIRE);}
-    ;
-
-MemTypeKeyword
-    : PARSEOP_MEMTYPE_CACHEABLE             {$$ = TrCreateLeafNode (PARSEOP_MEMTYPE_CACHEABLE);}
-    | PARSEOP_MEMTYPE_WRITECOMBINING        {$$ = TrCreateLeafNode (PARSEOP_MEMTYPE_WRITECOMBINING);}
-    | PARSEOP_MEMTYPE_PREFETCHABLE          {$$ = TrCreateLeafNode (PARSEOP_MEMTYPE_PREFETCHABLE);}
-    | PARSEOP_MEMTYPE_NONCACHEABLE          {$$ = TrCreateLeafNode (PARSEOP_MEMTYPE_NONCACHEABLE);}
-    ;
-
-OptionalReadWriteKeyword
-    :                                       {$$ = TrCreateLeafNode (PARSEOP_READWRITETYPE_BOTH);}
-    | PARSEOP_READWRITETYPE_BOTH            {$$ = TrCreateLeafNode (PARSEOP_READWRITETYPE_BOTH);}
-    | PARSEOP_READWRITETYPE_READONLY        {$$ = TrCreateLeafNode (PARSEOP_READWRITETYPE_READONLY);}
-    ;
-
-InterruptTypeKeyword
-    : PARSEOP_INTTYPE_EDGE                  {$$ = TrCreateLeafNode (PARSEOP_INTTYPE_EDGE);}
-    | PARSEOP_INTTYPE_LEVEL                 {$$ = TrCreateLeafNode (PARSEOP_INTTYPE_LEVEL);}
-    ;
-
-InterruptLevel
-    : PARSEOP_INTLEVEL_ACTIVEHIGH           {$$ = TrCreateLeafNode (PARSEOP_INTLEVEL_ACTIVEHIGH);}
-    | PARSEOP_INTLEVEL_ACTIVELOW            {$$ = TrCreateLeafNode (PARSEOP_INTLEVEL_ACTIVELOW);}
-    ;
-
-ShareTypeKeyword
-    : PARSEOP_SHARETYPE_SHARED              {$$ = TrCreateLeafNode (PARSEOP_SHARETYPE_SHARED);}
-    | PARSEOP_SHARETYPE_EXCLUSIVE           {$$ = TrCreateLeafNode (PARSEOP_SHARETYPE_EXCLUSIVE);}
-    ;
-
-IODecodeKeyword
-    : PARSEOP_IODECODETYPE_16               {$$ = TrCreateLeafNode (PARSEOP_IODECODETYPE_16);}
-    | PARSEOP_IODECODETYPE_10               {$$ = TrCreateLeafNode (PARSEOP_IODECODETYPE_10);}
-    ;
-
-TypeKeyword
-    : PARSEOP_TYPE_TRANSLATION              {$$ = TrCreateLeafNode (PARSEOP_TYPE_TRANSLATION);}
-    | PARSEOP_TYPE_STATIC                   {$$ = TrCreateLeafNode (PARSEOP_TYPE_STATIC);}
-    ;
-
-TranslationKeyword
-    : PARSEOP_TRANSLATIONTYPE_SPARSE        {$$ = TrCreateLeafNode (PARSEOP_TRANSLATIONTYPE_SPARSE);}
-    | PARSEOP_TRANSLATIONTYPE_DENSE         {$$ = TrCreateLeafNode (PARSEOP_TRANSLATIONTYPE_DENSE);}
-    ;
-
-AddressKeyword
-    : PARSEOP_ADDRESSTYPE_MEMORY            {$$ = TrCreateLeafNode (PARSEOP_ADDRESSTYPE_MEMORY);}
-    | PARSEOP_ADDRESSTYPE_RESERVED          {$$ = TrCreateLeafNode (PARSEOP_ADDRESSTYPE_RESERVED);}
-    | PARSEOP_ADDRESSTYPE_NVS               {$$ = TrCreateLeafNode (PARSEOP_ADDRESSTYPE_NVS);}
-    | PARSEOP_ADDRESSTYPE_ACPI              {$$ = TrCreateLeafNode (PARSEOP_ADDRESSTYPE_ACPI);}
-    ;
-
 
 /******* Miscellaneous Types **************************************************/
 
@@ -2291,34 +2502,6 @@
     | PARSEOP_REVISION              {$$ = TrCreateLeafNode (PARSEOP_REVISION);}
     ;
 
-ByteConstExpr
-    : Type3Opcode                   {$$ = TrUpdateNode (PARSEOP_BYTECONST, $1);}
-    | Type2IntegerOpcode            {$$ = TrUpdateNode (PARSEOP_BYTECONST, $1);}
-    | ConstExprTerm                 {$$ = TrUpdateNode (PARSEOP_BYTECONST, $1);}
-    | ByteConst                     {}
-    ;
-
-WordConstExpr
-    : Type3Opcode                   {$$ = TrUpdateNode (PARSEOP_WORDCONST, $1);}
-    | Type2IntegerOpcode            {$$ = TrUpdateNode (PARSEOP_WORDCONST, $1);}
-    | ConstExprTerm                 {$$ = TrUpdateNode (PARSEOP_WORDCONST, $1);}
-    | WordConst                     {}
-    ;
-
-DWordConstExpr
-    : Type3Opcode                   {$$ = TrUpdateNode (PARSEOP_DWORDCONST, $1);}
-    | Type2IntegerOpcode            {$$ = TrUpdateNode (PARSEOP_DWORDCONST, $1);}
-    | ConstExprTerm                 {$$ = TrUpdateNode (PARSEOP_DWORDCONST, $1);}
-    | DWordConst                    {}
-    ;
-
-QWordConstExpr
-    : Type3Opcode                   {$$ = TrUpdateNode (PARSEOP_QWORDCONST, $1);}
-    | Type2IntegerOpcode            {$$ = TrUpdateNode (PARSEOP_QWORDCONST, $1);}
-    | ConstExprTerm                 {$$ = TrUpdateNode (PARSEOP_QWORDCONST, $1);}
-    | QWordConst                    {}
-    ;
-
 ConstExprTerm
     : PARSEOP_ZERO                  {$$ = TrCreateValuedLeafNode (PARSEOP_ZERO, 0);}
     | PARSEOP_ONE                   {$$ = TrCreateValuedLeafNode (PARSEOP_ONE, 1);}
@@ -2326,6 +2509,35 @@
     | PARSEOP___DATE__              {$$ = TrCreateConstantLeafNode (PARSEOP___DATE__);}
     | PARSEOP___FILE__              {$$ = TrCreateConstantLeafNode (PARSEOP___FILE__);}
     | PARSEOP___LINE__              {$$ = TrCreateConstantLeafNode (PARSEOP___LINE__);}
+    | PARSEOP___PATH__              {$$ = TrCreateConstantLeafNode (PARSEOP___PATH__);}
+    ;
+
+ByteConstExpr
+    : Type3Opcode                   {$$ = TrUpdateNode (PARSEOP_BYTECONST, $1);}
+    | Type2IntegerOpcode            {$$ = TrUpdateNode (PARSEOP_BYTECONST, $1);}
+    | ConstExprTerm                 {$$ = TrUpdateNode (PARSEOP_BYTECONST, $1);}
+    | ByteConst                     {}
+    ;
+
+WordConstExpr
+    : Type3Opcode                   {$$ = TrUpdateNode (PARSEOP_WORDCONST, $1);}
+    | Type2IntegerOpcode            {$$ = TrUpdateNode (PARSEOP_WORDCONST, $1);}
+    | ConstExprTerm                 {$$ = TrUpdateNode (PARSEOP_WORDCONST, $1);}
+    | WordConst                     {}
+    ;
+
+DWordConstExpr
+    : Type3Opcode                   {$$ = TrUpdateNode (PARSEOP_DWORDCONST, $1);}
+    | Type2IntegerOpcode            {$$ = TrUpdateNode (PARSEOP_DWORDCONST, $1);}
+    | ConstExprTerm                 {$$ = TrUpdateNode (PARSEOP_DWORDCONST, $1);}
+    | DWordConst                    {}
+    ;
+
+QWordConstExpr
+    : Type3Opcode                   {$$ = TrUpdateNode (PARSEOP_QWORDCONST, $1);}
+    | Type2IntegerOpcode            {$$ = TrUpdateNode (PARSEOP_QWORDCONST, $1);}
+    | ConstExprTerm                 {$$ = TrUpdateNode (PARSEOP_QWORDCONST, $1);}
+    | QWordConst                    {}
     ;
 
 /* OptionalCount must appear before ByteList or an incorrect reduction will result */
@@ -2336,7 +2548,6 @@
     | ',' TermArg                   {$$ = $2;}
     ;
 
-
 BufferTerm
     : PARSEOP_BUFFER '('            {$<n>$ = TrCreateLeafNode (PARSEOP_BUFFER);}
         OptionalTermArg
@@ -2359,6 +2570,15 @@
         ByteConstExpr               {$$ = TrLinkPeerNode ($1,$3);}
     ;
 
+DataBufferTerm
+    : PARSEOP_DATABUFFER  '('       {$<n>$ = TrCreateLeafNode (PARSEOP_DATABUFFER);}
+        OptionalWordConst
+        ')' '{'
+            ByteList '}'            {$$ = TrLinkChildren ($<n>3,2,$4,$7);}
+    | PARSEOP_DATABUFFER '('
+        error ')'                   {$$ = AslDoError(); yyclearin;}
+    ;
+
 DWordList
     :                               {$$ = NULL;}
     | DWordConstExpr
@@ -2376,11 +2596,6 @@
         error ')'                   {$$ = AslDoError(); yyclearin;}
     ;
 
-VarPackageLengthTerm
-    :                               {$$ = TrCreateLeafNode (PARSEOP_DEFAULT_ARG);}
-    | TermArg                       {$$ = $1;}
-    ;
-
 PackageList
     :                               {$$ = NULL;}
     | PackageElement
@@ -2394,6 +2609,15 @@
     | NameString                    {}
     ;
 
+VarPackageLengthTerm
+    :                               {$$ = TrCreateLeafNode (PARSEOP_DEFAULT_ARG);}
+    | TermArg                       {$$ = $1;}
+    ;
+
+
+/******* Macros ***********************************************/
+
+
 EISAIDTerm
     : PARSEOP_EISAID '('
         StringData ')'              {$$ = TrUpdateNode (PARSEOP_EISAID, $3);}
@@ -2401,6 +2625,14 @@
         error ')'                   {$$ = AslDoError(); yyclearin;}
     ;
 
+UnicodeTerm
+    : PARSEOP_UNICODE '('           {$<n>$ = TrCreateLeafNode (PARSEOP_UNICODE);}
+        StringData
+        ')'                         {$$ = TrLinkChildren ($<n>3,2,0,$4);}
+    | PARSEOP_UNICODE '('
+        error ')'                   {$$ = AslDoError(); yyclearin;}
+    ;
+
 
 /******* Resources and Memory ***********************************************/
 
@@ -2419,14 +2651,6 @@
                                           TrCreateLeafNode (PARSEOP_ENDTAG));}
     ;
 
-UnicodeTerm
-    : PARSEOP_UNICODE '('           {$<n>$ = TrCreateLeafNode (PARSEOP_UNICODE);}
-        StringData
-        ')'                         {$$ = TrLinkChildren ($<n>3,2,0,$4);}
-    | PARSEOP_UNICODE '('
-        error ')'                   {$$ = AslDoError(); yyclearin;}
-    ;
-
 ResourceMacroList
     :                               {$$ = NULL;}
     | ResourceMacroList
@@ -2442,7 +2666,11 @@
     | ExtendedIOTerm                {}
     | ExtendedMemoryTerm            {}
     | ExtendedSpaceTerm             {}
+    | FixedDmaTerm                  {}
     | FixedIOTerm                   {}
+    | GpioIntTerm                   {}
+    | GpioIoTerm                    {}
+    | I2cSerialBusTerm              {}
     | InterruptTerm                 {}
     | IOTerm                        {}
     | IRQNoFlagsTerm                {}
@@ -2454,8 +2682,10 @@
     | QWordMemoryTerm               {}
     | QWordSpaceTerm                {}
     | RegisterTerm                  {}
+    | SpiSerialBusTerm              {}
+    | StartDependentFnNoPriTerm     {}
     | StartDependentFnTerm          {}
-    | StartDependentFnNoPriTerm     {}
+    | UartSerialBusTerm             {}
     | VendorLongTerm                {}
     | VendorShortTerm               {}
     | WordBusNumberTerm             {}
@@ -2612,6 +2842,17 @@
         error ')'                   {$$ = AslDoError(); yyclearin;}
     ;
 
+FixedDmaTerm
+    : PARSEOP_FIXEDDMA '('          {$<n>$ = TrCreateLeafNode (PARSEOP_FIXEDDMA);}
+        WordConstExpr               // 04: DMA RequestLines
+        ',' WordConstExpr           // 06: DMA Channels
+        OptionalXferSize            // 07: DMA TransferSize
+        OptionalNameString          // 08: DescriptorName
+        ')'                         {$$ = TrLinkChildren ($<n>3,4,$4,$6,$7,$8);}
+    | PARSEOP_FIXEDDMA '('
+        error ')'                   {$$ = AslDoError(); yyclearin;}
+    ;
+
 FixedIOTerm
     : PARSEOP_FIXEDIO '('           {$<n>$ = TrCreateLeafNode (PARSEOP_FIXEDIO);}
         WordConstExpr
@@ -2622,6 +2863,58 @@
         error ')'                   {$$ = AslDoError(); yyclearin;}
     ;
 
+GpioIntTerm
+    : PARSEOP_GPIO_INT '('          {$<n>$ = TrCreateLeafNode (PARSEOP_GPIO_INT);}
+        InterruptTypeKeyword        // 04: InterruptType
+        ',' InterruptLevel          // 06: InterruptLevel
+        OptionalShareType           // 07: SharedType
+        ',' PinConfigByte           // 09: PinConfig
+        OptionalWordConstExpr       // 10: DebounceTimeout
+        ',' StringData              // 12: ResourceSource
+        OptionalByteConstExpr       // 13: ResourceSourceIndex
+        OptionalResourceType        // 14: ResourceType
+        OptionalNameString          // 15: DescriptorName
+        OptionalBuffer_Last         // 16: VendorData
+        ')' '{'
+            DWordConstExpr '}'      {$$ = TrLinkChildren ($<n>3,11,$4,$6,$7,$9,$10,$12,$13,$14,$15,$16,$19);}
+    | PARSEOP_GPIO_INT '('
+        error ')'                   {$$ = AslDoError(); yyclearin;}
+    ;
+
+GpioIoTerm
+    : PARSEOP_GPIO_IO '('           {$<n>$ = TrCreateLeafNode (PARSEOP_GPIO_IO);}
+        OptionalShareType_First     // 04: SharedType
+        ',' PinConfigByte           // 06: PinConfig
+        OptionalWordConstExpr       // 07: DebounceTimeout
+        OptionalWordConstExpr       // 08: DriveStrength
+        OptionalIoRestriction       // 09: IoRestriction
+        ',' StringData              // 11: ResourceSource
+        OptionalByteConstExpr       // 12: ResourceSourceIndex
+        OptionalResourceType        // 13: ResourceType
+        OptionalNameString          // 14: DescriptorName
+        OptionalBuffer_Last         // 15: VendorData
+        ')' '{'
+            DWordList '}'           {$$ = TrLinkChildren ($<n>3,11,$4,$6,$7,$8,$9,$11,$12,$13,$14,$15,$18);}
+    | PARSEOP_GPIO_IO '('
+        error ')'                   {$$ = AslDoError(); yyclearin;}
+    ;
+
+I2cSerialBusTerm
+    : PARSEOP_I2C_SERIALBUS '('     {$<n>$ = TrCreateLeafNode (PARSEOP_I2C_SERIALBUS);}
+        WordConstExpr               // 04: SlaveAddress
+        OptionalSlaveMode           // 05: SlaveMode
+        ',' DWordConstExpr          // 07: ConnectionSpeed
+        OptionalAddressingMode      // 08: AddressingMode
+        ',' StringData              // 10: ResourceSource
+        OptionalByteConstExpr       // 11: ResourceSourceIndex
+        OptionalResourceType        // 12: ResourceType
+        OptionalNameString          // 13: DescriptorName
+        OptionalBuffer_Last         // 14: VendorData
+        ')'                         {$$ = TrLinkChildren ($<n>3,9,$4,$5,$7,$8,$10,$11,$12,$13,$14);}
+    | PARSEOP_I2C_SERIALBUS '('
+        error ')'                   {$$ = AslDoError(); yyclearin;}
+    ;
+
 InterruptTerm
     : PARSEOP_INTERRUPT '('         {$<n>$ = TrCreateLeafNode (PARSEOP_INTERRUPT);}
         OptionalResourceType_First
@@ -2787,6 +3080,34 @@
         error ')'                   {$$ = AslDoError(); yyclearin;}
     ;
 
+SpiSerialBusTerm
+    : PARSEOP_SPI_SERIALBUS '('     {$<n>$ = TrCreateLeafNode (PARSEOP_SPI_SERIALBUS);}
+        WordConstExpr               // 04: DeviceSelection
+        OptionalDevicePolarity      // 05: DevicePolarity
+        OptionalWireMode            // 06: WireMode
+        ',' ByteConstExpr           // 08: DataBitLength
+        OptionalSlaveMode           // 09: SlaveMode
+        ',' DWordConstExpr          // 11: ConnectionSpeed
+        ',' ClockPolarityKeyword    // 13: ClockPolarity
+        ',' ClockPhaseKeyword       // 15: ClockPhase
+        ',' StringData              // 17: ResourceSource
+        OptionalByteConstExpr       // 18: ResourceSourceIndex
+        OptionalResourceType        // 19: ResourceType
+        OptionalNameString          // 20: DescriptorName
+        OptionalBuffer_Last         // 21: VendorData
+        ')'                         {$$ = TrLinkChildren ($<n>3,13,$4,$5,$6,$8,$9,$11,$13,$15,$17,$18,$19,$20,$21);}
+    | PARSEOP_SPI_SERIALBUS '('
+        error ')'                   {$$ = AslDoError(); yyclearin;}
+    ;
+
+StartDependentFnNoPriTerm
+    : PARSEOP_STARTDEPENDENTFN_NOPRI '('    {$<n>$ = TrCreateLeafNode (PARSEOP_STARTDEPENDENTFN_NOPRI);}
+        ')' '{'
+        ResourceMacroList '}'       {$$ = TrLinkChildren ($<n>3,1,$6);}
+    | PARSEOP_STARTDEPENDENTFN_NOPRI '('
+        error ')'                   {$$ = AslDoError(); yyclearin;}
+    ;
+
 StartDependentFnTerm
     : PARSEOP_STARTDEPENDENTFN '('  {$<n>$ = TrCreateLeafNode (PARSEOP_STARTDEPENDENTFN);}
         ByteConstExpr
@@ -2797,11 +3118,24 @@
         error ')'                   {$$ = AslDoError(); yyclearin;}
     ;
 
-StartDependentFnNoPriTerm
-    : PARSEOP_STARTDEPENDENTFN_NOPRI '('    {$<n>$ = TrCreateLeafNode (PARSEOP_STARTDEPENDENTFN_NOPRI);}
-        ')' '{'
-        ResourceMacroList '}'       {$$ = TrLinkChildren ($<n>3,1,$6);}
-    | PARSEOP_STARTDEPENDENTFN_NOPRI '('
+UartSerialBusTerm
+    : PARSEOP_UART_SERIALBUS '('    {$<n>$ = TrCreateLeafNode (PARSEOP_UART_SERIALBUS);}
+        DWordConstExpr              // 04: ConnectionSpeed
+        OptionalBitsPerByte         // 05: BitsPerByte
+        OptionalStopBits            // 06: StopBits
+        ',' ByteConstExpr           // 08: LinesInUse
+        OptionalEndian              // 09: Endianess
+        OptionalParityType          // 10: Parity
+        OptionalFlowControl         // 11: FlowControl
+        ',' WordConstExpr           // 13: Rx BufferSize
+        ',' WordConstExpr           // 15: Tx BufferSize
+        ',' StringData              // 17: ResourceSource
+        OptionalByteConstExpr       // 18: ResourceSourceIndex
+        OptionalResourceType        // 19: ResourceType
+        OptionalNameString          // 20: DescriptorName
+        OptionalBuffer_Last         // 21: VendorData
+        ')'                         {$$ = TrLinkChildren ($<n>3,14,$4,$5,$6,$8,$9,$10,$11,$13,$15,$17,$18,$19,$20,$21);}
+    | PARSEOP_UART_SERIALBUS '('
         error ')'                   {$$ = AslDoError(); yyclearin;}
     ;
 
@@ -2910,6 +3244,16 @@
     : Integer                       {$$ = TrUpdateNode (PARSEOP_PACKAGE_LENGTH,(ACPI_PARSE_OBJECT *) $1);}
     ;
 
+NameStringItem
+    : ',' NameString                {$$ = $2;}
+    | ',' error                     {$$ = AslDoError (); yyclearin;}
+    ;
+
+TermArgItem
+    : ',' TermArg                   {$$ = $2;}
+    | ',' error                     {$$ = AslDoError (); yyclearin;}
+    ;
+
 OptionalBusMasterKeyword
     : ','                                       {$$ = TrCreateLeafNode (PARSEOP_BUSMASTERTYPE_MASTER);}
     | ',' PARSEOP_BUSMASTERTYPE_MASTER          {$$ = TrCreateLeafNode (PARSEOP_BUSMASTERTYPE_MASTER);}
@@ -2929,12 +3273,28 @@
     | ',' ByteConstExpr             {$$ = $2;}
     ;
 
+OptionalAddressingMode
+    : ','                           {$$ = NULL;}
+    | ',' AddressingModeKeyword     {$$ = $2;}
+    ;
+
 OptionalAddressRange
     :                               {$$ = NULL;}
     | ','                           {$$ = NULL;}
     | ',' AddressKeyword            {$$ = $2;}
     ;
 
+OptionalBitsPerByte
+    : ','                           {$$ = NULL;}
+    | ',' BitsPerByteKeyword        {$$ = $2;}
+    ;
+
+OptionalBuffer_Last
+    :                               {$$ = NULL;}
+    | ','                           {$$ = NULL;}
+    | ',' DataBufferTerm            {$$ = $2;}
+    ;
+
 OptionalByteConstExpr
     :                               {$$ = NULL;}
     | ','                           {$$ = NULL;}
@@ -2946,12 +3306,32 @@
     | ',' DecodeKeyword             {$$ = $2;}
     ;
 
+OptionalDevicePolarity
+    : ','                           {$$ = NULL;}
+    | ',' DevicePolarityKeyword     {$$ = $2;}
+    ;
+
 OptionalDWordConstExpr
     :                               {$$ = NULL;}
     | ','                           {$$ = NULL;}
     | ',' DWordConstExpr            {$$ = $2;}
     ;
 
+OptionalEndian
+    : ','                           {$$ = NULL;}
+    | ',' EndianKeyword             {$$ = $2;}
+    ;
+
+OptionalFlowControl
+    : ','                           {$$ = NULL;}
+    | ',' FlowControlKeyword        {$$ = $2;}
+    ;
+
+OptionalIoRestriction
+    : ','                           {$$ = NULL;}
+    | ',' IoRestrictionKeyword      {$$ = $2;}
+    ;
+
 OptionalListString
     :                               {$$ = TrCreateValuedLeafNode (PARSEOP_STRING_LITERAL, ACPI_TO_INTEGER (""));}   /* Placeholder is a NULL string */
     | ','                           {$$ = TrCreateValuedLeafNode (PARSEOP_STRING_LITERAL, ACPI_TO_INTEGER (""));}   /* Placeholder is a NULL string */
@@ -2995,6 +3375,11 @@
     | ',' ObjectTypeKeyword         {$$ = $2;}
     ;
 
+OptionalParityType
+    : ','                           {$$ = NULL;}
+    | ',' ParityTypeKeyword         {$$ = $2;}
+    ;
+
 OptionalQWordConstExpr
     :                               {$$ = NULL;}
     | ','                           {$$ = NULL;}
@@ -3006,6 +3391,12 @@
     | ',' RangeTypeKeyword          {$$ = $2;}
     ;
 
+OptionalReadWriteKeyword
+    :                                   {$$ = TrCreateLeafNode (PARSEOP_READWRITETYPE_BOTH);}
+    | PARSEOP_READWRITETYPE_BOTH        {$$ = TrCreateLeafNode (PARSEOP_READWRITETYPE_BOTH);}
+    | PARSEOP_READWRITETYPE_READONLY    {$$ = TrCreateLeafNode (PARSEOP_READWRITETYPE_READONLY);}
+    ;
+
 OptionalReference
     :                               {$$ = TrCreateLeafNode (PARSEOP_ZERO);}       /* Placeholder is a ZeroOp object */
     | ','                           {$$ = TrCreateLeafNode (PARSEOP_ZERO);}       /* Placeholder is a ZeroOp object */
@@ -3013,27 +3404,48 @@
     ;
 
 OptionalResourceType_First
-    :                               {$$ = NULL;}
+    :                               {$$ = TrCreateLeafNode (PARSEOP_RESOURCETYPE_CONSUMER);}
     | ResourceTypeKeyword           {$$ = $1;}
     ;
 
 OptionalResourceType
-    : ','                           {$$ = NULL;}
+    :                               {$$ = TrCreateLeafNode (PARSEOP_RESOURCETYPE_CONSUMER);}
+    | ','                           {$$ = TrCreateLeafNode (PARSEOP_RESOURCETYPE_CONSUMER);}
     | ',' ResourceTypeKeyword       {$$ = $2;}
     ;
 
+OptionalReturnArg
+    :                               {$$ = TrSetNodeFlags (TrCreateLeafNode (PARSEOP_ZERO), NODE_IS_NULL_RETURN);}       /* Placeholder is a ZeroOp object */
+    | TermArg                       {$$ = $1;}
+    ;
+
 OptionalSerializeRuleKeyword
     :                               {$$ = NULL;}
     | ','                           {$$ = NULL;}
     | ',' SerializeRuleKeyword      {$$ = $2;}
     ;
 
+OptionalSlaveMode
+    : ','                           {$$ = NULL;}
+    | ',' SlaveModeKeyword          {$$ = $2;}
+    ;
+
 OptionalShareType
     :                               {$$ = NULL;}
     | ','                           {$$ = NULL;}
     | ',' ShareTypeKeyword          {$$ = $2;}
     ;
 
+OptionalShareType_First
+    :                               {$$ = NULL;}
+    | ShareTypeKeyword              {$$ = $1;}
+    ;
+
+OptionalStopBits
+    : ','                           {$$ = NULL;}
+    | ',' StopBitsKeyword           {$$ = $2;}
+    ;
+
 OptionalStringData
     :                               {$$ = NULL;}
     | ','                           {$$ = NULL;}
@@ -3045,11 +3457,6 @@
     | TermArg                       {$$ = $1;}
     ;
 
-OptionalReturnArg
-    :                               {$$ = TrSetNodeFlags (TrCreateLeafNode (PARSEOP_ZERO), NODE_IS_NULL_RETURN);}       /* Placeholder is a ZeroOp object */
-    | TermArg                       {$$ = $1;}
-    ;
-
 OptionalType
     :                               {$$ = NULL;}
     | ','                           {$$ = NULL;}
@@ -3068,23 +3475,33 @@
     | ',' TranslationKeyword        {$$ = $2;}
     ;
 
-
-TermArgItem
-    : ',' TermArg                   {$$ = $2;}
-    | ',' error                     {$$ = AslDoError (); yyclearin;}
-    ;
-
-NameStringItem
-    : ',' NameString                {$$ = $2;}
-    | ',' error                     {$$ = AslDoError (); yyclearin;}
+OptionalWireMode
+    : ','                           {$$ = NULL;}
+    | ',' WireModeKeyword           {$$ = $2;}
+    ;
+
+OptionalWordConst
+    :                               {$$ = NULL;}
+    | WordConst                     {$$ = $1;}
+    ;
+
+OptionalWordConstExpr
+    : ','                           {$$ = NULL;}
+    | ',' WordConstExpr             {$$ = $2;}
+    ;
+
+OptionalXferSize
+    :                               {$$ = TrCreateValuedLeafNode (PARSEOP_XFERSIZE_32, 2);}
+    | ','                           {$$ = TrCreateValuedLeafNode (PARSEOP_XFERSIZE_32, 2);}
+    | ',' XferSizeKeyword           {$$ = $2;}
     ;
 
 %%
-
-
-/*
+/******************************************************************************
+ *
  * Local support functions
- */
+ *
+ *****************************************************************************/
 
 int
 AslCompilerwrap(void)
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/compiler/asldefine.h
--- a/head/sys/contrib/dev/acpica/compiler/asldefine.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/compiler/asldefine.h	Tue Dec 06 20:26:16 2011 +0200
@@ -56,7 +56,7 @@
 #define ASL_INVOCATION_NAME         "iasl"
 #define ASL_CREATOR_ID              "INTL"
 
-#define ASL_COMPLIANCE              "Supports ACPI Specification Revision 4.0a"
+#define ASL_COMPLIANCE              "Supports ACPI Specification Revision 5.0"
 
 
 /* Configuration constants */
@@ -153,5 +153,25 @@
 #define POSITIVE                    0
 
 
+/* Helper macros for resource tag creation */
+
+#define RsCreateMultiBitField \
+    RsCreateResourceField
+
+#define RsCreateBitField(Op, Name, ByteOffset, BitOffset) \
+    RsCreateResourceField (Op, Name, ByteOffset, BitOffset, 1)
+
+#define RsCreateByteField(Op, Name, ByteOffset) \
+    RsCreateResourceField (Op, Name, ByteOffset, 0, 8);
+
+#define RsCreateWordField(Op, Name, ByteOffset) \
+    RsCreateResourceField (Op, Name, ByteOffset, 0, 16);
+
+#define RsCreateDwordField(Op, Name, ByteOffset) \
+    RsCreateResourceField (Op, Name, ByteOffset, 0, 32);
+
+#define RsCreateQwordField(Op, Name, ByteOffset) \
+    RsCreateResourceField (Op, Name, ByteOffset, 0, 64);
+
 #endif /* ASLDEFINE.H */
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/compiler/aslerror.c
--- a/head/sys/contrib/dev/acpica/compiler/aslerror.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/compiler/aslerror.c	Tue Dec 06 20:26:16 2011 +0200
@@ -319,10 +319,23 @@
 
         if (Enode->LineNumber)
         {
+            /* Main message: try to use string from AslMessages first */
+
+            if (!MainMessage)
+            {
+                MainMessage = "";
+            }
+
             MsgLength = strlen (MainMessage);
             if (MsgLength == 0)
             {
+                /* Use the secondary/extra message as main message */
+
                 MainMessage = Enode->Message;
+                if (!MainMessage)
+                {
+                    MainMessage = "";
+                }
 
                 MsgLength = strlen (MainMessage);
                 ExtraMessage = NULL;
@@ -620,13 +633,13 @@
 
 int
 AslCompilererror (
-    char                    *CompilerMessage)
+    const char              *CompilerMessage)
 {
 
     AslCommonError (ASL_ERROR, ASL_MSG_SYNTAX, Gbl_CurrentLineNumber,
-                    Gbl_LogicalLineNumber, Gbl_CurrentLineOffset,
-                    Gbl_CurrentColumn, Gbl_Files[ASL_FILE_INPUT].Filename,
-                    CompilerMessage);
+        Gbl_LogicalLineNumber, Gbl_CurrentLineOffset,
+        Gbl_CurrentColumn, Gbl_Files[ASL_FILE_INPUT].Filename,
+        ACPI_CAST_PTR (char, CompilerMessage));
 
     return 0;
 }
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/compiler/aslfiles.c
--- a/head/sys/contrib/dev/acpica/compiler/aslfiles.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/compiler/aslfiles.c	Tue Dec 06 20:26:16 2011 +0200
@@ -174,14 +174,18 @@
 {
     FILE                    *fp;
     UINT32                  FileSize;
+    long                    Offset;
 
 
     fp = Gbl_Files[FileId].Handle;
+    Offset = ftell (fp);
 
     fseek (fp, 0, SEEK_END);
     FileSize = (UINT32) ftell (fp);
-    fseek (fp, 0, SEEK_SET);
 
+    /* Restore file pointer */
+
+    fseek (fp, Offset, SEEK_SET);
     return (FileSize);
 }
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/compiler/aslglobal.h
--- a/head/sys/contrib/dev/acpica/compiler/aslglobal.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/compiler/aslglobal.h	Tue Dec 06 20:26:16 2011 +0200
@@ -128,6 +128,7 @@
 ASL_EXTERN BOOLEAN                  ASL_INIT_GLOBAL (Gbl_UseOriginalCompilerId, FALSE);
 ASL_EXTERN BOOLEAN                  ASL_INIT_GLOBAL (Gbl_VerboseTemplates, FALSE);
 ASL_EXTERN BOOLEAN                  ASL_INIT_GLOBAL (Gbl_DoTemplates, FALSE);
+ASL_EXTERN BOOLEAN                  ASL_INIT_GLOBAL (Gbl_CompileGeneric, FALSE);
 
 
 #define HEX_OUTPUT_NONE         0
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/compiler/asllisting.c
--- a/head/sys/contrib/dev/acpica/compiler/asllisting.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/compiler/asllisting.c	Tue Dec 06 20:26:16 2011 +0200
@@ -850,9 +850,9 @@
 
         FlPrintFile (FileId, "\n\nSummary of errors and warnings\n\n");
         AePrintErrorLog (FileId);
-        FlPrintFile (FileId, "\n\n");
+        FlPrintFile (FileId, "\n");
         UtDisplaySummary (FileId);
-        FlPrintFile (FileId, "\n\n");
+        FlPrintFile (FileId, "\n");
     }
 }
 
@@ -1309,6 +1309,7 @@
     /* Get AML size, seek back to start */
 
     AmlFileSize = FlGetFileSize (ASL_FILE_AML_OUTPUT);
+    FlSeekFile (ASL_FILE_AML_OUTPUT, 0);
 
     FlPrintFile (ASL_FILE_HEX_OUTPUT, " * C source code output\n");
     FlPrintFile (ASL_FILE_HEX_OUTPUT, " * AML code block contains 0x%X bytes\n *\n */\n",
@@ -1365,7 +1366,6 @@
     }
 
     FlPrintFile (ASL_FILE_HEX_OUTPUT, "};\n");
-    FlCloseFile (ASL_FILE_HEX_OUTPUT);
 }
 
 
@@ -1397,6 +1397,7 @@
     /* Get AML size, seek back to start */
 
     AmlFileSize = FlGetFileSize (ASL_FILE_AML_OUTPUT);
+    FlSeekFile (ASL_FILE_AML_OUTPUT, 0);
 
     FlPrintFile (ASL_FILE_HEX_OUTPUT, " * ASL source code output\n");
     FlPrintFile (ASL_FILE_HEX_OUTPUT, " * AML code block contains 0x%X bytes\n *\n */\n",
@@ -1453,7 +1454,6 @@
     }
 
     FlPrintFile (ASL_FILE_HEX_OUTPUT, "    })\n");
-    FlCloseFile (ASL_FILE_HEX_OUTPUT);
 }
 
 
@@ -1485,6 +1485,7 @@
     /* Get AML size, seek back to start */
 
     AmlFileSize = FlGetFileSize (ASL_FILE_AML_OUTPUT);
+    FlSeekFile (ASL_FILE_AML_OUTPUT, 0);
 
     FlPrintFile (ASL_FILE_HEX_OUTPUT, "; Assembly code source output\n");
     FlPrintFile (ASL_FILE_HEX_OUTPUT, "; AML code block contains 0x%X bytes\n;\n",
@@ -1536,7 +1537,6 @@
     }
 
     FlPrintFile (ASL_FILE_HEX_OUTPUT, "\n");
-    FlCloseFile (ASL_FILE_HEX_OUTPUT);
 }
 
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/compiler/aslload.c
--- a/head/sys/contrib/dev/acpica/compiler/aslload.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/compiler/aslload.c	Tue Dec 06 20:26:16 2011 +0200
@@ -189,7 +189,7 @@
         {
         case AML_INT_RESERVEDFIELD_OP:
         case AML_INT_ACCESSFIELD_OP:
-
+        case AML_INT_CONNECTION_OP:
             break;
 
         default:
@@ -224,8 +224,10 @@
             }
             break;
         }
+
         Child = Child->Asl.Next;
     }
+
     return (AE_OK);
 }
 
@@ -290,7 +292,6 @@
     InitializerOp = ASL_GET_CHILD_NODE (Op);
     while (InitializerOp)
     {
-
         if (InitializerOp->Asl.ExternalName)
         {
             Status = AcpiNsLookup (WalkState->ScopeInfo,
@@ -305,20 +306,15 @@
             }
 
             /*
-             * Store the field offset in the namespace node so it
-             * can be used when the field is referenced
+             * Store the field offset and length in the namespace node
+             * so it can be used when the field is referenced
              */
-            Node->Value = (UINT32) InitializerOp->Asl.Value.Integer;
+            Node->Value = InitializerOp->Asl.Value.Tag.BitOffset;
+            Node->Length = InitializerOp->Asl.Value.Tag.BitLength;
             InitializerOp->Asl.Node = Node;
             Node->Op = InitializerOp;
+        }
 
-            /* Pass thru the field type (Bitfield or Bytefield) */
-
-            if (InitializerOp->Asl.CompileFlags & NODE_IS_BIT_OFFSET)
-            {
-                Node->Flags |= ANOBJ_IS_BIT_OFFSET;
-            }
-        }
         InitializerOp = ASL_GET_PEER_NODE (InitializerOp);
     }
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/compiler/asllookup.c
--- a/head/sys/contrib/dev/acpica/compiler/asllookup.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/compiler/asllookup.c	Tue Dec 06 20:26:16 2011 +0200
@@ -822,7 +822,10 @@
     ACPI_PARSE_OBJECT       *OwningOp;
     ACPI_PARSE_OBJECT       *SpaceIdOp;
     UINT32                  MinimumLength;
-    UINT32                  Temp;
+    UINT32                  Offset;
+    UINT32                  FieldBitLength;
+    UINT32                  TagBitLength;
+    UINT8                   Message = 0;
     const ACPI_OPCODE_INFO  *OpInfo;
     UINT32                  Flags;
 
@@ -1026,74 +1029,106 @@
     /* 2) Check for a reference to a resource descriptor */
 
     if ((Node->Type == ACPI_TYPE_LOCAL_RESOURCE_FIELD) ||
-             (Node->Type == ACPI_TYPE_LOCAL_RESOURCE))
+        (Node->Type == ACPI_TYPE_LOCAL_RESOURCE))
     {
         /*
-         * This was a reference to a field within a resource descriptor.  Extract
-         * the associated field offset (either a bit or byte offset depending on
-         * the field type) and change the named reference into an integer for
-         * AML code generation
+         * This was a reference to a field within a resource descriptor.
+         * Extract the associated field offset (either a bit or byte
+         * offset depending on the field type) and change the named
+         * reference into an integer for AML code generation
          */
-        Temp = Node->Value;
-        if (Node->Flags & ANOBJ_IS_BIT_OFFSET)
+        Offset = Node->Value;
+        TagBitLength = Node->Length;
+
+        /*
+         * If a field is being created, generate the length (in bits) of
+         * the field. Note: Opcodes other than CreateXxxField and Index
+         * can come through here. For other opcodes, we just need to
+         * convert the resource tag reference to an integer offset.
+         */
+        switch (Op->Asl.Parent->Asl.AmlOpcode)
         {
-            Op->Asl.CompileFlags |= NODE_IS_BIT_OFFSET;
+        case AML_CREATE_FIELD_OP: /* Variable "Length" field, in bits */
+            /*
+             * We know the length operand is an integer constant because
+             * we know that it contains a reference to a resource
+             * descriptor tag.
+             */
+            FieldBitLength = (UINT32) Op->Asl.Next->Asl.Value.Integer;
+            break;
+
+        case AML_CREATE_BIT_FIELD_OP:
+            FieldBitLength = 1;
+            break;
+
+        case AML_CREATE_BYTE_FIELD_OP:
+        case AML_INDEX_OP:
+            FieldBitLength = 8;
+            break;
+
+        case AML_CREATE_WORD_FIELD_OP:
+            FieldBitLength = 16;
+            break;
+
+        case AML_CREATE_DWORD_FIELD_OP:
+            FieldBitLength = 32;
+            break;
+
+        case AML_CREATE_QWORD_FIELD_OP:
+            FieldBitLength = 64;
+            break;
+
+        default:
+            FieldBitLength = 0;
+            break;
         }
 
-        /* Perform BitOffset <--> ByteOffset conversion if necessary */
+        /* Check the field length against the length of the resource tag */
+
+        if (FieldBitLength)
+        {
+            if (TagBitLength < FieldBitLength)
+            {
+                Message = ASL_MSG_TAG_SMALLER;
+            }
+            else if (TagBitLength > FieldBitLength)
+            {
+                Message = ASL_MSG_TAG_LARGER;
+            }
+
+            if (Message)
+            {
+                sprintf (MsgBuffer, "Tag: %u bit%s, Field: %u bit%s",
+                    TagBitLength, (TagBitLength > 1) ? "s" : "",
+                    FieldBitLength, (FieldBitLength > 1) ? "s" : "");
+
+                AslError (ASL_WARNING, Message, Op, MsgBuffer);
+            }
+        }
+
+        /* Convert the BitOffset to a ByteOffset for certain opcodes */
 
         switch (Op->Asl.Parent->Asl.AmlOpcode)
         {
-        case AML_CREATE_FIELD_OP:
-
-            /* We allow a Byte offset to Bit Offset conversion for this op */
-
-            if (!(Op->Asl.CompileFlags & NODE_IS_BIT_OFFSET))
-            {
-                /* Simply multiply byte offset times 8 to get bit offset */
-
-                Temp = ACPI_MUL_8 (Temp);
-            }
-            break;
-
-
-        case AML_CREATE_BIT_FIELD_OP:
-
-            /* This op requires a Bit Offset */
-
-            if (!(Op->Asl.CompileFlags & NODE_IS_BIT_OFFSET))
-            {
-                AslError (ASL_ERROR, ASL_MSG_BYTES_TO_BITS, Op, NULL);
-            }
-            break;
-
-
         case AML_CREATE_BYTE_FIELD_OP:
         case AML_CREATE_WORD_FIELD_OP:
         case AML_CREATE_DWORD_FIELD_OP:
         case AML_CREATE_QWORD_FIELD_OP:
         case AML_INDEX_OP:
 
-            /* These Ops require Byte offsets */
-
-            if (Op->Asl.CompileFlags & NODE_IS_BIT_OFFSET)
-            {
-                AslError (ASL_ERROR, ASL_MSG_BITS_TO_BYTES, Op, NULL);
-            }
+            Offset = ACPI_DIV_8 (Offset);
             break;
 
-
         default:
-            /* Nothing to do for other opcodes */
             break;
         }
 
         /* Now convert this node to an integer whose value is the field offset */
 
-        Op->Asl.AmlLength       = 0;
-        Op->Asl.ParseOpcode     = PARSEOP_INTEGER;
-        Op->Asl.Value.Integer   = (UINT64) Temp;
-        Op->Asl.CompileFlags   |= NODE_IS_RESOURCE_FIELD;
+        Op->Asl.AmlLength = 0;
+        Op->Asl.ParseOpcode = PARSEOP_INTEGER;
+        Op->Asl.Value.Integer = (UINT64) Offset;
+        Op->Asl.CompileFlags |= NODE_IS_RESOURCE_FIELD;
 
         OpcGenerateAmlOpcode (Op);
     }
@@ -1253,6 +1288,7 @@
             {
             case ACPI_ADR_SPACE_EC:
             case ACPI_ADR_SPACE_CMOS:
+            case ACPI_ADR_SPACE_GPIO:
 
                 if ((UINT8) Op->Asl.Parent->Asl.Value.Integer != AML_FIELD_ACCESS_BYTE)
                 {
@@ -1262,6 +1298,7 @@
 
             case ACPI_ADR_SPACE_SMBUS:
             case ACPI_ADR_SPACE_IPMI:
+            case ACPI_ADR_SPACE_GSBUS:
 
                 if ((UINT8) Op->Asl.Parent->Asl.Value.Integer != AML_FIELD_ACCESS_BUFFER)
                 {
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/compiler/aslmain.c
--- a/head/sys/contrib/dev/acpica/compiler/aslmain.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/compiler/aslmain.c	Tue Dec 06 20:26:16 2011 +0200
@@ -96,7 +96,7 @@
 
 
 #define ASL_TOKEN_SEPARATORS    " \t\n"
-#define ASL_SUPPORTED_OPTIONS   "@:2b:c:d^e:fgh^i^I:l^no:p:r:s:t:T:v:w:x:z"
+#define ASL_SUPPORTED_OPTIONS   "@:2b:c:d^e:fgh^i^I:l^mno:p:r:s:t:T:G^v:w:x:z"
 
 
 /*******************************************************************************
@@ -116,55 +116,57 @@
     void)
 {
 
-    printf ("Global:\n");
-    printf ("  -@<file>       Specify command file\n");
-    printf ("  -I<dir>        Specify additional include directory\n");
+    printf ("\nGlobal:\n");
+    ACPI_OPTION ("-@ <file>",       "Specify command file");
+    ACPI_OPTION ("-I <dir>",        "Specify additional include directory");
 
     printf ("\nGeneral Output:\n");
-    printf ("  -p<prefix>     Specify path/filename prefix for all output files\n");
-    printf ("  -va            Disable all errors and warnings (summary only)\n");
-    printf ("  -vi            Less verbose errors and warnings for use with IDEs\n");
-    printf ("  -vo            Enable optimization comments\n");
-    printf ("  -vr            Disable remarks\n");
-    printf ("  -vs            Disable signon\n");
-    printf ("  -w<1|2|3>      Set warning reporting level\n");
+    ACPI_OPTION ("-p <prefix>",     "Specify path/filename prefix for all output files");
+    ACPI_OPTION ("-va",             "Disable all errors and warnings (summary only)");
+    ACPI_OPTION ("-vi",             "Less verbose errors and warnings for use with IDEs");
+    ACPI_OPTION ("-vo",             "Enable optimization comments");
+    ACPI_OPTION ("-vr",             "Disable remarks");
+    ACPI_OPTION ("-vs",             "Disable signon");
+    ACPI_OPTION ("-w <1|2|3>",      "Set warning reporting level");
 
     printf ("\nAML Output Files:\n");
-    printf ("  -s<a|c>        Create AML in assembler or C source file (*.asm or *.c)\n");
-    printf ("  -i<a|c>        Create assembler or C include file (*.inc or *.h)\n");
-    printf ("  -t<a|c|s>      Create AML in assembler, C, or ASL hex table (*.hex)\n");
+    ACPI_OPTION ("-s <a|c>",        "Create AML in assembler or C source file (*.asm or *.c)");
+    ACPI_OPTION ("-i <a|c>",        "Create assembler or C include file (*.inc or *.h)");
+    ACPI_OPTION ("-t <a|c|s>",      "Create AML in assembler, C, or ASL hex table (*.hex)");
 
     printf ("\nAML Code Generation:\n");
-    printf ("  -oa            Disable all optimizations (compatibility mode)\n");
-    printf ("  -of            Disable constant folding\n");
-    printf ("  -oi            Disable integer optimization to Zero/One/Ones\n");
-    printf ("  -on            Disable named reference string optimization\n");
-    printf ("  -cr            Disable Resource Descriptor error checking\n");
-    printf ("  -r<Revision>   Override table header Revision (1-255)\n");
+    ACPI_OPTION ("-oa",             "Disable all optimizations (compatibility mode)");
+    ACPI_OPTION ("-of",             "Disable constant folding");
+    ACPI_OPTION ("-oi",             "Disable integer optimization to Zero/One/Ones");
+    ACPI_OPTION ("-on",             "Disable named reference string optimization");
+    ACPI_OPTION ("-cr",             "Disable Resource Descriptor error checking");
+    ACPI_OPTION ("-r <revision>",   "Override table header Revision (1-255)");
 
     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");
+    ACPI_OPTION ("-l",              "Create mixed listing file (ASL source and AML) (*.lst)");
+    ACPI_OPTION ("-ln",             "Create namespace file (*.nsp)");
+    ACPI_OPTION ("-ls",             "Create combined source file (expanded includes) (*.src)");
 
     printf ("\nACPI Data Tables:\n");
-    printf ("  -T <Sig>|ALL|* Create table template file(s) for <Sig>\n");
-    printf ("  -vt            Create verbose templates (full disassembly)\n");
+    ACPI_OPTION ("-G",              "Compile custom table containing generic operators");
+    ACPI_OPTION ("-T <sig>|ALL|*",  "Create table template file(s) for <Sig>");
+    ACPI_OPTION ("-vt",             "Create verbose templates (full disassembly)");
 
     printf ("\nAML Disassembler:\n");
-    printf ("  -d  [file]     Disassemble or decode binary ACPI table to file (*.dsl)\n");
-    printf ("  -da [f1,f2]    Disassemble multiple tables from single namespace\n");
-    printf ("  -dc [file]     Disassemble AML and immediately compile it\n");
-    printf ("                 (Obtain DSDT from current system if no input file)\n");
-    printf ("  -e  [f1,f2]    Include ACPI table(s) for external symbol resolution\n");
-    printf ("  -2             Emit ACPI 2.0 compatible ASL code\n");
-    printf ("  -g             Get ACPI tables and write to files (*.dat)\n");
+    ACPI_OPTION ("-d  [file]",      "Disassemble or decode binary ACPI table to file (*.dsl)");
+    ACPI_OPTION ("-da [f1,f2]",     "Disassemble multiple tables from single namespace");
+    ACPI_OPTION ("-dc [file]",      "Disassemble AML and immediately compile it");
+    ACPI_OPTION ("",                "(Obtain DSDT from current system if no input file)");
+    ACPI_OPTION ("-e  [f1,f2]",     "Include ACPI table(s) for external symbol resolution");
+    ACPI_OPTION ("-m",              "Do not translate Buffers to Resource Templates");
+    ACPI_OPTION ("-2",              "Emit ACPI 2.0 compatible ASL code");
+    ACPI_OPTION ("-g",              "Get ACPI tables and write to files (*.dat)");
 
     printf ("\nHelp:\n");
-    printf ("  -h             Additional help and compiler debug options\n");
-    printf ("  -hc            Display operators allowed in constant expressions\n");
-    printf ("  -hr            Display ACPI reserved method names\n");
-    printf ("  -ht            Display currently supported ACPI table names\n");
+    ACPI_OPTION ("-h",              "Additional help and compiler debug options");
+    ACPI_OPTION ("-hc",             "Display operators allowed in constant expressions");
+    ACPI_OPTION ("-hr",             "Display ACPI reserved method names");
+    ACPI_OPTION ("-ht",             "Display currently supported ACPI table names");
 }
 
 
@@ -185,7 +187,7 @@
     void)
 {
 
-    printf ("AML output filename generation:\n");
+    printf ("\nAML output filename generation:\n");
     printf ("  Output filenames are generated by appending an extension to a common\n");
     printf ("  filename prefix.  The filename prefix is obtained via one of the\n");
     printf ("  following methods (in priority order):\n");
@@ -197,13 +199,13 @@
     Options ();
 
     printf ("\nCompiler/Disassembler Debug Options:\n");
-    printf ("  -b<p|t|b>      Create compiler debug/trace file (*.txt)\n");
-    printf ("                   Types: Parse/Tree/Both\n");
-    printf ("  -f             Ignore errors, force creation of AML output file(s)\n");
-    printf ("  -n             Parse only, no output generation\n");
-    printf ("  -ot            Display compile times\n");
-    printf ("  -x<level>      Set debug level for trace output\n");
-    printf ("  -z             Do not insert new compiler ID for DataTables\n");
+    ACPI_OPTION ("-b<p|t|b>",       "Create compiler debug/trace file (*.txt)");
+    ACPI_OPTION ("",                "Types: Parse/Tree/Both");
+    ACPI_OPTION ("-f",              "Ignore errors, force creation of AML output file(s)");
+    ACPI_OPTION ("-n",              "Parse only, no output generation");
+    ACPI_OPTION ("-ot",             "Display compile times");
+    ACPI_OPTION ("-x<level>",       "Set debug level for trace output");
+    ACPI_OPTION ("-z",              "Do not insert new compiler ID for DataTables");
 }
 
 
@@ -224,8 +226,8 @@
     void)
 {
 
-    printf ("%s\n", ASL_COMPLIANCE);
-    printf ("Usage:    %s [Options] [Files]\n\n", ASL_INVOCATION_NAME);
+    printf ("%s\n\n", ASL_COMPLIANCE);
+    ACPI_USAGE_HEADER ("iasl [Options] [Files]");
     Options ();
 }
 
@@ -600,6 +602,20 @@
         break;
 
 
+    case 'm':
+
+        AcpiGbl_NoResourceDisassembly = TRUE;
+        break;
+
+
+    case 'n':
+
+        /* Parse only */
+
+        Gbl_ParseOnlyFlag = TRUE;
+        break;
+
+
     case 'o':
 
         switch (AcpiGbl_Optarg[0])
@@ -648,14 +664,6 @@
         break;
 
 
-    case 'n':
-
-        /* Parse only */
-
-        Gbl_ParseOnlyFlag = TRUE;
-        break;
-
-
     case 'p':
 
         /* Override default AML output filename */
@@ -720,6 +728,11 @@
         break;
 
 
+    case 'G':
+        Gbl_CompileGeneric = TRUE;
+        break;
+
+
     case 'T':
         Gbl_DoTemplates = TRUE;
         Gbl_TemplateSignature = AcpiGbl_Optarg;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/compiler/aslmap.c
--- a/head/sys/contrib/dev/acpica/compiler/aslmap.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/compiler/aslmap.c	Tue Dec 06 20:26:16 2011 +0200
@@ -126,13 +126,16 @@
 
 
 /* ACCESSAS */                  OP_TABLE_ENTRY (AML_INT_ACCESSFIELD_OP,     0,                              0,                  0),
-/* ACCESSATTRIB_BLOCK */        OP_TABLE_ENTRY (AML_BYTE_OP,                AML_FIELD_ATTRIB_SMB_BLOCK,     0,                  0),
-/* ACCESSATTRIB_BLOCK_CALL */   OP_TABLE_ENTRY (AML_BYTE_OP,                AML_FIELD_ATTRIB_SMB_BLOCK_CALL,0,                  0),
-/* ACCESSATTRIB_BYTE */         OP_TABLE_ENTRY (AML_BYTE_OP,                AML_FIELD_ATTRIB_SMB_BYTE,      0,                  0),
-/* ACCESSATTRIB_WORD_CALL */    OP_TABLE_ENTRY (AML_BYTE_OP,                AML_FIELD_ATTRIB_SMB_WORD_CALL, 0,                  0),
-/* ACCESSATTRIB_QUICK */        OP_TABLE_ENTRY (AML_BYTE_OP,                AML_FIELD_ATTRIB_SMB_QUICK,     0,                  0),
-/* ACCESSATTRIB_SND_RCV */      OP_TABLE_ENTRY (AML_BYTE_OP,                AML_FIELD_ATTRIB_SMB_SEND_RCV,  0,                  0),
-/* ACCESSATTRIB_WORD */         OP_TABLE_ENTRY (AML_BYTE_OP,                AML_FIELD_ATTRIB_SMB_WORD,      0,                  0),
+/* ACCESSATTRIB_BLOCK */        OP_TABLE_ENTRY (AML_BYTE_OP,                AML_FIELD_ATTRIB_BLOCK,         0,                  0),
+/* ACCESSATTRIB_BLOCK_CALL */   OP_TABLE_ENTRY (AML_BYTE_OP,                AML_FIELD_ATTRIB_BLOCK_CALL,    0,                  0),
+/* ACCESSATTRIB_BYTE */         OP_TABLE_ENTRY (AML_BYTE_OP,                AML_FIELD_ATTRIB_BYTE,          0,                  0),
+/* ACCESSATTRIB_MULTIBYTE */    OP_TABLE_ENTRY (AML_BYTE_OP,                AML_FIELD_ATTRIB_MULTIBYTE,     0,                  0),
+/* ACCESSATTRIB_QUICK */        OP_TABLE_ENTRY (AML_BYTE_OP,                AML_FIELD_ATTRIB_QUICK,         0,                  0),
+/* ACCESSATTRIB_RAW_BYTES */    OP_TABLE_ENTRY (AML_BYTE_OP,                AML_FIELD_ATTRIB_RAW_BYTES,     0,                  0),
+/* ACCESSATTRIB_RAW_PROCESS */  OP_TABLE_ENTRY (AML_BYTE_OP,                AML_FIELD_ATTRIB_RAW_PROCESS,   0,                  0),
+/* ACCESSATTRIB_SND_RCV */      OP_TABLE_ENTRY (AML_BYTE_OP,                AML_FIELD_ATTRIB_SEND_RCV,      0,                  0),
+/* ACCESSATTRIB_WORD */         OP_TABLE_ENTRY (AML_BYTE_OP,                AML_FIELD_ATTRIB_WORD,          0,                  0),
+/* ACCESSATTRIB_WORD_CALL */    OP_TABLE_ENTRY (AML_BYTE_OP,                AML_FIELD_ATTRIB_WORD_CALL,     0,                  0),
 /* ACCESSTYPE_ANY */            OP_TABLE_ENTRY (AML_BYTE_OP,                AML_FIELD_ACCESS_ANY,           0,                  0),
 /* ACCESSTYPE_BUF */            OP_TABLE_ENTRY (AML_BYTE_OP,                AML_FIELD_ACCESS_BUFFER,        0,                  0),
 /* ACCESSTYPE_BYTE */           OP_TABLE_ENTRY (AML_BYTE_OP,                AML_FIELD_ACCESS_BYTE,          0,                  0),
@@ -141,7 +144,8 @@
 /* ACCESSTYPE_WORD */           OP_TABLE_ENTRY (AML_BYTE_OP,                AML_FIELD_ACCESS_WORD,          0,                  0),
 /* ACQUIRE */                   OP_TABLE_ENTRY (AML_ACQUIRE_OP,             0,                              0,                  ACPI_BTYPE_INTEGER),
 /* ADD */                       OP_TABLE_ENTRY (AML_ADD_OP,                 0,                              0,                  ACPI_BTYPE_INTEGER),
-/* ADDRESSSPACE_FFIXEDHW */     OP_TABLE_ENTRY (AML_BYTE_OP,                ACPI_ADR_SPACE_FIXED_HARDWARE,  0,                  0),
+/* ADDRESSINGMODE_7BIT */       OP_TABLE_ENTRY (AML_BYTE_OP,                0,                              0,                  0),
+/* ADDRESSINGMODE_10BIT */      OP_TABLE_ENTRY (AML_BYTE_OP,                1,                              0,                  0),
 /* ADDRESSTYPE_ACPI */          OP_TABLE_ENTRY (AML_BYTE_OP,                2,                              0,                  0),
 /* ADDRESSTYPE_MEMORY */        OP_TABLE_ENTRY (AML_BYTE_OP,                0,                              0,                  0),
 /* ADDRESSTYPE_NVS */           OP_TABLE_ENTRY (AML_BYTE_OP,                3,                              0,                  0),
@@ -156,6 +160,11 @@
 /* ARG5 */                      OP_TABLE_ENTRY (AML_ARG5,                   0,                              0,                  ACPI_BTYPE_OBJECTS_AND_REFS),
 /* ARG6 */                      OP_TABLE_ENTRY (AML_ARG6,                   0,                              0,                  ACPI_BTYPE_OBJECTS_AND_REFS),
 /* BANKFIELD */                 OP_TABLE_ENTRY (AML_BANK_FIELD_OP,          0,                              NODE_AML_PACKAGE,   0),
+/* BITSPERBYTE_EIGHT */         OP_TABLE_ENTRY (AML_BYTE_OP,                3,                              0,                  0),
+/* BITSPERBYTE_FIVE */          OP_TABLE_ENTRY (AML_BYTE_OP,                0,                              0,                  0),
+/* BITSPERBYTE_NINE */          OP_TABLE_ENTRY (AML_BYTE_OP,                4,                              0,                  0),
+/* BITSPERBYTE_SEVEN */         OP_TABLE_ENTRY (AML_BYTE_OP,                2,                              0,                  0),
+/* BITSPERBYTE_SIX */           OP_TABLE_ENTRY (AML_BYTE_OP,                1,                              0,                  0),
 /* BREAK */                     OP_TABLE_ENTRY (AML_BREAK_OP,               0,                              0,                  0),
 /* BREAKPOINT */                OP_TABLE_ENTRY (AML_BREAK_POINT_OP,         0,                              0,                  0),
 /* BUFFER */                    OP_TABLE_ENTRY (AML_BUFFER_OP,              0,                              NODE_AML_PACKAGE,   ACPI_BTYPE_BUFFER),
@@ -163,9 +172,14 @@
 /* BUSMASTERTYPE_NOTMASTER */   OP_TABLE_ENTRY (AML_BYTE_OP,                0,                              0,                  0),
 /* BYTECONST */                 OP_TABLE_ENTRY (AML_RAW_DATA_BYTE,          0,                              0,                  ACPI_BTYPE_INTEGER),
 /* CASE */                      OP_TABLE_ENTRY (AML_DEFAULT_ARG_OP,         0,                              0,                  0),
+/* CLOCKPHASE_FIRST */          OP_TABLE_ENTRY (AML_BYTE_OP,                0,                              0,                  0),
+/* CLOCKPHASE_SECOND */         OP_TABLE_ENTRY (AML_BYTE_OP,                1,                              0,                  0),
+/* CLOCKPOLARITY_HIGH */        OP_TABLE_ENTRY (AML_BYTE_OP,                1,                              0,                  0),
+/* CLOCKPOLARITY_LOW */         OP_TABLE_ENTRY (AML_BYTE_OP,                0,                              0,                  0),
 /* CONCATENATE */               OP_TABLE_ENTRY (AML_CONCAT_OP,              0,                              0,                  ACPI_BTYPE_COMPUTE_DATA),
 /* CONCATENATERESTEMPLATE */    OP_TABLE_ENTRY (AML_CONCAT_RES_OP,          0,                              0,                  ACPI_BTYPE_BUFFER),
 /* CONDREFOF */                 OP_TABLE_ENTRY (AML_COND_REF_OF_OP,         0,                              0,                  ACPI_BTYPE_INTEGER),
+/* CONNECTION */                OP_TABLE_ENTRY (AML_INT_CONNECTION_OP,      0,                              0,                  0),
 /* CONTINUE */                  OP_TABLE_ENTRY (AML_CONTINUE_OP,            0,                              0,                  0),
 /* COPY */                      OP_TABLE_ENTRY (AML_COPY_OP,                0,                              0,                  ACPI_BTYPE_DATA_REFERENCE),
 /* CREATEBITFIELD */            OP_TABLE_ENTRY (AML_CREATE_BIT_FIELD_OP,    0,                              0,                  0),
@@ -174,6 +188,7 @@
 /* CREATEFIELD */               OP_TABLE_ENTRY (AML_CREATE_FIELD_OP,        0,                              0,                  0),
 /* CREATEQWORDFIELD */          OP_TABLE_ENTRY (AML_CREATE_QWORD_FIELD_OP,  0,                              0,                  0),
 /* CREATEWORDFIELD */           OP_TABLE_ENTRY (AML_CREATE_WORD_FIELD_OP,   0,                              0,                  0),
+/* DATABUFFER */                OP_TABLE_ENTRY (AML_DEFAULT_ARG_OP,         0,                              0,                  0),
 /* DATATABLEREGION */           OP_TABLE_ENTRY (AML_DATA_REGION_OP,         0,                              0,                  0),
 /* DEBUG */                     OP_TABLE_ENTRY (AML_DEBUG_OP,               0,                              0,                  ACPI_BTYPE_DEBUG_OBJECT),
 /* DECODETYPE_POS */            OP_TABLE_ENTRY (AML_BYTE_OP,                0,                              0,                  0),
@@ -184,6 +199,8 @@
 /* DEFINITIONBLOCK */           OP_TABLE_ENTRY (AML_DEFAULT_ARG_OP,         0,                              0,                  0),
 /* DEREFOF */                   OP_TABLE_ENTRY (AML_DEREF_OF_OP,            0,                              0,                  ACPI_BTYPE_DATA_REFERENCE | ACPI_BTYPE_STRING),
 /* DEVICE */                    OP_TABLE_ENTRY (AML_DEVICE_OP,              0,                              NODE_AML_PACKAGE,   0),
+/* DEVICEPOLARITY_HIGH */       OP_TABLE_ENTRY (AML_BYTE_OP,                1,                              0,                  0),
+/* DEVICEPOLARITY_LOW */        OP_TABLE_ENTRY (AML_BYTE_OP,                0,                              0,                  0),
 /* DIVIDE */                    OP_TABLE_ENTRY (AML_DIVIDE_OP,              0,                              0,                  ACPI_BTYPE_INTEGER),
 /* DMA */                       OP_TABLE_ENTRY (AML_DEFAULT_ARG_OP,         0,                              0,                  0),
 /* DMATYPE_A */                 OP_TABLE_ENTRY (AML_BYTE_OP,                1,                              0,                  0),
@@ -198,6 +215,8 @@
 /* ELSE */                      OP_TABLE_ENTRY (AML_ELSE_OP,                0,                              NODE_AML_PACKAGE,   0),
 /* ELSEIF */                    OP_TABLE_ENTRY (AML_DEFAULT_ARG_OP,         0,                              NODE_AML_PACKAGE,   0),
 /* ENDDEPENDENTFN */            OP_TABLE_ENTRY (AML_DEFAULT_ARG_OP,         0,                              0,                  0),
+/* ENDIAN_BIG */                OP_TABLE_ENTRY (AML_BYTE_OP,                1,                              0,                  0),
+/* ENDIAN_LITTLE */             OP_TABLE_ENTRY (AML_BYTE_OP,                0,                              0,                  0),
 /* ENDTAG */                    OP_TABLE_ENTRY (AML_DEFAULT_ARG_OP,         0,                              0,                  0),
 /* ERRORNODE */                 OP_TABLE_ENTRY (AML_NOOP_OP,                0,                              0,                  0),
 /* EVENT */                     OP_TABLE_ENTRY (AML_EVENT_OP,               0,                              0,                  0),
@@ -209,9 +228,16 @@
 /* FIELD */                     OP_TABLE_ENTRY (AML_FIELD_OP,               0,                              NODE_AML_PACKAGE,   0),
 /* FINDSETLEFTBIT */            OP_TABLE_ENTRY (AML_FIND_SET_LEFT_BIT_OP,   0,                              0,                  ACPI_BTYPE_INTEGER),
 /* FINDSETRIGHTBIT */           OP_TABLE_ENTRY (AML_FIND_SET_RIGHT_BIT_OP,  0,                              0,                  ACPI_BTYPE_INTEGER),
+/* FIXEDDMA */                  OP_TABLE_ENTRY (AML_DEFAULT_ARG_OP,         0,                              0,                  0),
 /* FIXEDIO */                   OP_TABLE_ENTRY (AML_DEFAULT_ARG_OP,         0,                              0,                  0),
+/* FLOWCONTROL_HW */            OP_TABLE_ENTRY (AML_BYTE_OP,                1,                              0,                  0),
+/* FLOWCONTROL_NONE */          OP_TABLE_ENTRY (AML_BYTE_OP,                0,                              0,                  0),
+/* FLOWCONTROL_SW */            OP_TABLE_ENTRY (AML_BYTE_OP,                2,                              0,                  0),
 /* FROMBCD */                   OP_TABLE_ENTRY (AML_FROM_BCD_OP,            0,                              0,                  ACPI_BTYPE_INTEGER),
 /* FUNCTION */                  OP_TABLE_ENTRY (AML_METHOD_OP,              0,                              NODE_AML_PACKAGE,   0),
+/* GPIOINT */                   OP_TABLE_ENTRY (AML_DEFAULT_ARG_OP,         0,                              0,                  0),
+/* GPIOIO */                    OP_TABLE_ENTRY (AML_DEFAULT_ARG_OP,         0,                              0,                  0),
+/* I2CSERIALBUS */              OP_TABLE_ENTRY (AML_DEFAULT_ARG_OP,         0,                              0,                  0),
 /* IF */                        OP_TABLE_ENTRY (AML_IF_OP,                  0,                              NODE_AML_PACKAGE,   0),
 /* INCLUDE */                   OP_TABLE_ENTRY (AML_DEFAULT_ARG_OP,         0,                              0,                  0),
 /* INCLUDE_CSTYLE */            OP_TABLE_ENTRY (AML_DEFAULT_ARG_OP,         0,                              0,                  0),
@@ -221,6 +247,7 @@
 /* INDEXFIELD */                OP_TABLE_ENTRY (AML_INDEX_FIELD_OP,         0,                              NODE_AML_PACKAGE,   0),
 /* INTEGER */                   OP_TABLE_ENTRY (AML_BYTE_OP,                0,                              0,                  ACPI_BTYPE_INTEGER),
 /* INTERRUPT */                 OP_TABLE_ENTRY (AML_DEFAULT_ARG_OP,         0,                              0,                  0),
+/* INTLEVEL_ACTIVEBOTH */       OP_TABLE_ENTRY (AML_BYTE_OP,                2,                              0,                  0),
 /* INTLEVEL_ACTIVEHIGH */       OP_TABLE_ENTRY (AML_BYTE_OP,                0,                              0,                  0),
 /* INTLEVEL_ACTIVELOW */        OP_TABLE_ENTRY (AML_BYTE_OP,                1,                              0,                  0),
 /* INTTYPE_EDGE */              OP_TABLE_ENTRY (AML_BYTE_OP,                1,                              0,                  0),
@@ -228,6 +255,10 @@
 /* IO */                        OP_TABLE_ENTRY (AML_DEFAULT_ARG_OP,         0,                              0,                  0),
 /* IODECODETYPE_10 */           OP_TABLE_ENTRY (AML_BYTE_OP,                0,                              0,                  0),
 /* IODECODETYPE_16 */           OP_TABLE_ENTRY (AML_BYTE_OP,                1,                              0,                  0),
+/* IORESTRICT_IN */             OP_TABLE_ENTRY (AML_BYTE_OP,                1,                              0,                  0),
+/* IORESTRICT_NONE */           OP_TABLE_ENTRY (AML_BYTE_OP,                0,                              0,                  0),
+/* IORESTRICT_OUT */            OP_TABLE_ENTRY (AML_BYTE_OP,                2,                              0,                  0),
+/* IORESTRICT_PRESERVE */       OP_TABLE_ENTRY (AML_BYTE_OP,                3,                              0,                  0),
 /* IRQ */                       OP_TABLE_ENTRY (AML_DEFAULT_ARG_OP,         0,                              0,                  0),
 /* IRQNOFLAGS */                OP_TABLE_ENTRY (AML_DEFAULT_ARG_OP,         0,                              0,                  0),
 /* LAND */                      OP_TABLE_ENTRY (AML_LAND_OP,                0,                              0,                  ACPI_BTYPE_INTEGER),
@@ -308,6 +339,15 @@
 /* OR */                        OP_TABLE_ENTRY (AML_BIT_OR_OP,              0,                              0,                  ACPI_BTYPE_INTEGER),
 /* PACKAGE */                   OP_TABLE_ENTRY (AML_PACKAGE_OP,             0,                              NODE_AML_PACKAGE,   ACPI_BTYPE_PACKAGE),
 /* PACKAGEP_LENGTH */           OP_TABLE_ENTRY (AML_PACKAGE_LENGTH,         0,                              NODE_AML_PACKAGE,   0),
+/* PARITYTYPE_EVEN */           OP_TABLE_ENTRY (AML_BYTE_OP,                1,                              0,                  0),
+/* PARITYTYPE_MARK */           OP_TABLE_ENTRY (AML_BYTE_OP,                3,                              0,                  0),
+/* PARITYTYPE_NONE */           OP_TABLE_ENTRY (AML_BYTE_OP,                0,                              0,                  0),
+/* PARITYTYPE_ODD */            OP_TABLE_ENTRY (AML_BYTE_OP,                2,                              0,                  0),
+/* PARITYTYPE_SPACE */          OP_TABLE_ENTRY (AML_BYTE_OP,                4,                              0,                  0),
+/* PIN_NOPULL */                OP_TABLE_ENTRY (AML_BYTE_OP,                3,                              0,                  0),
+/* PIN_PULLDEFAULT */           OP_TABLE_ENTRY (AML_BYTE_OP,                0,                              0,                  0),
+/* PIN_PULLDOWN */              OP_TABLE_ENTRY (AML_BYTE_OP,                2,                              0,                  0),
+/* PIN_PULLUP */                OP_TABLE_ENTRY (AML_BYTE_OP,                1,                              0,                  0),
 /* POWERRESOURCE */             OP_TABLE_ENTRY (AML_POWER_RES_OP,           0,                              NODE_AML_PACKAGE,   0),
 /* PROCESSOR */                 OP_TABLE_ENTRY (AML_PROCESSOR_OP,           0,                              NODE_AML_PACKAGE,   0),
 /* QWORDCONST */                OP_TABLE_ENTRY (AML_RAW_DATA_QWORD,         0,                              0,                  ACPI_BTYPE_INTEGER),
@@ -323,6 +363,9 @@
 /* REFOF */                     OP_TABLE_ENTRY (AML_REF_OF_OP,              0,                              0,                  ACPI_BTYPE_REFERENCE),
 /* REGIONSPACE_CMOS */          OP_TABLE_ENTRY (AML_RAW_DATA_BYTE,          ACPI_ADR_SPACE_CMOS,            0,                  0),
 /* REGIONSPACE_EC */            OP_TABLE_ENTRY (AML_RAW_DATA_BYTE,          ACPI_ADR_SPACE_EC,              0,                  0),
+/* REGIONSPACE_FFIXEDHW */      OP_TABLE_ENTRY (AML_RAW_DATA_BYTE,          ACPI_ADR_SPACE_FIXED_HARDWARE,  0,                  0),
+/* REGIONSPACE_GPIO */          OP_TABLE_ENTRY (AML_RAW_DATA_BYTE,          ACPI_ADR_SPACE_GPIO,            0,                  0),
+/* REGIONSPACE_GSBUS */         OP_TABLE_ENTRY (AML_RAW_DATA_BYTE,          ACPI_ADR_SPACE_GSBUS,           0,                  0),
 /* REGIONSPACE_IO */            OP_TABLE_ENTRY (AML_RAW_DATA_BYTE,          ACPI_ADR_SPACE_SYSTEM_IO,       0,                  0),
 /* REGIONSPACE_IPMI */          OP_TABLE_ENTRY (AML_RAW_DATA_BYTE,          ACPI_ADR_SPACE_IPMI,            0,                  0),
 /* REGIONSPACE_MEM */           OP_TABLE_ENTRY (AML_RAW_DATA_BYTE,          ACPI_ADR_SPACE_SYSTEM_MEMORY,   0,                  0),
@@ -342,15 +385,24 @@
 /* SERIALIZERULE_NOTSERIAL */   OP_TABLE_ENTRY (AML_BYTE_OP,                0,                              0,                  0),
 /* SERIALIZERULE_SERIAL */      OP_TABLE_ENTRY (AML_BYTE_OP,                1,                              0,                  0),
 /* SHARETYPE_EXCLUSIVE */       OP_TABLE_ENTRY (AML_BYTE_OP,                0,                              0,                  0),
+/* SHARETYPE_EXCLUSIVEWAKE */   OP_TABLE_ENTRY (AML_BYTE_OP,                2,                              0,                  0),
 /* SHARETYPE_SHARED */          OP_TABLE_ENTRY (AML_BYTE_OP,                1,                              0,                  0),
+/* SHARETYPE_SHAREDWAKE */      OP_TABLE_ENTRY (AML_BYTE_OP,                3,                              0,                  0),
 /* SHIFTLEFT */                 OP_TABLE_ENTRY (AML_SHIFT_LEFT_OP,          0,                              0,                  ACPI_BTYPE_INTEGER),
 /* SHIFTRIGHT */                OP_TABLE_ENTRY (AML_SHIFT_RIGHT_OP,         0,                              0,                  ACPI_BTYPE_INTEGER),
 /* SIGNAL */                    OP_TABLE_ENTRY (AML_SIGNAL_OP,              0,                              0,                  0),
 /* SIZEOF */                    OP_TABLE_ENTRY (AML_SIZE_OF_OP,             0,                              0,                  ACPI_BTYPE_INTEGER),
+/* SLAVEMODE_CONTROLLERINIT */  OP_TABLE_ENTRY (AML_BYTE_OP,                0,                              0,                  0),
+/* SLAVEMODE_DEVICEINIT */      OP_TABLE_ENTRY (AML_BYTE_OP,                1,                              0,                  0),
 /* SLEEP */                     OP_TABLE_ENTRY (AML_SLEEP_OP,               0,                              0,                  0),
+/* SPISERIALBUS */              OP_TABLE_ENTRY (AML_DEFAULT_ARG_OP,         0,                              0,                  0),
 /* STALL */                     OP_TABLE_ENTRY (AML_STALL_OP,               0,                              0,                  0),
 /* STARTDEPENDENTFN */          OP_TABLE_ENTRY (AML_BYTE_OP,                0,                              0,                  0),
 /* STARTDEPENDENTFN_NOPRI */    OP_TABLE_ENTRY (AML_BYTE_OP,                0,                              0,                  0),
+/* STOPBITS_ONE */              OP_TABLE_ENTRY (AML_BYTE_OP,                1,                              0,                  0),
+/* STOPBITS_ONEPLUSHALF */      OP_TABLE_ENTRY (AML_BYTE_OP,                2,                              0,                  0),
+/* STOPBITS_TWO */              OP_TABLE_ENTRY (AML_BYTE_OP,                3,                              0,                  0),
+/* STOPBITS_ZERO */             OP_TABLE_ENTRY (AML_BYTE_OP,                0,                              0,                  0),
 /* STORE */                     OP_TABLE_ENTRY (AML_STORE_OP,               0,                              0,                  ACPI_BTYPE_DATA_REFERENCE),
 /* STRING_LITERAL */            OP_TABLE_ENTRY (AML_STRING_OP,              0,                              0,                  ACPI_BTYPE_STRING),
 /* SUBTRACT */                  OP_TABLE_ENTRY (AML_SUBTRACT_OP,            0,                              0,                  ACPI_BTYPE_INTEGER),
@@ -368,6 +420,7 @@
 /* TRANSLATIONTYPE_SPARSE */    OP_TABLE_ENTRY (AML_BYTE_OP,                1,                              0,                  0),
 /* TYPE_STATIC */               OP_TABLE_ENTRY (AML_BYTE_OP,                0,                              0,                  0),
 /* TYPE_TRANSLATION */          OP_TABLE_ENTRY (AML_BYTE_OP,                1,                              0,                  0),
+/* UART_SERIALBUS */            OP_TABLE_ENTRY (AML_DEFAULT_ARG_OP,         0,                              0,                  0),
 /* UNICODE */                   OP_TABLE_ENTRY (AML_BUFFER_OP,              0,                              NODE_AML_PACKAGE,   0),
 /* UNLOAD */                    OP_TABLE_ENTRY (AML_UNLOAD_OP,              0,                              0,                  0),
 /* UPDATERULE_ONES */           OP_TABLE_ENTRY (AML_BYTE_OP,                AML_FIELD_UPDATE_WRITE_AS_ONES, 0,                  0),
@@ -378,10 +431,18 @@
 /* VENDORSHORT */               OP_TABLE_ENTRY (AML_BYTE_OP,                0,                              0,                  0),
 /* WAIT */                      OP_TABLE_ENTRY (AML_WAIT_OP,                0,                              0,                  ACPI_BTYPE_INTEGER),
 /* WHILE */                     OP_TABLE_ENTRY (AML_WHILE_OP,               0,                              NODE_AML_PACKAGE,   0),
+/* WIREMODE_FOUR */             OP_TABLE_ENTRY (AML_BYTE_OP,                0,                              0,                  0),
+/* WIREMODE_THREE */            OP_TABLE_ENTRY (AML_BYTE_OP,                1,                              0,                  0),
 /* WORDBUSNUMBER */             OP_TABLE_ENTRY (AML_BYTE_OP,                0,                              0,                  0),
 /* WORDCONST */                 OP_TABLE_ENTRY (AML_RAW_DATA_WORD,          0,                              0,                  ACPI_BTYPE_INTEGER),
 /* WORDIO */                    OP_TABLE_ENTRY (AML_BYTE_OP,                0,                              0,                  0),
 /* WORDSPACE */                 OP_TABLE_ENTRY (AML_BYTE_OP,                0,                              0,                  0),
+/* XFERSIZE_8 */                OP_TABLE_ENTRY (AML_BYTE_OP,                0,                              0,                  0),
+/* XFERSIZE_16 */               OP_TABLE_ENTRY (AML_BYTE_OP,                0,                              0,                  0),
+/* XFERSIZE_32 */               OP_TABLE_ENTRY (AML_BYTE_OP,                0,                              0,                  0),
+/* XFERSIZE_64 */               OP_TABLE_ENTRY (AML_BYTE_OP,                0,                              0,                  0),
+/* XFERSIZE_128 */              OP_TABLE_ENTRY (AML_BYTE_OP,                0,                              0,                  0),
+/* XFERSIZE_256 */              OP_TABLE_ENTRY (AML_BYTE_OP,                0,                              0,                  0),
 /* XFERTYPE_8 */                OP_TABLE_ENTRY (AML_BYTE_OP,                0,                              0,                  0),
 /* XFERTYPE_8_16 */             OP_TABLE_ENTRY (AML_BYTE_OP,                1,                              0,                  0),
 /* XFERTYPE_16 */               OP_TABLE_ENTRY (AML_BYTE_OP,                2,                              0,                  0),
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/compiler/aslmessages.h
--- a/head/sys/contrib/dev/acpica/compiler/aslmessages.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/compiler/aslmessages.h	Tue Dec 06 20:26:16 2011 +0200
@@ -61,17 +61,20 @@
 typedef enum
 {
     ASL_MSG_RESERVED = 0,
+
+    ASL_MSG_ALIGNMENT,
     ASL_MSG_ALPHANUMERIC_STRING,
     ASL_MSG_AML_NOT_IMPLEMENTED,
     ASL_MSG_ARG_COUNT_HI,
     ASL_MSG_ARG_COUNT_LO,
     ASL_MSG_ARG_INIT,
     ASL_MSG_BACKWARDS_OFFSET,
-    ASL_MSG_BITS_TO_BYTES,
     ASL_MSG_BUFFER_LENGTH,
-    ASL_MSG_BYTES_TO_BITS,
     ASL_MSG_CLOSE,
     ASL_MSG_COMPILER_INTERNAL,
+    ASL_MSG_COMPILER_RESERVED,
+    ASL_MSG_CONNECTION_MISSING,
+    ASL_MSG_CONNECTION_INVALID,
     ASL_MSG_CONSTANT_EVALUATION,
     ASL_MSG_CONSTANT_FOLDED,
     ASL_MSG_CORE_EXCEPTION,
@@ -90,15 +93,26 @@
     ASL_MSG_FIELD_ACCESS_WIDTH,
     ASL_MSG_FIELD_UNIT_ACCESS_WIDTH,
     ASL_MSG_FIELD_UNIT_OFFSET,
+    ASL_MSG_GPE_NAME_CONFLICT,
+    ASL_MSG_HID_LENGTH,
+    ASL_MSG_HID_PREFIX,
+    ASL_MSG_HID_SUFFIX,
     ASL_MSG_INCLUDE_FILE_OPEN,
     ASL_MSG_INPUT_FILE_OPEN,
     ASL_MSG_INTEGER_LENGTH,
     ASL_MSG_INTEGER_OPTIMIZATION,
     ASL_MSG_INTERRUPT_LIST,
     ASL_MSG_INTERRUPT_NUMBER,
+    ASL_MSG_INVALID_ACCESS_SIZE,
+    ASL_MSG_INVALID_ADDR_FLAGS,
     ASL_MSG_INVALID_CONSTANT_OP,
     ASL_MSG_INVALID_EISAID,
     ASL_MSG_INVALID_ESCAPE,
+    ASL_MSG_INVALID_GRAN_FIXED,
+    ASL_MSG_INVALID_GRANULARITY,
+    ASL_MSG_INVALID_LENGTH,
+    ASL_MSG_INVALID_LENGTH_FIXED,
+    ASL_MSG_INVALID_MIN_MAX,
     ASL_MSG_INVALID_OPERAND,
     ASL_MSG_INVALID_PERFORMANCE,
     ASL_MSG_INVALID_PRIORITY,
@@ -107,28 +121,38 @@
     ASL_MSG_INVALID_TIME,
     ASL_MSG_INVALID_TYPE,
     ASL_MSG_INVALID_UUID,
+    ASL_MSG_ISA_ADDRESS,
+    ASL_MSG_LEADING_ASTERISK,
     ASL_MSG_LIST_LENGTH_LONG,
     ASL_MSG_LIST_LENGTH_SHORT,
     ASL_MSG_LISTING_FILE_OPEN,
     ASL_MSG_LISTING_FILENAME,
     ASL_MSG_LOCAL_INIT,
+    ASL_MSG_LOCAL_OUTSIDE_METHOD,
     ASL_MSG_LONG_LINE,
     ASL_MSG_MEMORY_ALLOCATION,
     ASL_MSG_MISSING_ENDDEPENDENT,
     ASL_MSG_MISSING_STARTDEPENDENT,
+    ASL_MSG_MULTIPLE_DEFAULT,
     ASL_MSG_MULTIPLE_TYPES,
     ASL_MSG_NAME_EXISTS,
     ASL_MSG_NAME_OPTIMIZATION,
+    ASL_MSG_NAMED_OBJECT_IN_WHILE,
     ASL_MSG_NESTED_COMMENT,
     ASL_MSG_NO_CASES,
+    ASL_MSG_NO_REGION,
     ASL_MSG_NO_RETVAL,
     ASL_MSG_NO_WHILE,
     ASL_MSG_NON_ASCII,
+    ASL_MSG_NON_ZERO,
     ASL_MSG_NOT_EXIST,
     ASL_MSG_NOT_FOUND,
     ASL_MSG_NOT_METHOD,
     ASL_MSG_NOT_PARAMETER,
     ASL_MSG_NOT_REACHABLE,
+    ASL_MSG_NOT_REFERENCED,
+    ASL_MSG_NULL_DESCRIPTOR,
+    ASL_MSG_NULL_STRING,
     ASL_MSG_OPEN,
     ASL_MSG_OUTPUT_FILE_OPEN,
     ASL_MSG_OUTPUT_FILENAME,
@@ -140,6 +164,7 @@
     ASL_MSG_RESERVED_ARG_COUNT_HI,
     ASL_MSG_RESERVED_ARG_COUNT_LO,
     ASL_MSG_RESERVED_METHOD,
+    ASL_MSG_RESERVED_NO_RETURN_VAL,
     ASL_MSG_RESERVED_OPERAND_TYPE,
     ASL_MSG_RESERVED_RETURN_VALUE,
     ASL_MSG_RESERVED_USE,
@@ -148,63 +173,45 @@
     ASL_MSG_RESOURCE_INDEX,
     ASL_MSG_RESOURCE_LIST,
     ASL_MSG_RESOURCE_SOURCE,
+    ASL_MSG_RESULT_NOT_USED,
     ASL_MSG_RETURN_TYPES,
     ASL_MSG_SCOPE_FWD_REF,
     ASL_MSG_SCOPE_TYPE,
     ASL_MSG_SEEK,
+    ASL_MSG_SERIALIZED,
     ASL_MSG_SINGLE_NAME_OPTIMIZATION,
     ASL_MSG_SOME_NO_RETVAL,
+    ASL_MSG_STRING_LENGTH,
     ASL_MSG_SWITCH_TYPE,
     ASL_MSG_SYNC_LEVEL,
     ASL_MSG_SYNTAX,
     ASL_MSG_TABLE_SIGNATURE,
+    ASL_MSG_TAG_LARGER,
+    ASL_MSG_TAG_SMALLER,
+    ASL_MSG_TIMEOUT,
     ASL_MSG_TOO_MANY_TEMPS,
     ASL_MSG_UNKNOWN_RESERVED_NAME,
     ASL_MSG_UNREACHABLE_CODE,
     ASL_MSG_UNSUPPORTED,
+    ASL_MSG_UPPER_CASE,
     ASL_MSG_VENDOR_LIST,
     ASL_MSG_WRITE,
-    ASL_MSG_MULTIPLE_DEFAULT,
-    ASL_MSG_TIMEOUT,
-    ASL_MSG_RESULT_NOT_USED,
-    ASL_MSG_NOT_REFERENCED,
-    ASL_MSG_NON_ZERO,
-    ASL_MSG_STRING_LENGTH,
-    ASL_MSG_SERIALIZED,
-    ASL_MSG_COMPILER_RESERVED,
-    ASL_MSG_NAMED_OBJECT_IN_WHILE,
-    ASL_MSG_LOCAL_OUTSIDE_METHOD,
-    ASL_MSG_ALIGNMENT,
-    ASL_MSG_ISA_ADDRESS,
-    ASL_MSG_INVALID_MIN_MAX,
-    ASL_MSG_INVALID_LENGTH,
-    ASL_MSG_INVALID_LENGTH_FIXED,
-    ASL_MSG_INVALID_GRANULARITY,
-    ASL_MSG_INVALID_GRAN_FIXED,
-    ASL_MSG_INVALID_ACCESS_SIZE,
-    ASL_MSG_INVALID_ADDR_FLAGS,
-    ASL_MSG_NULL_DESCRIPTOR,
-    ASL_MSG_UPPER_CASE,
-    ASL_MSG_HID_LENGTH,
-    ASL_MSG_NULL_STRING,
-    ASL_MSG_LEADING_ASTERISK,
-    ASL_MSG_RESERVED_NO_RETURN_VAL,
-    ASL_MSG_GPE_NAME_CONFLICT,
-    ASL_MSG_NO_REGION,
 
+/* These messages are used by the data table compiler only */
+
+    ASL_MSG_BUFFER_ELEMENT,
+    ASL_MSG_DIVIDE_BY_ZERO,
+    ASL_MSG_FLAG_VALUE,
+    ASL_MSG_INTEGER_SIZE,
+    ASL_MSG_INVALID_EXPRESSION,
     ASL_MSG_INVALID_FIELD_NAME,
-    ASL_MSG_INTEGER_SIZE,
     ASL_MSG_INVALID_HEX_INTEGER,
-    ASL_MSG_BUFFER_ELEMENT,
+    ASL_MSG_OEM_TABLE,
     ASL_MSG_RESERVED_VALUE,
-    ASL_MSG_FLAG_VALUE,
-    ASL_MSG_ZERO_VALUE,
+    ASL_MSG_UNKNOWN_LABEL,
+    ASL_MSG_UNKNOWN_SUBTABLE,
     ASL_MSG_UNKNOWN_TABLE,
-    ASL_MSG_UNKNOWN_SUBTABLE,
-    ASL_MSG_OEM_TABLE,
-    ASL_MSG_UNKNOWN_LABEL,
-    ASL_MSG_INVALID_EXPRESSION,
-    ASL_MSG_DIVIDE_BY_ZERO
+    ASL_MSG_ZERO_VALUE
 
 } ASL_MESSAGE_IDS;
 
@@ -215,17 +222,19 @@
 
 char                        *AslMessages [] = {
 /*    The zeroth message is reserved */    "",
+/*    ASL_MSG_ALIGNMENT */                  "Must be a multiple of alignment/granularity value",
 /*    ASL_MSG_ALPHANUMERIC_STRING */        "String must be entirely alphanumeric",
 /*    ASL_MSG_AML_NOT_IMPLEMENTED */        "Opcode is not implemented in compiler AML code generator",
 /*    ASL_MSG_ARG_COUNT_HI */               "Too many arguments",
 /*    ASL_MSG_ARG_COUNT_LO */               "Too few arguments",
 /*    ASL_MSG_ARG_INIT */                   "Method argument is not initialized",
 /*    ASL_MSG_BACKWARDS_OFFSET */           "Invalid backwards offset",
-/*    ASL_MSG_BITS_TO_BYTES */              "Field offset is in bits, but a byte offset is required",
 /*    ASL_MSG_BUFFER_LENGTH */              "Effective AML buffer length is zero",
-/*    ASL_MSG_BYTES_TO_BITS */              "Field offset is in bytes, but a bit offset is required",
 /*    ASL_MSG_CLOSE */                      "Could not close file",
 /*    ASL_MSG_COMPILER_INTERNAL */          "Internal compiler error",
+/*    ASL_MSG_COMPILER_RESERVED */          "Use of compiler reserved name",
+/*    ASL_MSG_CONNECTION_MISSING */         "A Connection operator is required for this field SpaceId",
+/*    ASL_MSG_CONNECTION_INVALID */         "Invalid OpRegion SpaceId for use of Connection operator",
 /*    ASL_MSG_CONSTANT_EVALUATION */        "Could not evaluate constant expression",
 /*    ASL_MSG_CONSTANT_FOLDED */            "Constant expression evaluated and reduced",
 /*    ASL_MSG_CORE_EXCEPTION */             "From ACPI CA Subsystem",
@@ -244,15 +253,26 @@
 /*    ASL_MSG_FIELD_ACCESS_WIDTH */         "Access width is greater than region size",
 /*    ASL_MSG_FIELD_UNIT_ACCESS_WIDTH */    "Access width of Field Unit extends beyond region limit",
 /*    ASL_MSG_FIELD_UNIT_OFFSET */          "Field Unit extends beyond region limit",
+/*    ASL_MSG_GPE_NAME_CONFLICT */          "Name conflicts with a previous GPE method",
+/*    ASL_MSG_HID_LENGTH */                 "_HID string must be exactly 7 or 8 characters",
+/*    ASL_MSG_HID_PREFIX */                 "_HID prefix must be all uppercase or decimal digits",
+/*    ASL_MSG_HID_SUFFIX */                 "_HID suffix must be all hex digits",
 /*    ASL_MSG_INCLUDE_FILE_OPEN */          "Could not open include file",
 /*    ASL_MSG_INPUT_FILE_OPEN */            "Could not open input file",
 /*    ASL_MSG_INTEGER_LENGTH */             "64-bit integer in 32-bit table, truncating",
 /*    ASL_MSG_INTEGER_OPTIMIZATION */       "Integer optimized to single-byte AML opcode",
 /*    ASL_MSG_INTERRUPT_LIST */             "Too many interrupts (16 max)",
 /*    ASL_MSG_INTERRUPT_NUMBER */           "Invalid interrupt number (must be 0-15)",
+/*    ASL_MSG_INVALID_ACCESS_SIZE */        "Invalid AccessSize (Maximum is 4 - QWord access)",
+/*    ASL_MSG_INVALID_ADDR_FLAGS */         "Invalid combination of Length and Min/Max fixed flags",
 /*    ASL_MSG_INVALID_CONSTANT_OP */        "Invalid operator in constant expression (not type 3/4/5)",
 /*    ASL_MSG_INVALID_EISAID */             "EISAID string must be of the form \"UUUXXXX\" (3 uppercase, 4 hex digits)",
 /*    ASL_MSG_INVALID_ESCAPE */             "Invalid or unknown escape sequence",
+/*    ASL_MSG_INVALID_GRAN_FIXED */         "Granularity must be zero for fixed Min/Max",
+/*    ASL_MSG_INVALID_GRANULARITY */        "Granularity must be zero or a power of two minus one",
+/*    ASL_MSG_INVALID_LENGTH */             "Length is larger than Min/Max window",
+/*    ASL_MSG_INVALID_LENGTH_FIXED */       "Length is not equal to fixed Min/Max window",
+/*    ASL_MSG_INVALID_MIN_MAX */            "Address Min is greater than Address Max",
 /*    ASL_MSG_INVALID_OPERAND */            "Invalid operand",
 /*    ASL_MSG_INVALID_PERFORMANCE */        "Invalid performance/robustness value",
 /*    ASL_MSG_INVALID_PRIORITY */           "Invalid priority value",
@@ -261,28 +281,38 @@
 /*    ASL_MSG_INVALID_TIME */               "Time parameter too long (255 max)",
 /*    ASL_MSG_INVALID_TYPE */               "Invalid type",
 /*    ASL_MSG_INVALID_UUID */               "UUID string must be of the form \"aabbccdd-eeff-gghh-iijj-kkllmmnnoopp\"",
+/*    ASL_MSG_ISA_ADDRESS */                "Maximum 10-bit ISA address (0x3FF)",
+/*    ASL_MSG_LEADING_ASTERISK */           "Invalid leading asterisk",
 /*    ASL_MSG_LIST_LENGTH_LONG */           "Initializer list longer than declared package length",
 /*    ASL_MSG_LIST_LENGTH_SHORT */          "Initializer list shorter than declared package length",
 /*    ASL_MSG_LISTING_FILE_OPEN */          "Could not open listing file",
 /*    ASL_MSG_LISTING_FILENAME */           "Could not create listing filename",
 /*    ASL_MSG_LOCAL_INIT */                 "Method local variable is not initialized",
+/*    ASL_MSG_LOCAL_OUTSIDE_METHOD */       "Local or Arg used outside a control method",
 /*    ASL_MSG_LONG_LINE */                  "Splitting long input line",
 /*    ASL_MSG_MEMORY_ALLOCATION */          "Memory allocation failure",
 /*    ASL_MSG_MISSING_ENDDEPENDENT */       "Missing EndDependentFn() macro in dependent resource list",
 /*    ASL_MSG_MISSING_STARTDEPENDENT */     "Missing StartDependentFn() macro in dependent resource list",
+/*    ASL_MSG_MULTIPLE_DEFAULT */           "More than one Default statement within Switch construct",
 /*    ASL_MSG_MULTIPLE_TYPES */             "Multiple types",
 /*    ASL_MSG_NAME_EXISTS */                "Name already exists in scope",
 /*    ASL_MSG_NAME_OPTIMIZATION */          "NamePath optimized",
+/*    ASL_MSG_NAMED_OBJECT_IN_WHILE */      "Creating a named object in a While loop",
 /*    ASL_MSG_NESTED_COMMENT */             "Nested comment found",
 /*    ASL_MSG_NO_CASES */                   "No Case statements under Switch",
+/*    ASL_MSG_NO_REGION */                  "_REG has no corresponding Operation Region",
 /*    ASL_MSG_NO_RETVAL */                  "Called method returns no value",
 /*    ASL_MSG_NO_WHILE */                   "No enclosing While statement",
 /*    ASL_MSG_NON_ASCII */                  "Invalid characters found in file",
+/*    ASL_MSG_NON_ZERO */                   "Operand evaluates to zero",
 /*    ASL_MSG_NOT_EXIST */                  "Object does not exist",
 /*    ASL_MSG_NOT_FOUND */                  "Object not found or not accessible from scope",
 /*    ASL_MSG_NOT_METHOD */                 "Not a control method, cannot invoke",
 /*    ASL_MSG_NOT_PARAMETER */              "Not a parameter, used as local only",
 /*    ASL_MSG_NOT_REACHABLE */              "Object is not accessible from this scope",
+/*    ASL_MSG_NOT_REFERENCED */             "Namespace object is not referenced",
+/*    ASL_MSG_NULL_DESCRIPTOR */            "Min/Max/Length/Gran are all zero, but no resource tag",
+/*    ASL_MSG_NULL_STRING */                "Invalid zero-length (null) string",
 /*    ASL_MSG_OPEN */                       "Could not open file",
 /*    ASL_MSG_OUTPUT_FILE_OPEN */           "Could not open output AML file",
 /*    ASL_MSG_OUTPUT_FILENAME */            "Could not create output filename",
@@ -294,6 +324,7 @@
 /*    ASL_MSG_RESERVED_ARG_COUNT_HI */      "Reserved method has too many arguments",
 /*    ASL_MSG_RESERVED_ARG_COUNT_LO */      "Reserved method has too few arguments",
 /*    ASL_MSG_RESERVED_METHOD */            "Reserved name must be a control method",
+/*    ASL_MSG_RESERVED_NO_RETURN_VAL */     "Reserved method should not return a value",
 /*    ASL_MSG_RESERVED_OPERAND_TYPE */      "Invalid object type for reserved name",
 /*    ASL_MSG_RESERVED_RETURN_VALUE */      "Reserved method must return a value",
 /*    ASL_MSG_RESERVED_USE */               "Invalid use of reserved name",
@@ -302,65 +333,45 @@
 /*    ASL_MSG_RESOURCE_INDEX */             "Missing ResourceSourceIndex (required)",
 /*    ASL_MSG_RESOURCE_LIST */              "Too many resource items (internal error)",
 /*    ASL_MSG_RESOURCE_SOURCE */            "Missing ResourceSource string (required)",
+/*    ASL_MSG_RESULT_NOT_USED */            "Result is not used, operator has no effect",
 /*    ASL_MSG_RETURN_TYPES */               "Not all control paths return a value",
 /*    ASL_MSG_SCOPE_FWD_REF */              "Forward references from Scope operator not allowed",
 /*    ASL_MSG_SCOPE_TYPE */                 "Existing object has invalid type for Scope operator",
 /*    ASL_MSG_SEEK */                       "Could not seek file",
+/*    ASL_MSG_SERIALIZED */                 "Control Method marked Serialized",
 /*    ASL_MSG_SINGLE_NAME_OPTIMIZATION */   "NamePath optimized to NameSeg (uses run-time search path)",
 /*    ASL_MSG_SOME_NO_RETVAL */             "Called method may not always return a value",
+/*    ASL_MSG_STRING_LENGTH */              "String literal too long",
 /*    ASL_MSG_SWITCH_TYPE */                "Switch expression is not a static Integer/Buffer/String data type, defaulting to Integer",
 /*    ASL_MSG_SYNC_LEVEL */                 "SyncLevel must be in the range 0-15",
 /*    ASL_MSG_SYNTAX */                     "",
 /*    ASL_MSG_TABLE_SIGNATURE */            "Invalid Table Signature",
+/*    ASL_MSG_TAG_LARGER */                 "ResourceTag larger than Field",
+/*    ASL_MSG_TAG_SMALLER */                "ResourceTag smaller than Field",
+/*    ASL_MSG_TIMEOUT */                    "Result is not used, possible operator timeout will be missed",
 /*    ASL_MSG_TOO_MANY_TEMPS */             "Method requires too many temporary variables (_T_x)",
 /*    ASL_MSG_UNKNOWN_RESERVED_NAME */      "Unknown reserved name",
 /*    ASL_MSG_UNREACHABLE_CODE */           "Statement is unreachable",
 /*    ASL_MSG_UNSUPPORTED */                "Unsupported feature",
+/*    ASL_MSG_UPPER_CASE */                 "Non-hex letters must be upper case",
 /*    ASL_MSG_VENDOR_LIST */                "Too many vendor data bytes (7 max)",
 /*    ASL_MSG_WRITE */                      "Could not write file",
-/*    ASL_MSG_MULTIPLE_DEFAULT */           "More than one Default statement within Switch construct",
-/*    ASL_MSG_TIMEOUT */                    "Result is not used, possible operator timeout will be missed",
-/*    ASL_MSG_RESULT_NOT_USED */            "Result is not used, operator has no effect",
-/*    ASL_MSG_NOT_REFERENCED */             "Namespace object is not referenced",
-/*    ASL_MSG_NON_ZERO */                   "Operand evaluates to zero",
-/*    ASL_MSG_STRING_LENGTH */              "String literal too long",
-/*    ASL_MSG_SERIALIZED */                 "Control Method marked Serialized",
-/*    ASL_MSG_COMPILER_RESERVED */          "Use of compiler reserved name",
-/*    ASL_MSG_NAMED_OBJECT_IN_WHILE */      "Creating a named object in a While loop",
-/*    ASL_MSG_LOCAL_OUTSIDE_METHOD */       "Local or Arg used outside a control method",
-/*    ASL_MSG_ALIGNMENT */                  "Must be a multiple of alignment/granularity value",
-/*    ASL_MSG_ISA_ADDRESS */                "Maximum 10-bit ISA address (0x3FF)",
-/*    ASL_MSG_INVALID_MIN_MAX */            "Address Min is greater than Address Max",
-/*    ASL_MSG_INVALID_LENGTH */             "Length is larger than Min/Max window",
-/*    ASL_MSG_INVALID_LENGTH_FIXED */       "Length is not equal to fixed Min/Max window",
-/*    ASL_MSG_INVALID_GRANULARITY */        "Granularity must be zero or a power of two minus one",
-/*    ASL_MSG_INVALID_GRAN_FIXED */         "Granularity must be zero for fixed Min/Max",
-/*    ASL_MSG_INVALID_ACCESS_SIZE */        "Invalid AccessSize (Maximum is 4 - QWord access)",
-/*    ASL_MSG_INVALID_ADDR_FLAGS */         "Invalid combination of Length and Min/Max fixed flags",
-/*    ASL_MSG_NULL_DESCRIPTOR */            "Min/Max/Length/Gran are all zero, but no resource tag",
-/*    ASL_MSG_UPPER_CASE */                 "Non-hex letters must be upper case",
-/*    ASL_MSG_HID_LENGTH */                 "_HID string must be exactly 7 or 8 characters",
-/*    ASL_MSG_NULL_STRING */                "Invalid zero-length (null) string",
-/*    ASL_MSG_LEADING_ASTERISK */           "Invalid leading asterisk",
-/*    ASL_MSG_RESERVED_NO_RETURN_VAL */     "Reserved method should not return a value",
-/*    ASL_MSG_GPE_NAME_CONFLICT */          "Name conflicts with a previous GPE method",
-/*    ASL_MSG_NO_REGION */                  "_REG has no corresponding Operation Region",
 
 /* These messages are used by the data table compiler only */
 
+/*    ASL_MSG_BUFFER_ELEMENT */             "Invalid element in buffer initializer list",
+/*    ASL_MSG_DIVIDE_BY_ZERO */             "Expression contains divide-by-zero",
+/*    ASL_MSG_FLAG_VALUE */                 "Flag value is too large",
+/*    ASL_MSG_INTEGER_SIZE */               "Integer too large for target",
+/*    ASL_MSG_INVALID_EXPRESSION */         "Invalid expression",
 /*    ASL_MSG_INVALID_FIELD_NAME */         "Invalid Field Name",
-/*    ASL_MSG_INTEGER_SIZE */               "Integer too large for target",
 /*    ASL_MSG_INVALID_HEX_INTEGER */        "Invalid hex integer constant",
-/*    ASL_MSG_BUFFER_ELEMENT */             "Invalid element in buffer initializer list",
+/*    ASL_MSG_OEM_TABLE */                  "OEM table - unknown contents",
 /*    ASL_MSG_RESERVED_VALUE */             "Reserved field must be zero",
-/*    ASL_MSG_FLAG_VALUE */                 "Flag value is too large",
-/*    ASL_MSG_ZERO_VALUE */                 "Value must be non-zero",
+/*    ASL_MSG_UNKNOWN_LABEL */              "Label is undefined",
+/*    ASL_MSG_UNKNOWN_SUBTABLE */           "Unknown subtable type",
 /*    ASL_MSG_UNKNOWN_TABLE */              "Unknown ACPI table signature",
-/*    ASL_MSG_UNKNOWN_SUBTABLE */           "Unknown subtable type",
-/*    ASL_MSG_OEM_TABLE */                  "OEM table - unknown contents",
-/*    ASL_MSG_UNKNOWN_LABEL */              "Label is undefined",
-/*    ASL_MSG_INVALID_EXPRESSION */         "Invalid expression",
-/*    ASL_MSG_DIVIDE_BY_ZERO */             "Expression contains divide-by-zero"
+/*    ASL_MSG_ZERO_VALUE */                 "Value must be non-zero"
 };
 
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/compiler/aslopcodes.c
--- a/head/sys/contrib/dev/acpica/compiler/aslopcodes.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/compiler/aslopcodes.c	Tue Dec 06 20:26:16 2011 +0200
@@ -58,6 +58,10 @@
     ACPI_PARSE_OBJECT       *Op);
 
 static void
+OpcDoConnection (
+    ACPI_PARSE_OBJECT       *Op);
+
+static void
 OpcDoUnicode (
     ACPI_PARSE_OBJECT       *Op);
 
@@ -321,26 +325,128 @@
 OpcDoAccessAs (
     ACPI_PARSE_OBJECT       *Op)
 {
-    ACPI_PARSE_OBJECT       *Next;
+    ACPI_PARSE_OBJECT       *TypeOp;
+    ACPI_PARSE_OBJECT       *AttribOp;
+    ACPI_PARSE_OBJECT       *LengthOp;
+    UINT8                   Attribute;
 
 
     Op->Asl.AmlOpcodeLength = 1;
-    Next = Op->Asl.Child;
+    TypeOp = Op->Asl.Child;
 
     /* First child is the access type */
 
-    Next->Asl.AmlOpcode = AML_RAW_DATA_BYTE;
-    Next->Asl.ParseOpcode = PARSEOP_RAW_DATA;
+    TypeOp->Asl.AmlOpcode = AML_RAW_DATA_BYTE;
+    TypeOp->Asl.ParseOpcode = PARSEOP_RAW_DATA;
 
     /* Second child is the optional access attribute */
 
-    Next = Next->Asl.Next;
-    if (Next->Asl.ParseOpcode == PARSEOP_DEFAULT_ARG)
+    AttribOp = TypeOp->Asl.Next;
+    if (AttribOp->Asl.ParseOpcode == PARSEOP_DEFAULT_ARG)
     {
-        Next->Asl.Value.Integer = 0;
+        AttribOp->Asl.Value.Integer = 0;
     }
-    Next->Asl.AmlOpcode = AML_RAW_DATA_BYTE;
-    Next->Asl.ParseOpcode = PARSEOP_RAW_DATA;
+    AttribOp->Asl.AmlOpcode = AML_RAW_DATA_BYTE;
+    AttribOp->Asl.ParseOpcode = PARSEOP_RAW_DATA;
+
+    /* Only a few AccessAttributes support AccessLength */
+
+    Attribute = (UINT8) AttribOp->Asl.Value.Integer;
+    if ((Attribute != AML_FIELD_ATTRIB_MULTIBYTE) &&
+        (Attribute != AML_FIELD_ATTRIB_RAW_BYTES) &&
+        (Attribute != AML_FIELD_ATTRIB_RAW_PROCESS))
+    {
+        return;
+    }
+
+    Op->Asl.AmlOpcode = AML_FIELD_EXT_ACCESS_OP;
+
+    /*
+     * Child of Attributes is the AccessLength (required for Multibyte,
+     * RawBytes, RawProcess.)
+     */
+    LengthOp = AttribOp->Asl.Child;
+    if (!LengthOp)
+    {
+        return;
+    }
+
+    /* TBD: probably can remove */
+
+    if (LengthOp->Asl.ParseOpcode == PARSEOP_DEFAULT_ARG)
+    {
+        LengthOp->Asl.Value.Integer = 16;
+    }
+
+    LengthOp->Asl.AmlOpcode = AML_RAW_DATA_BYTE;
+    LengthOp->Asl.ParseOpcode = PARSEOP_RAW_DATA;
+}
+
+
+/*******************************************************************************
+ *
+ * FUNCTION:    OpcDoConnection
+ *
+ * PARAMETERS:  Op        - Parse node
+ *
+ * RETURN:      None
+ *
+ * DESCRIPTION: Implement the Connection ASL keyword.
+ *
+ ******************************************************************************/
+
+static void
+OpcDoConnection (
+    ACPI_PARSE_OBJECT       *Op)
+{
+    ASL_RESOURCE_NODE       *Rnode;
+    ACPI_PARSE_OBJECT       *BufferOp;
+    ACPI_PARSE_OBJECT       *BufferLengthOp;
+    ACPI_PARSE_OBJECT       *BufferDataOp;
+    UINT8                   State;
+
+
+    Op->Asl.AmlOpcodeLength = 1;
+
+    if (Op->Asl.Child->Asl.AmlOpcode == AML_INT_NAMEPATH_OP)
+    {
+        return;
+    }
+
+    BufferOp = Op->Asl.Child;
+    BufferLengthOp = BufferOp->Asl.Child;
+    BufferDataOp = BufferLengthOp->Asl.Next;
+
+    State = ACPI_RSTATE_NORMAL;
+    Rnode = RsDoOneResourceDescriptor (BufferDataOp->Asl.Next, 0, &State);
+    if (!Rnode)
+    {
+        return; /* error */
+    }
+
+    /*
+     * Transform the nodes into the following
+     *
+     * Op           -> AML_BUFFER_OP
+     * First Child  -> BufferLength
+     * Second Child -> Descriptor Buffer (raw byte data)
+     */
+    BufferOp->Asl.ParseOpcode         = PARSEOP_BUFFER;
+    BufferOp->Asl.AmlOpcode           = AML_BUFFER_OP;
+    BufferOp->Asl.CompileFlags        = NODE_AML_PACKAGE | NODE_IS_RESOURCE_DESC;
+    UtSetParseOpName (BufferOp);
+
+    BufferLengthOp->Asl.ParseOpcode   = PARSEOP_INTEGER;
+    BufferLengthOp->Asl.Value.Integer = Rnode->BufferLength;
+    (void) OpcSetOptimalIntegerSize (BufferLengthOp);
+    UtSetParseOpName (BufferLengthOp);
+
+    BufferDataOp->Asl.ParseOpcode         = PARSEOP_RAW_DATA;
+    BufferDataOp->Asl.AmlOpcode           = AML_RAW_DATA_CHAIN;
+    BufferDataOp->Asl.AmlOpcodeLength     = 0;
+    BufferDataOp->Asl.AmlLength           = Rnode->BufferLength;
+    BufferDataOp->Asl.Value.Buffer        = (UINT8 *) Rnode;
+    UtSetParseOpName (BufferDataOp);
 }
 
 
@@ -545,7 +651,7 @@
 
 /*******************************************************************************
  *
- * FUNCTION:    OpcDoUiId
+ * FUNCTION:    OpcDoUuId
  *
  * PARAMETERS:  Op        - Parse node
  *
@@ -665,6 +771,11 @@
         OpcDoAccessAs (Op);
         break;
 
+    case PARSEOP_CONNECTION:
+
+        OpcDoConnection (Op);
+        break;
+
     case PARSEOP_EISAID:
 
         OpcDoEisaId (Op);
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/compiler/asloperands.c
--- a/head/sys/contrib/dev/acpica/compiler/asloperands.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/compiler/asloperands.c	Tue Dec 06 20:26:16 2011 +0200
@@ -761,6 +761,7 @@
 
     if ((PackageLengthOp->Asl.ParseOpcode == PARSEOP_INTEGER)      ||
         (PackageLengthOp->Asl.ParseOpcode == PARSEOP_QWORDCONST)   ||
+        (PackageLengthOp->Asl.ParseOpcode == PARSEOP_ZERO)         ||
         (PackageLengthOp->Asl.ParseOpcode == PARSEOP_DEFAULT_ARG))
     {
         if (!PackageLength)
@@ -778,8 +779,11 @@
      * If the PackageLength is a constant <= 255, we can change the
      * AML opcode from VarPackage to a simple (ACPI 1.0) Package opcode.
      */
-    if ((Op->Asl.Child->Asl.ParseOpcode == PARSEOP_INTEGER) &&
-        (Op->Asl.Child->Asl.Value.Integer <= 255))
+    if (((Op->Asl.Child->Asl.ParseOpcode == PARSEOP_INTEGER) &&
+            (Op->Asl.Child->Asl.Value.Integer <= 255))  ||
+        (Op->Asl.Child->Asl.ParseOpcode == PARSEOP_ONE) ||
+        (Op->Asl.Child->Asl.ParseOpcode == PARSEOP_ONES)||
+        (Op->Asl.Child->Asl.ParseOpcode == PARSEOP_ZERO))
     {
         Op->Asl.AmlOpcode = AML_PACKAGE_OP;
         Op->Asl.ParseOpcode = PARSEOP_PACKAGE;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/compiler/aslpredef.c
--- a/head/sys/contrib/dev/acpica/compiler/aslpredef.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/compiler/aslpredef.c	Tue Dec 06 20:26:16 2011 +0200
@@ -100,30 +100,49 @@
     {{"_ATT",     0,      0}},
     {{"_BAS",     0,      0}},
     {{"_BM_",     0,      0}},
+    {{"_DBT",     0,      0}},  /* Acpi 5.0 */
     {{"_DEC",     0,      0}},
+    {{"_DPL",     0,      0}},  /* Acpi 5.0 */
+    {{"_DRS",     0,      0}},  /* Acpi 5.0 */
+    {{"_END",     0,      0}},  /* Acpi 5.0 */
+    {{"_FLC",     0,      0}},  /* Acpi 5.0 */
     {{"_GRA",     0,      0}},
     {{"_HE_",     0,      0}},
     {{"_INT",     0,      0}},
+    {{"_IOR",     0,      0}},  /* Acpi 5.0 */
     {{"_LEN",     0,      0}},
+    {{"_LIN",     0,      0}},  /* Acpi 5.0 */
     {{"_LL_",     0,      0}},
     {{"_MAF",     0,      0}},
     {{"_MAX",     0,      0}},
     {{"_MEM",     0,      0}},
     {{"_MIF",     0,      0}},
     {{"_MIN",     0,      0}},
+    {{"_MOD",     0,      0}},  /* Acpi 5.0 */
     {{"_MTP",     0,      0}},
+    {{"_PAR",     0,      0}},  /* Acpi 5.0 */
+    {{"_PHA",     0,      0}},  /* Acpi 5.0 */
+    {{"_PIN",     0,      0}},  /* Acpi 5.0 */
+    {{"_PPI",     0,      0}},  /* Acpi 5.0 */
+    {{"_POL",     0,      0}},  /* Acpi 5.0 */
     {{"_RBO",     0,      0}},
     {{"_RBW",     0,      0}},
     {{"_RNG",     0,      0}},
     {{"_RT_",     0,      0}},  /* Acpi 3.0 */
     {{"_RW_",     0,      0}},
+    {{"_RXL",     0,      0}},  /* Acpi 5.0 */
     {{"_SHR",     0,      0}},
     {{"_SIZ",     0,      0}},
+    {{"_SLV",     0,      0}},  /* Acpi 5.0 */
+    {{"_SPE",     0,      0}},  /* Acpi 5.0 */
+    {{"_STB",     0,      0}},  /* Acpi 5.0 */
     {{"_TRA",     0,      0}},
     {{"_TRS",     0,      0}},
     {{"_TSF",     0,      0}},  /* Acpi 3.0 */
     {{"_TTP",     0,      0}},
+    {{"_TXL",     0,      0}},  /* Acpi 5.0 */
     {{"_TYP",     0,      0}},
+    {{"_VEN",     0,      0}},  /* Acpi 5.0 */
     {{{0,0,0,0},  0,      0}}   /* Table terminator */
 };
 
@@ -658,6 +677,7 @@
         break;
 
     case PARSEOP_PACKAGE:
+    case PARSEOP_VAR_PACKAGE:
         ReturnBtype = ACPI_RTYPE_PACKAGE;
         break;
 
@@ -817,4 +837,3 @@
         ThisRtype <<= 1;    /* Next Rtype */
     }
 }
-
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/compiler/aslresource.c
--- a/head/sys/contrib/dev/acpica/compiler/aslresource.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/compiler/aslresource.c	Tue Dec 06 20:26:16 2011 +0200
@@ -437,13 +437,14 @@
 
 /*******************************************************************************
  *
- * FUNCTION:    RsCreateBitField
+ * FUNCTION:    RsCreateResourceField
  *
  * PARAMETERS:  Op              - Resource field node
  *              Name            - Name of the field (Used only to reference
  *                                the field in the ASL, not in the AML)
  *              ByteOffset      - Offset from the field start
  *              BitOffset       - Additional bit offset
+ *              BitLength       - Number of bits in the field
  *
  * RETURN:      None, sets fields within the input node
  *
@@ -454,46 +455,20 @@
  ******************************************************************************/
 
 void
-RsCreateBitField (
+RsCreateResourceField (
     ACPI_PARSE_OBJECT       *Op,
     char                    *Name,
     UINT32                  ByteOffset,
-    UINT32                  BitOffset)
+    UINT32                  BitOffset,
+    UINT32                  BitLength)
 {
 
-    Op->Asl.ExternalName      = Name;
-    Op->Asl.Value.Integer     = ((UINT64) ByteOffset * 8) + BitOffset;
-    Op->Asl.CompileFlags     |= (NODE_IS_RESOURCE_FIELD | NODE_IS_BIT_OFFSET);
-}
+    Op->Asl.ExternalName = Name;
+    Op->Asl.CompileFlags |= NODE_IS_RESOURCE_FIELD;
 
 
-/*******************************************************************************
- *
- * FUNCTION:    RsCreateByteField
- *
- * PARAMETERS:  Op              - Resource field node
- *              Name            - Name of the field (Used only to reference
- *                                the field in the ASL, not in the AML)
- *              ByteOffset      - Offset from the field start
- *
- * RETURN:      None, sets fields within the input node
- *
- * DESCRIPTION: Utility function to generate a named byte field within a
- *              resource descriptor.  Mark a node as 1) a field in a resource
- *              descriptor, and 2) set the value to be a BYTE offset
- *
- ******************************************************************************/
-
-void
-RsCreateByteField (
-    ACPI_PARSE_OBJECT       *Op,
-    char                    *Name,
-    UINT32                  ByteOffset)
-{
-
-    Op->Asl.ExternalName      = Name;
-    Op->Asl.Value.Integer     = ByteOffset;
-    Op->Asl.CompileFlags     |= NODE_IS_RESOURCE_FIELD;
+    Op->Asl.Value.Tag.BitOffset = (ByteOffset * 8) + BitOffset;
+    Op->Asl.Value.Tag.BitLength = BitLength;
 }
 
 
@@ -538,6 +513,29 @@
 }
 
 
+void
+RsSetFlagBits16 (
+    UINT16                  *Flags,
+    ACPI_PARSE_OBJECT       *Op,
+    UINT8                   Position,
+    UINT8                   DefaultBit)
+{
+
+    if (Op->Asl.ParseOpcode == PARSEOP_DEFAULT_ARG)
+    {
+        /* Use the default bit */
+
+        *Flags |= (DefaultBit << Position);
+    }
+    else
+    {
+        /* Use the bit specified in the initialization node */
+
+        *Flags |= (((UINT16) Op->Asl.Value.Integer) << Position);
+    }
+}
+
+
 /*******************************************************************************
  *
  * FUNCTION:    RsCompleteNodeAndGetNext
@@ -662,6 +660,11 @@
                     CurrentByteOffset);
         break;
 
+    case PARSEOP_FIXEDDMA:
+        Rnode = RsDoFixedDmaDescriptor (DescriptorTypeOp,
+                    CurrentByteOffset);
+        break;
+
     case PARSEOP_DWORDIO:
         Rnode = RsDoDwordIoDescriptor (DescriptorTypeOp,
                     CurrentByteOffset);
@@ -845,6 +848,31 @@
                     CurrentByteOffset);
         break;
 
+    case PARSEOP_GPIO_INT:
+        Rnode = RsDoGpioIntDescriptor (DescriptorTypeOp,
+                    CurrentByteOffset);
+        break;
+
+    case PARSEOP_GPIO_IO:
+        Rnode = RsDoGpioIoDescriptor (DescriptorTypeOp,
+                    CurrentByteOffset);
+        break;
+
+    case PARSEOP_I2C_SERIALBUS:
+        Rnode = RsDoI2cSerialBusDescriptor (DescriptorTypeOp,
+                    CurrentByteOffset);
+        break;
+
+    case PARSEOP_SPI_SERIALBUS:
+        Rnode = RsDoSpiSerialBusDescriptor (DescriptorTypeOp,
+                    CurrentByteOffset);
+        break;
+
+    case PARSEOP_UART_SERIALBUS:
+        Rnode = RsDoUartSerialBusDescriptor (DescriptorTypeOp,
+                    CurrentByteOffset);
+        break;
+
     case PARSEOP_DEFAULT_ARG:
         /* Just ignore any of these, they are used as fillers/placeholders */
         break;
@@ -1019,10 +1047,12 @@
     Op->Asl.ParseOpcode               = PARSEOP_BUFFER;
     Op->Asl.AmlOpcode                 = AML_BUFFER_OP;
     Op->Asl.CompileFlags              = NODE_AML_PACKAGE | NODE_IS_RESOURCE_DESC;
+    UtSetParseOpName (Op);
 
     BufferLengthOp->Asl.ParseOpcode   = PARSEOP_INTEGER;
     BufferLengthOp->Asl.Value.Integer = CurrentByteOffset;
     (void) OpcSetOptimalIntegerSize (BufferLengthOp);
+    UtSetParseOpName (BufferLengthOp);
 
     BufferOp->Asl.ParseOpcode         = PARSEOP_RAW_DATA;
     BufferOp->Asl.AmlOpcode           = AML_RAW_DATA_CHAIN;
@@ -1030,8 +1060,7 @@
     BufferOp->Asl.AmlLength           = CurrentByteOffset;
     BufferOp->Asl.Value.Buffer        = (UINT8 *) HeadRnode.Next;
     BufferOp->Asl.CompileFlags       |= NODE_IS_RESOURCE_DATA;
+    UtSetParseOpName (BufferOp);
 
     return;
 }
-
-
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/compiler/aslrestype1.c
--- a/head/sys/contrib/dev/acpica/compiler/aslrestype1.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/compiler/aslrestype1.c	Tue Dec 06 20:26:16 2011 +0200
@@ -179,7 +179,7 @@
         case 1: /* Min Address */
 
             Descriptor->Memory24.Minimum = (UINT16) InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_MINADDR,
+            RsCreateWordField (InitializerOp, ACPI_RESTAG_MINADDR,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Memory24.Minimum));
             MinOp = InitializerOp;
             break;
@@ -187,7 +187,7 @@
         case 2: /* Max Address */
 
             Descriptor->Memory24.Maximum = (UINT16) InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_MAXADDR,
+            RsCreateWordField (InitializerOp, ACPI_RESTAG_MAXADDR,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Memory24.Maximum));
             MaxOp = InitializerOp;
             break;
@@ -195,14 +195,14 @@
         case 3: /* Alignment */
 
             Descriptor->Memory24.Alignment = (UINT16) InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_ALIGNMENT,
+            RsCreateWordField (InitializerOp, ACPI_RESTAG_ALIGNMENT,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Memory24.Alignment));
             break;
 
         case 4: /* Length */
 
             Descriptor->Memory24.AddressLength = (UINT16) InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_LENGTH,
+            RsCreateWordField (InitializerOp, ACPI_RESTAG_LENGTH,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Memory24.AddressLength));
             LengthOp = InitializerOp;
             break;
@@ -286,7 +286,7 @@
         case 1:  /* Min Address */
 
             Descriptor->Memory32.Minimum = (UINT32) InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_MINADDR,
+            RsCreateDwordField (InitializerOp, ACPI_RESTAG_MINADDR,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Memory32.Minimum));
             MinOp = InitializerOp;
             break;
@@ -294,7 +294,7 @@
         case 2: /* Max Address */
 
             Descriptor->Memory32.Maximum = (UINT32) InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_MAXADDR,
+            RsCreateDwordField (InitializerOp, ACPI_RESTAG_MAXADDR,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Memory32.Maximum));
             MaxOp = InitializerOp;
             break;
@@ -302,7 +302,7 @@
         case 3: /* Alignment */
 
             Descriptor->Memory32.Alignment = (UINT32) InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_ALIGNMENT,
+            RsCreateDwordField (InitializerOp, ACPI_RESTAG_ALIGNMENT,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Memory32.Alignment));
             AlignOp = InitializerOp;
             break;
@@ -310,7 +310,7 @@
         case 4: /* Length */
 
             Descriptor->Memory32.AddressLength = (UINT32) InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_LENGTH,
+            RsCreateDwordField (InitializerOp, ACPI_RESTAG_LENGTH,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Memory32.AddressLength));
             LengthOp = InitializerOp;
             break;
@@ -390,14 +390,14 @@
         case 1: /* Address */
 
             Descriptor->FixedMemory32.Address = (UINT32) InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_BASEADDRESS,
+            RsCreateDwordField (InitializerOp, ACPI_RESTAG_BASEADDRESS,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (FixedMemory32.Address));
             break;
 
         case 2: /* Length */
 
             Descriptor->FixedMemory32.AddressLength = (UINT32) InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_LENGTH,
+            RsCreateDwordField (InitializerOp, ACPI_RESTAG_LENGTH,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (FixedMemory32.AddressLength));
             break;
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/compiler/aslrestype1i.c
--- a/head/sys/contrib/dev/acpica/compiler/aslrestype1i.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/compiler/aslrestype1i.c	Tue Dec 06 20:26:16 2011 +0200
@@ -53,6 +53,7 @@
  * This module contains the I/O-related small resource descriptors:
  *
  * DMA
+ * FixedDMA
  * FixedIO
  * IO
  * IRQ
@@ -102,8 +103,8 @@
         case 0: /* DMA type */
 
             RsSetFlagBits (&Descriptor->Dma.Flags, InitializerOp, 5, 0);
-            RsCreateBitField (InitializerOp, ACPI_RESTAG_DMATYPE,
-                CurrentByteOffset + ASL_RESDESC_OFFSET (Dma.Flags), 5);
+            RsCreateMultiBitField (InitializerOp, ACPI_RESTAG_DMATYPE,
+                CurrentByteOffset + ASL_RESDESC_OFFSET (Dma.Flags), 5, 2);
             break;
 
         case 1: /* Bus Master */
@@ -116,8 +117,8 @@
         case 2: /* Xfer Type (transfer width) */
 
             RsSetFlagBits (&Descriptor->Dma.Flags, InitializerOp, 0, 0);
-            RsCreateBitField (InitializerOp, ACPI_RESTAG_XFERTYPE,
-                CurrentByteOffset + ASL_RESDESC_OFFSET (Dma.Flags), 0);
+            RsCreateMultiBitField (InitializerOp, ACPI_RESTAG_XFERTYPE,
+                CurrentByteOffset + ASL_RESDESC_OFFSET (Dma.Flags), 0, 2);
             break;
 
         case 3: /* Name */
@@ -182,6 +183,81 @@
 
 /*******************************************************************************
  *
+ * FUNCTION:    RsDoFixedDmaDescriptor
+ *
+ * PARAMETERS:  Op                  - Parent resource descriptor parse node
+ *              CurrentByteOffset   - Offset into the resource template AML
+ *                                    buffer (to track references to the desc)
+ *
+ * RETURN:      Completed resource node
+ *
+ * DESCRIPTION: Construct a short "FixedDMA" descriptor
+ *
+ ******************************************************************************/
+
+ASL_RESOURCE_NODE *
+RsDoFixedDmaDescriptor (
+    ACPI_PARSE_OBJECT       *Op,
+    UINT32                  CurrentByteOffset)
+{
+    AML_RESOURCE            *Descriptor;
+    ACPI_PARSE_OBJECT       *InitializerOp;
+    ASL_RESOURCE_NODE       *Rnode;
+    UINT32                  i;
+
+
+    InitializerOp = Op->Asl.Child;
+    Rnode = RsAllocateResourceNode (sizeof (AML_RESOURCE_FIXED_DMA));
+
+    Descriptor = Rnode->Buffer;
+    Descriptor->FixedDma.DescriptorType =
+        ACPI_RESOURCE_NAME_FIXED_DMA | ASL_RDESC_FIXED_DMA_SIZE;
+
+    /* Process all child initialization nodes */
+
+    for (i = 0; InitializerOp; i++)
+    {
+        switch (i)
+        {
+        case 0: /* DMA Request Lines [WORD] (_DMA) */
+
+            Descriptor->FixedDma.RequestLines = (UINT16) InitializerOp->Asl.Value.Integer;
+            RsCreateWordField (InitializerOp, ACPI_RESTAG_DMA,
+                CurrentByteOffset + ASL_RESDESC_OFFSET (FixedDma.RequestLines));
+            break;
+
+        case 1: /* DMA Channel [WORD] (_TYP) */
+
+            Descriptor->FixedDma.Channels = (UINT16) InitializerOp->Asl.Value.Integer;
+            RsCreateWordField (InitializerOp, ACPI_RESTAG_DMATYPE,
+                CurrentByteOffset + ASL_RESDESC_OFFSET (FixedDma.Channels));
+            break;
+
+        case 2: /* Transfer Width [BYTE] (_SIZ) */
+
+            Descriptor->FixedDma.Width = (UINT8) InitializerOp->Asl.Value.Integer;
+            RsCreateByteField (InitializerOp, ACPI_RESTAG_XFERTYPE,
+                CurrentByteOffset + ASL_RESDESC_OFFSET (FixedDma.Width));
+            break;
+
+        case 3: /* Descriptor Name (optional) */
+
+            UtAttachNamepathToOwner (Op, InitializerOp);
+            break;
+
+        default:    /* Ignore any extra nodes */
+            break;
+        }
+
+        InitializerOp = RsCompleteNodeAndGetNext (InitializerOp);
+    }
+
+    return (Rnode);
+}
+
+
+/*******************************************************************************
+ *
  * FUNCTION:    RsDoFixedIoDescriptor
  *
  * PARAMETERS:  Op                  - Parent resource descriptor parse node
@@ -223,7 +299,7 @@
 
             Descriptor->FixedIo.Address =
                 (UINT16) InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_BASEADDRESS,
+            RsCreateWordField (InitializerOp, ACPI_RESTAG_BASEADDRESS,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (FixedIo.Address));
             AddressOp = InitializerOp;
             break;
@@ -314,7 +390,7 @@
 
             Descriptor->Io.Minimum =
                 (UINT16) InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_MINADDR,
+            RsCreateWordField (InitializerOp, ACPI_RESTAG_MINADDR,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Io.Minimum));
             MinOp = InitializerOp;
             break;
@@ -323,7 +399,7 @@
 
             Descriptor->Io.Maximum =
                 (UINT16) InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_MAXADDR,
+            RsCreateWordField (InitializerOp, ACPI_RESTAG_MAXADDR,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Io.Maximum));
             MaxOp = InitializerOp;
             break;
@@ -480,7 +556,7 @@
 
                 /* Create a named field at the start of the list */
 
-                RsCreateByteField (InitializerOp, ACPI_RESTAG_INTERRUPT,
+                RsCreateWordField (InitializerOp, ACPI_RESTAG_INTERRUPT,
                     CurrentByteOffset + ASL_RESDESC_OFFSET (Irq.IrqMask));
             }
             break;
@@ -580,7 +656,7 @@
 
                 /* Create a named field at the start of the list */
 
-                RsCreateByteField (InitializerOp, ACPI_RESTAG_INTERRUPT,
+                RsCreateWordField (InitializerOp, ACPI_RESTAG_INTERRUPT,
                     CurrentByteOffset + ASL_RESDESC_OFFSET (Irq.IrqMask));
             }
             break;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/compiler/aslrestype2.c
--- a/head/sys/contrib/dev/acpica/compiler/aslrestype2.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/compiler/aslrestype2.c	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,3 @@
-
 /******************************************************************************
  *
  * Module Name: aslrestype2 - Miscellaneous Large resource descriptors
@@ -120,7 +119,7 @@
         case 3: /* Register Address */
 
             Descriptor->GenericReg.Address = InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_ADDRESS,
+            RsCreateQwordField (InitializerOp, ACPI_RESTAG_ADDRESS,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (GenericReg.Address));
             break;
 
@@ -354,7 +353,7 @@
 
                 /* Create a named field at the start of the list */
 
-                RsCreateByteField (InitializerOp, ACPI_RESTAG_INTERRUPT,
+                RsCreateDwordField (InitializerOp, ACPI_RESTAG_INTERRUPT,
                     CurrentByteOffset +
                     ASL_RESDESC_OFFSET (ExtendedIrq.Interrupts[0]));
             }
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/compiler/aslrestype2d.c
--- a/head/sys/contrib/dev/acpica/compiler/aslrestype2d.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/compiler/aslrestype2d.c	Tue Dec 06 20:26:16 2011 +0200
@@ -144,15 +144,15 @@
         case 4: /* Range Type */
 
             RsSetFlagBits (&Descriptor->Address32.SpecificFlags, InitializerOp, 0, 3);
-            RsCreateBitField (InitializerOp, ACPI_RESTAG_RANGETYPE,
-                CurrentByteOffset + ASL_RESDESC_OFFSET (Address32.SpecificFlags), 0);
+            RsCreateMultiBitField (InitializerOp, ACPI_RESTAG_RANGETYPE,
+                CurrentByteOffset + ASL_RESDESC_OFFSET (Address32.SpecificFlags), 0, 2);
             break;
 
         case 5: /* Address Granularity */
 
             Descriptor->Address32.Granularity =
                 (UINT32) InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_GRANULARITY,
+            RsCreateDwordField (InitializerOp, ACPI_RESTAG_GRANULARITY,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Address32.Granularity));
             GranOp = InitializerOp;
             break;
@@ -161,7 +161,7 @@
 
             Descriptor->Address32.Minimum =
                 (UINT32) InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_MINADDR,
+            RsCreateDwordField (InitializerOp, ACPI_RESTAG_MINADDR,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Address32.Minimum));
             MinOp = InitializerOp;
             break;
@@ -170,7 +170,7 @@
 
             Descriptor->Address32.Maximum =
                 (UINT32) InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_MAXADDR,
+            RsCreateDwordField (InitializerOp, ACPI_RESTAG_MAXADDR,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Address32.Maximum));
             MaxOp = InitializerOp;
             break;
@@ -179,7 +179,7 @@
 
             Descriptor->Address32.TranslationOffset =
                 (UINT32) InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_TRANSLATION,
+            RsCreateDwordField (InitializerOp, ACPI_RESTAG_TRANSLATION,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Address32.TranslationOffset));
             break;
 
@@ -187,7 +187,7 @@
 
             Descriptor->Address32.AddressLength =
                 (UINT32) InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_LENGTH,
+            RsCreateDwordField (InitializerOp, ACPI_RESTAG_LENGTH,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Address32.AddressLength));
             LengthOp = InitializerOp;
             break;
@@ -376,8 +376,8 @@
         case 4: /* Memory Type */
 
             RsSetFlagBits (&Descriptor->Address32.SpecificFlags, InitializerOp, 1, 0);
-            RsCreateBitField (InitializerOp, ACPI_RESTAG_MEMTYPE,
-                CurrentByteOffset + ASL_RESDESC_OFFSET (Address32.SpecificFlags), 1);
+            RsCreateMultiBitField (InitializerOp, ACPI_RESTAG_MEMTYPE,
+                CurrentByteOffset + ASL_RESDESC_OFFSET (Address32.SpecificFlags), 1, 2);
             break;
 
         case 5: /* Read/Write Type */
@@ -391,7 +391,7 @@
 
             Descriptor->Address32.Granularity =
                 (UINT32) InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_GRANULARITY,
+            RsCreateDwordField (InitializerOp, ACPI_RESTAG_GRANULARITY,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Address32.Granularity));
             GranOp = InitializerOp;
             break;
@@ -400,7 +400,7 @@
 
             Descriptor->Address32.Minimum =
                 (UINT32) InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_MINADDR,
+            RsCreateDwordField (InitializerOp, ACPI_RESTAG_MINADDR,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Address32.Minimum));
             MinOp = InitializerOp;
             break;
@@ -409,7 +409,7 @@
 
             Descriptor->Address32.Maximum =
                 (UINT32) InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_MAXADDR,
+            RsCreateDwordField (InitializerOp, ACPI_RESTAG_MAXADDR,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Address32.Maximum));
             MaxOp = InitializerOp;
             break;
@@ -418,7 +418,7 @@
 
             Descriptor->Address32.TranslationOffset =
                 (UINT32) InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_TRANSLATION,
+            RsCreateDwordField (InitializerOp, ACPI_RESTAG_TRANSLATION,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Address32.TranslationOffset));
             break;
 
@@ -426,7 +426,7 @@
 
             Descriptor->Address32.AddressLength =
                 (UINT32) InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_LENGTH,
+            RsCreateDwordField (InitializerOp, ACPI_RESTAG_LENGTH,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Address32.AddressLength));
             LengthOp = InitializerOp;
             break;
@@ -488,8 +488,8 @@
         case 14: /* Address Range */
 
             RsSetFlagBits (&Descriptor->Address32.SpecificFlags, InitializerOp, 3, 0);
-            RsCreateBitField (InitializerOp, ACPI_RESTAG_MEMATTRIBUTES,
-                CurrentByteOffset + ASL_RESDESC_OFFSET (Address32.SpecificFlags), 3);
+            RsCreateMultiBitField (InitializerOp, ACPI_RESTAG_MEMATTRIBUTES,
+                CurrentByteOffset + ASL_RESDESC_OFFSET (Address32.SpecificFlags), 3, 2);
             break;
 
         case 15: /* Type */
@@ -623,7 +623,7 @@
 
             Descriptor->Address32.Granularity =
                 (UINT32) InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_GRANULARITY,
+            RsCreateDwordField (InitializerOp, ACPI_RESTAG_GRANULARITY,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Address32.Granularity));
             GranOp = InitializerOp;
             break;
@@ -632,7 +632,7 @@
 
             Descriptor->Address32.Minimum =
                 (UINT32) InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_MINADDR,
+            RsCreateDwordField (InitializerOp, ACPI_RESTAG_MINADDR,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Address32.Minimum));
             MinOp = InitializerOp;
             break;
@@ -641,7 +641,7 @@
 
             Descriptor->Address32.Maximum =
                 (UINT32) InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_MAXADDR,
+            RsCreateDwordField (InitializerOp, ACPI_RESTAG_MAXADDR,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Address32.Maximum));
             MaxOp = InitializerOp;
             break;
@@ -650,7 +650,7 @@
 
             Descriptor->Address32.TranslationOffset =
                 (UINT32) InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_TRANSLATION,
+            RsCreateDwordField (InitializerOp, ACPI_RESTAG_TRANSLATION,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Address32.TranslationOffset));
             break;
 
@@ -658,7 +658,7 @@
 
             Descriptor->Address32.AddressLength =
                 (UINT32) InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_LENGTH,
+            RsCreateDwordField (InitializerOp, ACPI_RESTAG_LENGTH,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Address32.AddressLength));
             LengthOp = InitializerOp;
             break;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/compiler/aslrestype2e.c
--- a/head/sys/contrib/dev/acpica/compiler/aslrestype2e.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/compiler/aslrestype2e.c	Tue Dec 06 20:26:16 2011 +0200
@@ -136,14 +136,14 @@
         case 4: /* Range Type */
 
             RsSetFlagBits (&Descriptor->ExtAddress64.SpecificFlags, InitializerOp, 0, 3);
-            RsCreateBitField (InitializerOp, ACPI_RESTAG_RANGETYPE,
-                CurrentByteOffset + ASL_RESDESC_OFFSET (ExtAddress64.SpecificFlags), 0);
+            RsCreateMultiBitField (InitializerOp, ACPI_RESTAG_RANGETYPE,
+                CurrentByteOffset + ASL_RESDESC_OFFSET (ExtAddress64.SpecificFlags), 0, 2);
             break;
 
         case 5: /* Address Granularity */
 
             Descriptor->ExtAddress64.Granularity = InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_GRANULARITY,
+            RsCreateQwordField (InitializerOp, ACPI_RESTAG_GRANULARITY,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (ExtAddress64.Granularity));
             GranOp = InitializerOp;
            break;
@@ -151,7 +151,7 @@
         case 6: /* Address Min */
 
             Descriptor->ExtAddress64.Minimum = InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_MINADDR,
+            RsCreateQwordField (InitializerOp, ACPI_RESTAG_MINADDR,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (ExtAddress64.Minimum));
             MinOp = InitializerOp;
             break;
@@ -159,7 +159,7 @@
         case 7: /* Address Max */
 
             Descriptor->ExtAddress64.Maximum = InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_MAXADDR,
+            RsCreateQwordField (InitializerOp, ACPI_RESTAG_MAXADDR,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (ExtAddress64.Maximum));
             MaxOp = InitializerOp;
             break;
@@ -167,14 +167,14 @@
         case 8: /* Translation Offset */
 
             Descriptor->ExtAddress64.TranslationOffset = InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_TRANSLATION,
+            RsCreateQwordField (InitializerOp, ACPI_RESTAG_TRANSLATION,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (ExtAddress64.TranslationOffset));
             break;
 
         case 9: /* Address Length */
 
             Descriptor->ExtAddress64.AddressLength = InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_LENGTH,
+            RsCreateQwordField (InitializerOp, ACPI_RESTAG_LENGTH,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (ExtAddress64.AddressLength));
             LengthOp = InitializerOp;
             break;
@@ -182,7 +182,7 @@
         case 10: /* Type-Specific Attributes */
 
             Descriptor->ExtAddress64.TypeSpecific = InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_TYPESPECIFICATTRIBUTES,
+            RsCreateQwordField (InitializerOp, ACPI_RESTAG_TYPESPECIFICATTRIBUTES,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (ExtAddress64.TypeSpecific));
             break;
 
@@ -309,8 +309,8 @@
         case 4: /* Memory Type */
 
             RsSetFlagBits (&Descriptor->ExtAddress64.SpecificFlags, InitializerOp, 1, 0);
-            RsCreateBitField (InitializerOp, ACPI_RESTAG_MEMTYPE,
-                CurrentByteOffset + ASL_RESDESC_OFFSET (ExtAddress64.SpecificFlags), 1);
+            RsCreateMultiBitField (InitializerOp, ACPI_RESTAG_MEMTYPE,
+                CurrentByteOffset + ASL_RESDESC_OFFSET (ExtAddress64.SpecificFlags), 1, 2);
             break;
 
         case 5: /* Read/Write Type */
@@ -323,7 +323,7 @@
         case 6: /* Address Granularity */
 
             Descriptor->ExtAddress64.Granularity = InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_GRANULARITY,
+            RsCreateQwordField (InitializerOp, ACPI_RESTAG_GRANULARITY,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (ExtAddress64.Granularity));
             GranOp = InitializerOp;
             break;
@@ -331,7 +331,7 @@
         case 7: /* Min Address */
 
             Descriptor->ExtAddress64.Minimum = InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_MINADDR,
+            RsCreateQwordField (InitializerOp, ACPI_RESTAG_MINADDR,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (ExtAddress64.Minimum));
             MinOp = InitializerOp;
             break;
@@ -339,7 +339,7 @@
         case 8: /* Max Address */
 
             Descriptor->ExtAddress64.Maximum = InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_MAXADDR,
+            RsCreateQwordField (InitializerOp, ACPI_RESTAG_MAXADDR,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (ExtAddress64.Maximum));
             MaxOp = InitializerOp;
             break;
@@ -347,14 +347,14 @@
         case 9: /* Translation Offset */
 
             Descriptor->ExtAddress64.TranslationOffset = InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_TRANSLATION,
+            RsCreateQwordField (InitializerOp, ACPI_RESTAG_TRANSLATION,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (ExtAddress64.TranslationOffset));
             break;
 
         case 10: /* Address Length */
 
             Descriptor->ExtAddress64.AddressLength = InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_LENGTH,
+            RsCreateQwordField (InitializerOp, ACPI_RESTAG_LENGTH,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (ExtAddress64.AddressLength));
             LengthOp = InitializerOp;
             break;
@@ -362,7 +362,7 @@
         case 11: /* Type-Specific Attributes */
 
             Descriptor->ExtAddress64.TypeSpecific = InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_TYPESPECIFICATTRIBUTES,
+            RsCreateQwordField (InitializerOp, ACPI_RESTAG_TYPESPECIFICATTRIBUTES,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (ExtAddress64.TypeSpecific));
             break;
 
@@ -375,8 +375,8 @@
         case 13: /* Address Range */
 
             RsSetFlagBits (&Descriptor->ExtAddress64.SpecificFlags, InitializerOp, 3, 0);
-            RsCreateBitField (InitializerOp, ACPI_RESTAG_MEMATTRIBUTES,
-                CurrentByteOffset + ASL_RESDESC_OFFSET (ExtAddress64.SpecificFlags), 3);
+            RsCreateMultiBitField (InitializerOp, ACPI_RESTAG_MEMATTRIBUTES,
+                CurrentByteOffset + ASL_RESDESC_OFFSET (ExtAddress64.SpecificFlags), 3, 2);
             break;
 
         case 14: /* Type */
@@ -501,7 +501,7 @@
         case 6: /* Address Granularity */
 
             Descriptor->ExtAddress64.Granularity = InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_GRANULARITY,
+            RsCreateQwordField (InitializerOp, ACPI_RESTAG_GRANULARITY,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (ExtAddress64.Granularity));
             GranOp = InitializerOp;
             break;
@@ -509,7 +509,7 @@
         case 7: /* Min Address */
 
             Descriptor->ExtAddress64.Minimum = InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_MINADDR,
+            RsCreateQwordField (InitializerOp, ACPI_RESTAG_MINADDR,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (ExtAddress64.Minimum));
             MinOp = InitializerOp;
             break;
@@ -517,7 +517,7 @@
         case 8: /* Max Address */
 
             Descriptor->ExtAddress64.Maximum = InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_MAXADDR,
+            RsCreateQwordField (InitializerOp, ACPI_RESTAG_MAXADDR,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (ExtAddress64.Maximum));
             MaxOp = InitializerOp;
             break;
@@ -525,14 +525,14 @@
         case 9: /* Translation Offset */
 
             Descriptor->ExtAddress64.TranslationOffset = InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_TRANSLATION,
+            RsCreateQwordField (InitializerOp, ACPI_RESTAG_TRANSLATION,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (ExtAddress64.TranslationOffset));
             break;
 
         case 10: /* Address Length */
 
             Descriptor->ExtAddress64.AddressLength = InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_LENGTH,
+            RsCreateQwordField (InitializerOp, ACPI_RESTAG_LENGTH,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (ExtAddress64.AddressLength));
             LengthOp = InitializerOp;
             break;
@@ -540,7 +540,7 @@
         case 11: /* Type-Specific Attributes */
 
             Descriptor->ExtAddress64.TypeSpecific = InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_TYPESPECIFICATTRIBUTES,
+            RsCreateQwordField (InitializerOp, ACPI_RESTAG_TYPESPECIFICATTRIBUTES,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (ExtAddress64.TypeSpecific));
             break;
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/compiler/aslrestype2q.c
--- a/head/sys/contrib/dev/acpica/compiler/aslrestype2q.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/compiler/aslrestype2q.c	Tue Dec 06 20:26:16 2011 +0200
@@ -144,14 +144,14 @@
         case 4: /* Range Type */
 
             RsSetFlagBits (&Descriptor->Address64.SpecificFlags, InitializerOp, 0, 3);
-            RsCreateBitField (InitializerOp, ACPI_RESTAG_RANGETYPE,
-                CurrentByteOffset + ASL_RESDESC_OFFSET (Address64.SpecificFlags), 0);
+            RsCreateMultiBitField (InitializerOp, ACPI_RESTAG_RANGETYPE,
+                CurrentByteOffset + ASL_RESDESC_OFFSET (Address64.SpecificFlags), 0, 2);
             break;
 
         case 5: /* Address Granularity */
 
             Descriptor->Address64.Granularity = InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_GRANULARITY,
+            RsCreateQwordField (InitializerOp, ACPI_RESTAG_GRANULARITY,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Address64.Granularity));
             GranOp = InitializerOp;
             break;
@@ -159,7 +159,7 @@
         case 6: /* Address Min */
 
             Descriptor->Address64.Minimum = InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_MINADDR,
+            RsCreateQwordField (InitializerOp, ACPI_RESTAG_MINADDR,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Address64.Minimum));
             MinOp = InitializerOp;
             break;
@@ -167,7 +167,7 @@
         case 7: /* Address Max */
 
             Descriptor->Address64.Maximum = InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_MAXADDR,
+            RsCreateQwordField (InitializerOp, ACPI_RESTAG_MAXADDR,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Address64.Maximum));
             MaxOp = InitializerOp;
             break;
@@ -182,7 +182,7 @@
         case 9: /* Address Length */
 
             Descriptor->Address64.AddressLength = InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_LENGTH,
+            RsCreateQwordField (InitializerOp, ACPI_RESTAG_LENGTH,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Address64.AddressLength));
             LengthOp = InitializerOp;
             break;
@@ -366,8 +366,8 @@
         case 4: /* Memory Type */
 
             RsSetFlagBits (&Descriptor->Address64.SpecificFlags, InitializerOp, 1, 0);
-            RsCreateBitField (InitializerOp, ACPI_RESTAG_MEMTYPE,
-                CurrentByteOffset + ASL_RESDESC_OFFSET (Address64.SpecificFlags), 1);
+            RsCreateMultiBitField (InitializerOp, ACPI_RESTAG_MEMTYPE,
+                CurrentByteOffset + ASL_RESDESC_OFFSET (Address64.SpecificFlags), 1, 2);
             break;
 
         case 5: /* Read/Write Type */
@@ -380,7 +380,7 @@
         case 6: /* Address Granularity */
 
             Descriptor->Address64.Granularity = InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_GRANULARITY,
+            RsCreateQwordField (InitializerOp, ACPI_RESTAG_GRANULARITY,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Address64.Granularity));
             GranOp = InitializerOp;
             break;
@@ -388,7 +388,7 @@
         case 7: /* Min Address */
 
             Descriptor->Address64.Minimum = InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_MINADDR,
+            RsCreateQwordField (InitializerOp, ACPI_RESTAG_MINADDR,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Address64.Minimum));
             MinOp = InitializerOp;
             break;
@@ -396,7 +396,7 @@
         case 8: /* Max Address */
 
             Descriptor->Address64.Maximum = InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_MAXADDR,
+            RsCreateQwordField (InitializerOp, ACPI_RESTAG_MAXADDR,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Address64.Maximum));
             MaxOp = InitializerOp;
             break;
@@ -404,14 +404,14 @@
         case 9: /* Translation Offset */
 
             Descriptor->Address64.TranslationOffset = InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_TRANSLATION,
+            RsCreateQwordField (InitializerOp, ACPI_RESTAG_TRANSLATION,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Address64.TranslationOffset));
             break;
 
         case 10: /* Address Length */
 
             Descriptor->Address64.AddressLength = InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_LENGTH,
+            RsCreateQwordField (InitializerOp, ACPI_RESTAG_LENGTH,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Address64.AddressLength));
             LengthOp = InitializerOp;
             break;
@@ -473,8 +473,8 @@
         case 14: /* Address Range */
 
             RsSetFlagBits (&Descriptor->Address64.SpecificFlags, InitializerOp, 3, 0);
-            RsCreateBitField (InitializerOp, ACPI_RESTAG_MEMATTRIBUTES,
-                CurrentByteOffset + ASL_RESDESC_OFFSET (Address64.SpecificFlags), 3);
+            RsCreateMultiBitField (InitializerOp, ACPI_RESTAG_MEMATTRIBUTES,
+                CurrentByteOffset + ASL_RESDESC_OFFSET (Address64.SpecificFlags), 3, 2);
             break;
 
         case 15: /* Type */
@@ -607,7 +607,7 @@
         case 6: /* Address Granularity */
 
             Descriptor->Address64.Granularity = InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_GRANULARITY,
+            RsCreateQwordField (InitializerOp, ACPI_RESTAG_GRANULARITY,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Address64.Granularity));
             GranOp = InitializerOp;
             break;
@@ -615,7 +615,7 @@
         case 7: /* Min Address */
 
             Descriptor->Address64.Minimum = InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_MINADDR,
+            RsCreateQwordField (InitializerOp, ACPI_RESTAG_MINADDR,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Address64.Minimum));
             MinOp = InitializerOp;
             break;
@@ -623,7 +623,7 @@
         case 8: /* Max Address */
 
             Descriptor->Address64.Maximum = InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_MAXADDR,
+            RsCreateQwordField (InitializerOp, ACPI_RESTAG_MAXADDR,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Address64.Maximum));
             MaxOp = InitializerOp;
             break;
@@ -631,14 +631,14 @@
         case 9: /* Translation Offset */
 
             Descriptor->Address64.TranslationOffset = InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_TRANSLATION,
+            RsCreateQwordField (InitializerOp, ACPI_RESTAG_TRANSLATION,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Address64.TranslationOffset));
             break;
 
         case 10: /* Address Length */
 
             Descriptor->Address64.AddressLength = InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_LENGTH,
+            RsCreateQwordField (InitializerOp, ACPI_RESTAG_LENGTH,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Address64.AddressLength));
             LengthOp = InitializerOp;
             break;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/compiler/aslrestype2s.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/sys/contrib/dev/acpica/compiler/aslrestype2s.c	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,1187 @@
+/******************************************************************************
+ *
+ * Module Name: aslrestype2s - Serial Large resource descriptors
+ *
+ *****************************************************************************/
+
+/*
+ * Copyright (C) 2000 - 2011, Intel Corp.
+ * 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.
+ * 3. Neither the names of the above-listed copyright holders nor the names
+ *    of any contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ * Alternatively, this software may be distributed under the terms of the
+ * GNU General Public License ("GPL") version 2 as published by the Free
+ * Software Foundation.
+ *
+ * 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.
+ */
+
+
+#include <contrib/dev/acpica/compiler/aslcompiler.h>
+#include "aslcompiler.y.h"
+#include <contrib/dev/acpica/include/amlcode.h>
+
+#define _COMPONENT          ACPI_COMPILER
+        ACPI_MODULE_NAME    ("aslrestype2s")
+
+
+static UINT16
+RsGetBufferDataLength (
+    ACPI_PARSE_OBJECT       *InitializerOp);
+
+static UINT16
+RsGetInterruptDataLength (
+    ACPI_PARSE_OBJECT       *InitializerOp);
+
+static BOOLEAN
+RsGetVendorData (
+    ACPI_PARSE_OBJECT       *InitializerOp,
+    UINT8                   *VendorData,
+    ACPI_SIZE               DescriptorOffset);
+
+/*
+ * This module contains descriptors for serial buses and GPIO:
+ *
+ * GpioInt
+ * GpioIo
+ * I2cSerialBus
+ * SpiSerialBus
+ * UartSerialBus
+ */
+
+
+/*******************************************************************************
+ *
+ * FUNCTION:    RsGetBufferDataLength
+ *
+ * PARAMETERS:  InitializerOp       - Current parse op, start of the resource
+ *                                    descriptor
+ *
+ * RETURN:      Length of the data buffer
+ *
+ * DESCRIPTION: Get the length of a RawDataBuffer, used for vendor data.
+ *
+ ******************************************************************************/
+
+static UINT16
+RsGetBufferDataLength (
+    ACPI_PARSE_OBJECT       *InitializerOp)
+{
+    UINT16                  ExtraDataSize = 0;
+    ACPI_PARSE_OBJECT       *DataList;
+
+
+    /* Find the byte-initializer list */
+
+    while (InitializerOp)
+    {
+        if (InitializerOp->Asl.ParseOpcode == PARSEOP_DATABUFFER)
+        {
+            /* First child is the optional length (ignore it here) */
+
+            DataList = InitializerOp->Asl.Child;
+            DataList = ASL_GET_PEER_NODE (DataList);
+
+            /* Count the data items (each one is a byte of data) */
+
+            while (DataList)
+            {
+                ExtraDataSize++;
+                DataList = ASL_GET_PEER_NODE (DataList);
+            }
+
+            return (ExtraDataSize);
+        }
+
+        InitializerOp = ASL_GET_PEER_NODE (InitializerOp);
+    }
+
+    return (ExtraDataSize);
+}
+
+
+/*******************************************************************************
+ *
+ * FUNCTION:    RsGetInterruptDataLength
+ *
+ * PARAMETERS:  InitializerOp       - Current parse op, start of the resource
+ *                                    descriptor
+ *
+ * RETURN:      Length of the interrupt data list
+ *
+ * DESCRIPTION: Get the length of a list of interrupt DWORDs for the GPIO
+ *              descriptors.
+ *
+ ******************************************************************************/
+
+static UINT16
+RsGetInterruptDataLength (
+    ACPI_PARSE_OBJECT       *InitializerOp)
+{
+    UINT16                  InterruptLength;
+    UINT32                  i;
+
+
+    /* Count the interrupt numbers */
+
+    InterruptLength = 0;
+    for (i = 0; InitializerOp; i++)
+    {
+        InitializerOp = ASL_GET_PEER_NODE (InitializerOp);
+
+        /* Interrupt list starts at offset 10 (Gpio descriptors) */
+
+        if (i >= 10)
+        {
+            InterruptLength += 2;
+        }
+    }
+
+    return (InterruptLength);
+}
+
+
+/*******************************************************************************
+ *
+ * FUNCTION:    RsGetVendorData
+ *
+ * PARAMETERS:  InitializerOp       - Current parse op, start of the resource
+ *                                    descriptor.
+ *              VendorData          - Where the vendor data is returned
+ *              DescriptorOffset    - Where vendor data begins in descriptor
+ *
+ * RETURN:      TRUE if valid vendor data was returned, FALSE otherwise.
+ *
+ * DESCRIPTION: Extract the vendor data and construct a vendor data buffer.
+ *
+ ******************************************************************************/
+
+static BOOLEAN
+RsGetVendorData (
+    ACPI_PARSE_OBJECT       *InitializerOp,
+    UINT8                   *VendorData,
+    ACPI_SIZE               DescriptorOffset)
+{
+    ACPI_PARSE_OBJECT       *BufferOp;
+    UINT32                  SpecifiedLength = ACPI_UINT32_MAX;
+    UINT16                  ActualLength = 0;
+
+
+    /* VendorData field is always optional */
+
+    if (InitializerOp->Asl.ParseOpcode == PARSEOP_DEFAULT_ARG)
+    {
+        return (FALSE);
+    }
+
+    BufferOp = InitializerOp->Asl.Child;
+    if (!BufferOp)
+    {
+        AslError (ASL_ERROR, ASL_MSG_SYNTAX, InitializerOp, "");
+        return (FALSE);
+    }
+
+    /* First child is the optional buffer length (WORD) */
+
+    if (BufferOp->Asl.ParseOpcode != PARSEOP_DEFAULT_ARG)
+    {
+        SpecifiedLength = (UINT16) BufferOp->Asl.Value.Integer;
+    }
+
+    /* Insert field tag _VEN */
+
+    RsCreateByteField (InitializerOp, ACPI_RESTAG_VENDORDATA,
+        (UINT16) DescriptorOffset);
+
+    /* Walk the list of buffer initializers (each is one byte) */
+
+    BufferOp = RsCompleteNodeAndGetNext (BufferOp);
+    if (BufferOp->Asl.ParseOpcode != PARSEOP_DEFAULT_ARG)
+    {
+        while (BufferOp)
+        {
+            *VendorData = (UINT8) BufferOp->Asl.Value.Integer;
+            VendorData++;
+            ActualLength++;
+            BufferOp = RsCompleteNodeAndGetNext (BufferOp);
+        }
+    }
+
+    /* Length validation. Buffer cannot be of zero length */
+
+    if ((SpecifiedLength == 0) ||
+        ((SpecifiedLength == ACPI_UINT32_MAX) && (ActualLength == 0)))
+    {
+        AslError (ASL_ERROR, ASL_MSG_BUFFER_LENGTH, InitializerOp, NULL);
+        return (FALSE);
+    }
+
+    if (SpecifiedLength != ACPI_UINT32_MAX)
+    {
+        /* ActualLength > SpecifiedLength -> error */
+
+        if (ActualLength > SpecifiedLength)
+        {
+            AslError (ASL_ERROR, ASL_MSG_LIST_LENGTH_LONG, InitializerOp, NULL);
+            return (FALSE);
+        }
+
+        /* ActualLength < SpecifiedLength -> remark */
+
+        else if (ActualLength < SpecifiedLength)
+        {
+            AslError (ASL_REMARK, ASL_MSG_LIST_LENGTH_SHORT, InitializerOp, NULL);
+            return (FALSE);
+        }
+    }
+
+    return (TRUE);
+}
+
+
+/*******************************************************************************
+ *
+ * FUNCTION:    RsDoGpioIntDescriptor
+ *
+ * PARAMETERS:  Op                  - Parent resource descriptor parse node
+ *              CurrentByteOffset   - Offset into the resource template AML
+ *                                    buffer (to track references to the desc)
+ *
+ * RETURN:      Completed resource node
+ *
+ * DESCRIPTION: Construct a long "GpioInt" descriptor
+ *
+ ******************************************************************************/
+
+ASL_RESOURCE_NODE *
+RsDoGpioIntDescriptor (
+    ACPI_PARSE_OBJECT       *Op,
+    UINT32                  CurrentByteOffset)
+{
+    AML_RESOURCE            *Descriptor;
+    ACPI_PARSE_OBJECT       *InitializerOp;
+    ASL_RESOURCE_NODE       *Rnode;
+    char                    *ResourceSource = NULL;
+    UINT8                   *VendorData = NULL;
+    UINT16                  *InterruptList = NULL;
+    UINT16                  ResSourceLength;
+    UINT16                  VendorLength;
+    UINT16                  InterruptLength;
+    UINT16                  DescriptorSize;
+    UINT32                  i;
+
+
+    InitializerOp = Op->Asl.Child;
+
+    /*
+     * Calculate lengths for fields that have variable length:
+     * 1) Resource Source string
+     * 2) Vendor Data buffer
+     * 3) PIN (interrupt) list
+     */
+    ResSourceLength = RsGetStringDataLength (InitializerOp);
+    VendorLength = RsGetBufferDataLength (InitializerOp);
+    InterruptLength = RsGetInterruptDataLength (InitializerOp);
+
+    DescriptorSize = ACPI_AML_SIZE_LARGE (AML_RESOURCE_GPIO) +
+        ResSourceLength + VendorLength + InterruptLength;
+
+    /* Allocate the local resource node and initialize */
+
+    Rnode = RsAllocateResourceNode (DescriptorSize + sizeof (AML_RESOURCE_LARGE_HEADER));
+
+    Descriptor = Rnode->Buffer;
+    Descriptor->Gpio.ResourceLength  = DescriptorSize;
+    Descriptor->Gpio.DescriptorType  = ACPI_RESOURCE_NAME_GPIO;
+    Descriptor->Gpio.RevisionId      = AML_RESOURCE_GPIO_REVISION;
+    Descriptor->Gpio.ConnectionType  = AML_RESOURCE_GPIO_TYPE_INT;
+
+    /* Build pointers to optional areas */
+
+    InterruptList = ACPI_ADD_PTR (UINT16, Descriptor, sizeof (AML_RESOURCE_GPIO));
+    ResourceSource = ACPI_ADD_PTR (char, InterruptList, InterruptLength);
+    VendorData = ACPI_ADD_PTR (UINT8, ResourceSource, ResSourceLength);
+
+    /* Setup offsets within the descriptor */
+
+    Descriptor->Gpio.PinTableOffset = (UINT16)
+        ACPI_PTR_DIFF (InterruptList, Descriptor);
+
+    Descriptor->Gpio.ResSourceOffset = (UINT16)
+        ACPI_PTR_DIFF (ResourceSource, Descriptor);
+
+    DbgPrint (ASL_DEBUG_OUTPUT,
+        "%16s - Actual: %.2X, Base: %.2X, ResLen: %.2X, VendLen: %.2X, IntLen: %.2X\n",
+        "GpioInt", Descriptor->Gpio.ResourceLength, (UINT16) sizeof (AML_RESOURCE_GPIO),
+        ResSourceLength, VendorLength, InterruptLength);
+
+    /* Process all child initialization nodes */
+
+    for (i = 0; InitializerOp; i++)
+    {
+        switch (i)
+        {
+        case 0: /* Interrupt Mode - edge/level [Flag] (_MOD) */
+
+            RsSetFlagBits16 (&Descriptor->Gpio.IntFlags, InitializerOp, 0, 0);
+            RsCreateBitField (InitializerOp, ACPI_RESTAG_MODE,
+                CurrentByteOffset + ASL_RESDESC_OFFSET (Gpio.IntFlags), 0);
+            break;
+
+        case 1: /* Interrupt Polarity - Active high/low [Flags] (_POL) */
+
+            RsSetFlagBits16 (&Descriptor->Gpio.IntFlags, InitializerOp, 1, 0);
+            RsCreateMultiBitField (InitializerOp, ACPI_RESTAG_POLARITY,
+                CurrentByteOffset + ASL_RESDESC_OFFSET (Gpio.IntFlags), 1, 2);
+            break;
+
+        case 2: /* Share Type - Default: exclusive (0) [Flags] (_SHR) */
+
+            RsSetFlagBits16 (&Descriptor->Gpio.IntFlags, InitializerOp, 3, 0);
+            RsCreateMultiBitField (InitializerOp, ACPI_RESTAG_INTERRUPTSHARE,
+                CurrentByteOffset + ASL_RESDESC_OFFSET (Gpio.IntFlags), 3, 2);
+            break;
+
+        case 3: /* Pin Config [BYTE] (_PPI) */
+
+            Descriptor->Gpio.PinConfig = (UINT8) InitializerOp->Asl.Value.Integer;
+            RsCreateByteField (InitializerOp, ACPI_RESTAG_PINCONFIG,
+                CurrentByteOffset + ASL_RESDESC_OFFSET (Gpio.PinConfig));
+            break;
+
+        case 4: /* DebounceTimeout [WORD] (_DBT) */
+
+            Descriptor->Gpio.DebounceTimeout = (UINT16) InitializerOp->Asl.Value.Integer;
+            RsCreateWordField (InitializerOp, ACPI_RESTAG_DEBOUNCETIME,
+                CurrentByteOffset + ASL_RESDESC_OFFSET (Gpio.DebounceTimeout));
+            break;
+
+        case 5: /* ResSource [Optional Field - STRING] */
+
+            if (ResSourceLength)
+            {
+                /* Copy string to the descriptor */
+
+                strcpy (ResourceSource,
+                    InitializerOp->Asl.Value.String);
+            }
+            break;
+
+        case 6: /* Resource Index */
+
+            if (InitializerOp->Asl.ParseOpcode != PARSEOP_DEFAULT_ARG)
+            {
+                Descriptor->Gpio.ResSourceIndex = (UINT8) InitializerOp->Asl.Value.Integer;
+            }
+            break;
+
+        case 7: /* Resource Usage (consumer/producer) */
+
+            RsSetFlagBits16 (&Descriptor->Gpio.Flags, InitializerOp, 0, 1);
+            break;
+
+        case 8: /* ResourceTag (Descriptor Name) */
+
+            UtAttachNamepathToOwner (Op, InitializerOp);
+            break;
+
+        case 9: /* Vendor Data (Optional - Buffer of BYTEs) (_VEN) */
+
+            /*
+             * Always set the VendorOffset even if there is no Vendor Data.
+             * This field is required in order to calculate the length
+             * of the ResourceSource at runtime.
+             */
+            Descriptor->Gpio.VendorOffset = (UINT16)
+                ACPI_PTR_DIFF (VendorData, Descriptor);
+
+            if (RsGetVendorData (InitializerOp, VendorData,
+                    (CurrentByteOffset +  Descriptor->Gpio.VendorOffset)))
+            {
+                Descriptor->Gpio.VendorLength = VendorLength;
+            }
+            break;
+
+        default:
+            /*
+             * PINs come through here, repeatedly. Each PIN must be a DWORD.
+             * NOTE: there is no "length" field for this, so from ACPI spec:
+             *  The number of pins in the table can be calculated from:
+             *  PinCount = (Resource Source Name Offset - Pin Table Offset) / 2
+             *  (implies resource source must immediately follow the pin list.)
+             *  Name: _PIN
+             */
+            *InterruptList = (UINT16) InitializerOp->Asl.Value.Integer;
+            InterruptList++;
+
+            /* Case 10: First interrupt number in list */
+
+            if (i == 10)
+            {
+                if (InitializerOp->Asl.ParseOpcode == PARSEOP_DEFAULT_ARG)
+                {
+                    /* Must be at least one interrupt */
+
+                    AslError (ASL_ERROR, ASL_MSG_EX_INTERRUPT_LIST_MIN,
+                        InitializerOp, NULL);
+                }
+
+                /* Check now for duplicates in list */
+
+                RsCheckListForDuplicates (InitializerOp);
+
+                /* Create a named field at the start of the list */
+
+                RsCreateDwordField (InitializerOp, ACPI_RESTAG_PIN,
+                    CurrentByteOffset + Descriptor->Gpio.PinTableOffset);
+            }
+            break;
+        }
+
+        InitializerOp = RsCompleteNodeAndGetNext (InitializerOp);
+    }
+
+    return (Rnode);
+}
+
+
+/*******************************************************************************
+ *
+ * FUNCTION:    RsDoGpioIoDescriptor
+ *
+ * PARAMETERS:  Op                  - Parent resource descriptor parse node
+ *              CurrentByteOffset   - Offset into the resource template AML
+ *                                    buffer (to track references to the desc)
+ *
+ * RETURN:      Completed resource node
+ *
+ * DESCRIPTION: Construct a long "GpioIo" descriptor
+ *
+ ******************************************************************************/
+
+ASL_RESOURCE_NODE *
+RsDoGpioIoDescriptor (
+    ACPI_PARSE_OBJECT       *Op,
+    UINT32                  CurrentByteOffset)
+{
+    AML_RESOURCE            *Descriptor;
+    ACPI_PARSE_OBJECT       *InitializerOp;
+    ASL_RESOURCE_NODE       *Rnode;
+    char                    *ResourceSource = NULL;
+    UINT8                   *VendorData = NULL;
+    UINT16                  *InterruptList = NULL;
+    UINT16                  ResSourceLength;
+    UINT16                  VendorLength;
+    UINT16                  InterruptLength;
+    UINT16                  DescriptorSize;
+    UINT32                  i;
+
+
+    InitializerOp = Op->Asl.Child;
+
+    /*
+     * Calculate lengths for fields that have variable length:
+     * 1) Resource Source string
+     * 2) Vendor Data buffer
+     * 3) PIN (interrupt) list
+     */
+    ResSourceLength = RsGetStringDataLength (InitializerOp);
+    VendorLength = RsGetBufferDataLength (InitializerOp);
+    InterruptLength = RsGetInterruptDataLength (InitializerOp);
+
+    DescriptorSize = ACPI_AML_SIZE_LARGE (AML_RESOURCE_GPIO) +
+        ResSourceLength + VendorLength + InterruptLength;
+
+    /* Allocate the local resource node and initialize */
+
+    Rnode = RsAllocateResourceNode (DescriptorSize + sizeof (AML_RESOURCE_LARGE_HEADER));
+
+    Descriptor = Rnode->Buffer;
+    Descriptor->Gpio.ResourceLength  = DescriptorSize;
+    Descriptor->Gpio.DescriptorType  = ACPI_RESOURCE_NAME_GPIO;
+    Descriptor->Gpio.RevisionId      = AML_RESOURCE_GPIO_REVISION;
+    Descriptor->Gpio.ConnectionType  = AML_RESOURCE_GPIO_TYPE_IO;
+
+    /* Build pointers to optional areas */
+
+    InterruptList = ACPI_ADD_PTR (UINT16, Descriptor, sizeof (AML_RESOURCE_GPIO));
+    ResourceSource = ACPI_ADD_PTR (char, InterruptList, InterruptLength);
+    VendorData = ACPI_ADD_PTR (UINT8, ResourceSource, ResSourceLength);
+
+    /* Setup offsets within the descriptor */
+
+    Descriptor->Gpio.PinTableOffset = (UINT16)
+        ACPI_PTR_DIFF (InterruptList, Descriptor);
+
+    Descriptor->Gpio.ResSourceOffset = (UINT16)
+        ACPI_PTR_DIFF (ResourceSource, Descriptor);
+
+    DbgPrint (ASL_DEBUG_OUTPUT,
+        "%16s - Actual: %.2X, Base: %.2X, ResLen: %.2X, VendLen: %.2X, IntLen: %.2X\n",
+        "GpioIo", Descriptor->Gpio.ResourceLength, (UINT16) sizeof (AML_RESOURCE_GPIO),
+        ResSourceLength, VendorLength, InterruptLength);
+
+    /* Process all child initialization nodes */
+
+    for (i = 0; InitializerOp; i++)
+    {
+        switch (i)
+        {
+        case 0: /* Share Type [Flags] (_SHR) */
+
+            RsSetFlagBits16 (&Descriptor->Gpio.IntFlags, InitializerOp, 3, 0);
+            RsCreateBitField (InitializerOp, ACPI_RESTAG_INTERRUPTSHARE,
+                CurrentByteOffset + ASL_RESDESC_OFFSET (Gpio.IntFlags), 3);
+            break;
+
+        case 1: /* Pin Config [BYTE] (_PPI) */
+
+            Descriptor->Gpio.PinConfig = (UINT8) InitializerOp->Asl.Value.Integer;
+            RsCreateByteField (InitializerOp, ACPI_RESTAG_PINCONFIG,
+                CurrentByteOffset + ASL_RESDESC_OFFSET (Gpio.PinConfig));
+            break;
+
+        case 2: /* DebounceTimeout [WORD] (_DBT) */
+
+            Descriptor->Gpio.DebounceTimeout = (UINT16) InitializerOp->Asl.Value.Integer;
+            RsCreateWordField (InitializerOp, ACPI_RESTAG_DEBOUNCETIME,
+                CurrentByteOffset + ASL_RESDESC_OFFSET (Gpio.DebounceTimeout));
+            break;
+
+        case 3: /* Drive Strength [WORD] (_DRS) */
+
+            Descriptor->Gpio.DriveStrength = (UINT16) InitializerOp->Asl.Value.Integer;
+            RsCreateWordField (InitializerOp, ACPI_RESTAG_DRIVESTRENGTH,
+                CurrentByteOffset + ASL_RESDESC_OFFSET (Gpio.DriveStrength));
+            break;
+
+        case 4: /* I/O Restriction [Flag] (_IOR) */
+
+            RsSetFlagBits16 (&Descriptor->Gpio.IntFlags, InitializerOp, 0, 0);
+            RsCreateMultiBitField (InitializerOp, ACPI_RESTAG_IORESTRICTION,
+                CurrentByteOffset + ASL_RESDESC_OFFSET (Gpio.IntFlags), 0, 2);
+            break;
+
+        case 5: /* ResSource [Optional Field - STRING] */
+
+            if (ResSourceLength)
+            {
+                /* Copy string to the descriptor */
+
+                strcpy (ResourceSource,
+                    InitializerOp->Asl.Value.String);
+            }
+            break;
+
+        case 6: /* Resource Index */
+
+            if (InitializerOp->Asl.ParseOpcode != PARSEOP_DEFAULT_ARG)
+            {
+                Descriptor->Gpio.ResSourceIndex = (UINT8) InitializerOp->Asl.Value.Integer;
+            }
+            break;
+
+        case 7: /* Resource Usage (consumer/producer) */
+
+            RsSetFlagBits16 (&Descriptor->Gpio.Flags, InitializerOp, 0, 1);
+            break;
+
+        case 8: /* ResourceTag (Descriptor Name) */
+
+            UtAttachNamepathToOwner (Op, InitializerOp);
+            break;
+
+        case 9: /* Vendor Data (Optional - Buffer of BYTEs) (_VEN) */
+
+            /*
+             * Always set the VendorOffset even if there is no Vendor Data.
+             * This field is required in order to calculate the length
+             * of the ResourceSource at runtime.
+             */
+            Descriptor->Gpio.VendorOffset = (UINT16)
+                ACPI_PTR_DIFF (VendorData, Descriptor);
+
+            if (RsGetVendorData (InitializerOp, VendorData,
+                    (CurrentByteOffset + Descriptor->Gpio.VendorOffset)))
+            {
+                Descriptor->Gpio.VendorLength = VendorLength;
+            }
+            break;
+
+        default:
+            /*
+             * PINs come through here, repeatedly. Each PIN must be a DWORD.
+             * NOTE: there is no "length" field for this, so from ACPI spec:
+             *  The number of pins in the table can be calculated from:
+             *  PinCount = (Resource Source Name Offset - Pin Table Offset) / 2
+             *  (implies resource source must immediately follow the pin list.)
+             *  Name: _PIN
+             */
+            *InterruptList = (UINT16) InitializerOp->Asl.Value.Integer;
+            InterruptList++;
+
+            /* Case 10: First interrupt number in list */
+
+            if (i == 10)
+            {
+                if (InitializerOp->Asl.ParseOpcode == PARSEOP_DEFAULT_ARG)
+                {
+                    /* Must be at least one interrupt */
+
+                    AslError (ASL_ERROR, ASL_MSG_EX_INTERRUPT_LIST_MIN,
+                        InitializerOp, NULL);
+                }
+
+                /* Check now for duplicates in list */
+
+                RsCheckListForDuplicates (InitializerOp);
+
+                /* Create a named field at the start of the list */
+
+                RsCreateDwordField (InitializerOp, ACPI_RESTAG_PIN,
+                    CurrentByteOffset + Descriptor->Gpio.PinTableOffset);
+            }
+            break;
+        }
+
+        InitializerOp = RsCompleteNodeAndGetNext (InitializerOp);
+    }
+
+    return (Rnode);
+}
+
+
+/*******************************************************************************
+ *
+ * FUNCTION:    RsDoI2cSerialBusDescriptor
+ *
+ * PARAMETERS:  Op                  - Parent resource descriptor parse node
+ *              CurrentByteOffset   - Offset into the resource template AML
+ *                                    buffer (to track references to the desc)
+ *
+ * RETURN:      Completed resource node
+ *
+ * DESCRIPTION: Construct a long "I2cSerialBus" descriptor
+ *
+ ******************************************************************************/
+
+ASL_RESOURCE_NODE *
+RsDoI2cSerialBusDescriptor (
+    ACPI_PARSE_OBJECT       *Op,
+    UINT32                  CurrentByteOffset)
+{
+    AML_RESOURCE            *Descriptor;
+    ACPI_PARSE_OBJECT       *InitializerOp;
+    ASL_RESOURCE_NODE       *Rnode;
+    char                    *ResourceSource = NULL;
+    UINT8                   *VendorData = NULL;
+    UINT16                  ResSourceLength;
+    UINT16                  VendorLength;
+    UINT16                  DescriptorSize;
+    UINT32                  i;
+
+
+    InitializerOp = Op->Asl.Child;
+
+    /*
+     * Calculate lengths for fields that have variable length:
+     * 1) Resource Source string
+     * 2) Vendor Data buffer
+     */
+    ResSourceLength = RsGetStringDataLength (InitializerOp);
+    VendorLength = RsGetBufferDataLength (InitializerOp);
+
+    DescriptorSize = ACPI_AML_SIZE_LARGE (AML_RESOURCE_I2C_SERIALBUS) +
+        ResSourceLength + VendorLength;
+
+    /* Allocate the local resource node and initialize */
+
+    Rnode = RsAllocateResourceNode (DescriptorSize + sizeof (AML_RESOURCE_LARGE_HEADER));
+
+    Descriptor = Rnode->Buffer;
+    Descriptor->I2cSerialBus.ResourceLength = DescriptorSize;
+    Descriptor->I2cSerialBus.DescriptorType = ACPI_RESOURCE_NAME_SERIAL_BUS;
+    Descriptor->I2cSerialBus.RevisionId     = AML_RESOURCE_I2C_REVISION;
+    Descriptor->I2cSerialBus.TypeRevisionId = AML_RESOURCE_I2C_TYPE_REVISION;
+    Descriptor->I2cSerialBus.Type           = AML_RESOURCE_I2C_SERIALBUSTYPE;
+    Descriptor->I2cSerialBus.TypeDataLength = AML_RESOURCE_I2C_MIN_DATA_LEN + VendorLength;
+
+    /* Build pointers to optional areas */
+
+    VendorData = ACPI_ADD_PTR (UINT8, Descriptor, sizeof (AML_RESOURCE_I2C_SERIALBUS));
+    ResourceSource = ACPI_ADD_PTR (char, VendorData, VendorLength);
+
+    DbgPrint (ASL_DEBUG_OUTPUT,
+        "%16s - Actual: %.2X, Base: %.2X, ResLen: %.2X, VendLen: %.2X, TypLen: %.2X\n",
+        "I2cSerialBus", Descriptor->I2cSerialBus.ResourceLength,
+        (UINT16) sizeof (AML_RESOURCE_I2C_SERIALBUS), ResSourceLength,
+        VendorLength, Descriptor->I2cSerialBus.TypeDataLength);
+
+    /* Process all child initialization nodes */
+
+    for (i = 0; InitializerOp; i++)
+    {
+        switch (i)
+        {
+        case 0: /* Slave Address [WORD] (_ADR) */
+
+            Descriptor->I2cSerialBus.SlaveAddress = (UINT16) InitializerOp->Asl.Value.Integer;
+            RsCreateWordField (InitializerOp, ACPI_RESTAG_ADDRESS,
+                CurrentByteOffset + ASL_RESDESC_OFFSET (I2cSerialBus.SlaveAddress));
+            break;
+
+        case 1: /* Slave Mode [Flag] (_SLV) */
+
+            RsSetFlagBits (&Descriptor->I2cSerialBus.Flags, InitializerOp, 0, 0);
+            RsCreateBitField (InitializerOp, ACPI_RESTAG_SLAVEMODE,
+                CurrentByteOffset + ASL_RESDESC_OFFSET (I2cSerialBus.Flags), 0);
+            break;
+
+        case 2: /* ConnectionSpeed [DWORD] (_SPE) */
+
+            Descriptor->I2cSerialBus.ConnectionSpeed = (UINT32) InitializerOp->Asl.Value.Integer;
+            RsCreateDwordField (InitializerOp, ACPI_RESTAG_SPEED,
+                CurrentByteOffset + ASL_RESDESC_OFFSET (I2cSerialBus.ConnectionSpeed));
+            break;
+
+        case 3: /* Addresssing Mode [Flag] (_MOD) */
+
+            RsSetFlagBits16 (&Descriptor->I2cSerialBus.TypeSpecificFlags, InitializerOp, 0, 0);
+            RsCreateBitField (InitializerOp, ACPI_RESTAG_MODE,
+                CurrentByteOffset + ASL_RESDESC_OFFSET (I2cSerialBus.TypeSpecificFlags), 0);
+            break;
+
+        case 4: /* ResSource [Optional Field - STRING] */
+
+            if (ResSourceLength)
+            {
+                /* Copy string to the descriptor */
+
+                strcpy (ResourceSource,
+                    InitializerOp->Asl.Value.String);
+            }
+            break;
+
+        case 5: /* Resource Index */
+
+            if (InitializerOp->Asl.ParseOpcode != PARSEOP_DEFAULT_ARG)
+            {
+                Descriptor->I2cSerialBus.ResSourceIndex = (UINT8) InitializerOp->Asl.Value.Integer;
+            }
+            break;
+
+        case 6: /* Resource Usage (consumer/producer) */
+
+            RsSetFlagBits (&Descriptor->I2cSerialBus.Flags, InitializerOp, 1, 1);
+            break;
+
+        case 7: /* ResourceTag (Descriptor Name) */
+
+            UtAttachNamepathToOwner (Op, InitializerOp);
+            break;
+
+        case 8: /* Vendor Data (Optional - Buffer of BYTEs) (_VEN) */
+
+            RsGetVendorData (InitializerOp, VendorData,
+                CurrentByteOffset + sizeof (AML_RESOURCE_I2C_SERIALBUS));
+            break;
+
+        default:    /* Ignore any extra nodes */
+            break;
+        }
+
+        InitializerOp = RsCompleteNodeAndGetNext (InitializerOp);
+    }
+
+    return (Rnode);
+}
+
+
+/*******************************************************************************
+ *
+ * FUNCTION:    RsDoSpiSerialBusDescriptor
+ *
+ * PARAMETERS:  Op                  - Parent resource descriptor parse node
+ *              CurrentByteOffset   - Offset into the resource template AML
+ *                                    buffer (to track references to the desc)
+ *
+ * RETURN:      Completed resource node
+ *
+ * DESCRIPTION: Construct a long "SPI Serial Bus" descriptor
+ *
+ ******************************************************************************/
+
+ASL_RESOURCE_NODE *
+RsDoSpiSerialBusDescriptor (
+    ACPI_PARSE_OBJECT       *Op,
+    UINT32                  CurrentByteOffset)
+{
+    AML_RESOURCE            *Descriptor;
+    ACPI_PARSE_OBJECT       *InitializerOp;
+    ASL_RESOURCE_NODE       *Rnode;
+    char                    *ResourceSource = NULL;
+    UINT8                   *VendorData = NULL;
+    UINT16                  ResSourceLength;
+    UINT16                  VendorLength;
+    UINT16                  DescriptorSize;
+    UINT32                  i;
+
+
+    InitializerOp = Op->Asl.Child;
+
+    /*
+     * Calculate lengths for fields that have variable length:
+     * 1) Resource Source string
+     * 2) Vendor Data buffer
+     */
+    ResSourceLength = RsGetStringDataLength (InitializerOp);
+    VendorLength = RsGetBufferDataLength (InitializerOp);
+
+    DescriptorSize = ACPI_AML_SIZE_LARGE (AML_RESOURCE_SPI_SERIALBUS) +
+        ResSourceLength + VendorLength;
+
+    /* Allocate the local resource node and initialize */
+
+    Rnode = RsAllocateResourceNode (DescriptorSize + sizeof (AML_RESOURCE_LARGE_HEADER));
+
+    Descriptor = Rnode->Buffer;
+    Descriptor->SpiSerialBus.ResourceLength = DescriptorSize;
+    Descriptor->SpiSerialBus.DescriptorType = ACPI_RESOURCE_NAME_SERIAL_BUS;
+    Descriptor->SpiSerialBus.RevisionId     = AML_RESOURCE_SPI_REVISION;
+    Descriptor->SpiSerialBus.TypeRevisionId = AML_RESOURCE_SPI_TYPE_REVISION;
+    Descriptor->SpiSerialBus.Type           = AML_RESOURCE_SPI_SERIALBUSTYPE;
+    Descriptor->SpiSerialBus.TypeDataLength = AML_RESOURCE_SPI_MIN_DATA_LEN + VendorLength;
+
+    /* Build pointers to optional areas */
+
+    VendorData = ACPI_ADD_PTR (UINT8, Descriptor, sizeof (AML_RESOURCE_SPI_SERIALBUS));
+    ResourceSource = ACPI_ADD_PTR (char, VendorData, VendorLength);
+
+    DbgPrint (ASL_DEBUG_OUTPUT,
+        "%16s - Actual: %.2X, Base: %.2X, ResLen: %.2X, VendLen: %.2X, TypLen: %.2X\n",
+        "SpiSerialBus", Descriptor->SpiSerialBus.ResourceLength,
+        (UINT16) sizeof (AML_RESOURCE_SPI_SERIALBUS), ResSourceLength,
+        VendorLength, Descriptor->SpiSerialBus.TypeDataLength);
+
+    /* Process all child initialization nodes */
+
+    for (i = 0; InitializerOp; i++)
+    {
+        switch (i)
+        {
+        case 0: /* Device Selection [WORD] (_ADR) */
+
+            Descriptor->SpiSerialBus.DeviceSelection = (UINT16) InitializerOp->Asl.Value.Integer;
+            RsCreateWordField (InitializerOp, ACPI_RESTAG_ADDRESS,
+                CurrentByteOffset + ASL_RESDESC_OFFSET (SpiSerialBus.DeviceSelection));
+            break;
+
+        case 1: /* Device Polarity [Flag] (_DPL) */
+
+            RsSetFlagBits16 (&Descriptor->SpiSerialBus.TypeSpecificFlags, InitializerOp, 1, 0);
+            RsCreateBitField (InitializerOp, ACPI_RESTAG_DEVICEPOLARITY,
+                CurrentByteOffset + ASL_RESDESC_OFFSET (SpiSerialBus.TypeSpecificFlags), 1);
+            break;
+
+        case 2: /* Wire Mode [Flag] (_MOD) */
+
+            RsSetFlagBits16 (&Descriptor->SpiSerialBus.TypeSpecificFlags, InitializerOp, 0, 0);
+            RsCreateBitField (InitializerOp, ACPI_RESTAG_MODE,
+                CurrentByteOffset + ASL_RESDESC_OFFSET (SpiSerialBus.TypeSpecificFlags), 0);
+            break;
+
+        case 3: /* Device Bit Length [BYTE] (_LEN) */
+
+            Descriptor->SpiSerialBus.DataBitLength = (UINT8) InitializerOp->Asl.Value.Integer;
+            RsCreateByteField (InitializerOp, ACPI_RESTAG_LENGTH,
+                CurrentByteOffset + ASL_RESDESC_OFFSET (SpiSerialBus.DataBitLength));
+            break;
+
+        case 4: /* Slave Mode [Flag] (_SLV) */
+
+            RsSetFlagBits (&Descriptor->SpiSerialBus.Flags, InitializerOp, 0, 0);
+            RsCreateBitField (InitializerOp, ACPI_RESTAG_SLAVEMODE,
+                CurrentByteOffset + ASL_RESDESC_OFFSET (SpiSerialBus.Flags), 0);
+            break;
+
+        case 5: /* ConnectionSpeed [DWORD] (_SPE) */
+
+            Descriptor->SpiSerialBus.ConnectionSpeed = (UINT32) InitializerOp->Asl.Value.Integer;
+            RsCreateDwordField (InitializerOp, ACPI_RESTAG_SPEED,
+                CurrentByteOffset + ASL_RESDESC_OFFSET (SpiSerialBus.ConnectionSpeed));
+            break;
+
+        case 6: /* Clock Polarity [BYTE] (_POL) */
+
+            Descriptor->SpiSerialBus.ClockPolarity = (UINT8) InitializerOp->Asl.Value.Integer;
+            RsCreateByteField (InitializerOp, ACPI_RESTAG_POLARITY,
+                CurrentByteOffset + ASL_RESDESC_OFFSET (SpiSerialBus.ClockPolarity));
+            break;
+
+        case 7: /* Clock Phase [BYTE] (_PHA) */
+
+            Descriptor->SpiSerialBus.ClockPhase = (UINT8) InitializerOp->Asl.Value.Integer;
+            RsCreateByteField (InitializerOp, ACPI_RESTAG_PHASE,
+                CurrentByteOffset + ASL_RESDESC_OFFSET (SpiSerialBus.ClockPhase));
+            break;
+
+        case 8: /* ResSource [Optional Field - STRING] */
+
+            if (ResSourceLength)
+            {
+                /* Copy string to the descriptor */
+
+                strcpy (ResourceSource,
+                    InitializerOp->Asl.Value.String);
+            }
+            break;
+
+        case 9: /* Resource Index */
+
+            if (InitializerOp->Asl.ParseOpcode != PARSEOP_DEFAULT_ARG)
+            {
+                Descriptor->SpiSerialBus.ResSourceIndex = (UINT8) InitializerOp->Asl.Value.Integer;
+            }
+            break;
+
+        case 10: /* Resource Usage (consumer/producer) */
+
+            RsSetFlagBits (&Descriptor->SpiSerialBus.Flags, InitializerOp, 1, 1);
+            break;
+
+        case 11: /* ResourceTag (Descriptor Name) */
+
+            UtAttachNamepathToOwner (Op, InitializerOp);
+            break;
+
+        case 12: /* Vendor Data (Optional - Buffer of BYTEs) (_VEN) */
+
+            RsGetVendorData (InitializerOp, VendorData,
+                CurrentByteOffset + sizeof (AML_RESOURCE_SPI_SERIALBUS));
+            break;
+
+        default:    /* Ignore any extra nodes */
+            break;
+        }
+
+        InitializerOp = RsCompleteNodeAndGetNext (InitializerOp);
+    }
+
+    return (Rnode);
+}
+
+
+/*******************************************************************************
+ *
+ * FUNCTION:    RsDoUartSerialBusDescriptor
+ *
+ * PARAMETERS:  Op                  - Parent resource descriptor parse node
+ *              CurrentByteOffset   - Offset into the resource template AML
+ *                                    buffer (to track references to the desc)
+ *
+ * RETURN:      Completed resource node
+ *
+ * DESCRIPTION: Construct a long "UART Serial Bus" descriptor
+ *
+ ******************************************************************************/
+
+ASL_RESOURCE_NODE *
+RsDoUartSerialBusDescriptor (
+    ACPI_PARSE_OBJECT       *Op,
+    UINT32                  CurrentByteOffset)
+{
+    AML_RESOURCE            *Descriptor;
+    ACPI_PARSE_OBJECT       *InitializerOp;
+    ASL_RESOURCE_NODE       *Rnode;
+    char                    *ResourceSource = NULL;
+    UINT8                   *VendorData = NULL;
+    UINT16                  ResSourceLength;
+    UINT16                  VendorLength;
+    UINT16                  DescriptorSize;
+    UINT32                  i;
+
+
+    InitializerOp = Op->Asl.Child;
+
+    /*
+     * Calculate lengths for fields that have variable length:
+     * 1) Resource Source string
+     * 2) Vendor Data buffer
+     */
+    ResSourceLength = RsGetStringDataLength (InitializerOp);
+    VendorLength = RsGetBufferDataLength (InitializerOp);
+
+    DescriptorSize = ACPI_AML_SIZE_LARGE (AML_RESOURCE_UART_SERIALBUS) +
+        ResSourceLength + VendorLength;
+
+    /* Allocate the local resource node and initialize */
+
+    Rnode = RsAllocateResourceNode (DescriptorSize + sizeof (AML_RESOURCE_LARGE_HEADER));
+
+    Descriptor = Rnode->Buffer;
+    Descriptor->UartSerialBus.ResourceLength = DescriptorSize;
+    Descriptor->UartSerialBus.DescriptorType = ACPI_RESOURCE_NAME_SERIAL_BUS;
+    Descriptor->UartSerialBus.RevisionId     = AML_RESOURCE_UART_REVISION;
+    Descriptor->UartSerialBus.TypeRevisionId = AML_RESOURCE_UART_TYPE_REVISION;
+    Descriptor->UartSerialBus.Type           = AML_RESOURCE_UART_SERIALBUSTYPE;
+    Descriptor->UartSerialBus.TypeDataLength = AML_RESOURCE_UART_MIN_DATA_LEN + VendorLength;
+
+    /* Build pointers to optional areas */
+
+    VendorData = ACPI_ADD_PTR (UINT8, Descriptor, sizeof (AML_RESOURCE_UART_SERIALBUS));
+    ResourceSource = ACPI_ADD_PTR (char, VendorData, VendorLength);
+
+    DbgPrint (ASL_DEBUG_OUTPUT,
+        "%16s - Actual: %.2X, Base: %.2X, ResLen: %.2X, VendLen: %.2X, TypLen: %.2X\n",
+        "UartSerialBus", Descriptor->UartSerialBus.ResourceLength,
+        (UINT16) sizeof (AML_RESOURCE_UART_SERIALBUS), ResSourceLength,
+        VendorLength, Descriptor->UartSerialBus.TypeDataLength);
+
+    /* Process all child initialization nodes */
+
+    for (i = 0; InitializerOp; i++)
+    {
+        switch (i)
+        {
+        case 0: /* ConnectionSpeed (Baud Rate) [DWORD] (_SPE) */
+
+            Descriptor->UartSerialBus.DefaultBaudRate = (UINT32) InitializerOp->Asl.Value.Integer;
+            RsCreateDwordField (InitializerOp, ACPI_RESTAG_SPEED,
+                CurrentByteOffset + ASL_RESDESC_OFFSET (UartSerialBus.DefaultBaudRate));
+            break;
+
+        case 1: /* Bits Per Byte [Flags] (_LEN) */
+
+            RsSetFlagBits16 (&Descriptor->UartSerialBus.TypeSpecificFlags, InitializerOp, 4, 3);
+            RsCreateMultiBitField (InitializerOp, ACPI_RESTAG_LENGTH,
+                CurrentByteOffset + ASL_RESDESC_OFFSET (UartSerialBus.TypeSpecificFlags), 4, 3);
+            break;
+
+        case 2: /* Stop Bits [Flags] (_STB) */
+
+            RsSetFlagBits16 (&Descriptor->UartSerialBus.TypeSpecificFlags, InitializerOp, 2, 1);
+            RsCreateMultiBitField (InitializerOp, ACPI_RESTAG_STOPBITS,
+                CurrentByteOffset + ASL_RESDESC_OFFSET (UartSerialBus.TypeSpecificFlags), 2, 2);
+            break;
+
+        case 3: /* Lines In Use [BYTE] (_LIN) */
+
+            Descriptor->UartSerialBus.LinesEnabled = (UINT8) InitializerOp->Asl.Value.Integer;
+            RsCreateByteField (InitializerOp, ACPI_RESTAG_LINE,
+                CurrentByteOffset + ASL_RESDESC_OFFSET (UartSerialBus.LinesEnabled));
+            break;
+
+        case 4: /* Endianness [Flag] (_END) */
+
+            RsSetFlagBits16 (&Descriptor->UartSerialBus.TypeSpecificFlags, InitializerOp, 7, 0);
+            RsCreateBitField (InitializerOp, ACPI_RESTAG_ENDIANNESS,
+                CurrentByteOffset + ASL_RESDESC_OFFSET (UartSerialBus.TypeSpecificFlags), 7);
+            break;
+
+        case 5: /* Parity [BYTE] (_PAR) */
+
+            Descriptor->UartSerialBus.Parity = (UINT8) InitializerOp->Asl.Value.Integer;
+            RsCreateByteField (InitializerOp, ACPI_RESTAG_PARITY,
+                CurrentByteOffset + ASL_RESDESC_OFFSET (UartSerialBus.Parity));
+            break;
+
+        case 6: /* Flow Control [Flags] (_FLC) */
+
+            RsSetFlagBits16 (&Descriptor->UartSerialBus.TypeSpecificFlags, InitializerOp, 0, 0);
+            RsCreateMultiBitField (InitializerOp, ACPI_RESTAG_FLOWCONTROL,
+                CurrentByteOffset + ASL_RESDESC_OFFSET (UartSerialBus.TypeSpecificFlags), 0, 2);
+            break;
+
+        case 7: /* Rx Buffer Size [WORD] (_RXL) */
+
+            Descriptor->UartSerialBus.RxFifoSize = (UINT16) InitializerOp->Asl.Value.Integer;
+            RsCreateWordField (InitializerOp, ACPI_RESTAG_LENGTH_RX,
+                CurrentByteOffset + ASL_RESDESC_OFFSET (UartSerialBus.RxFifoSize));
+            break;
+
+        case 8: /* Tx Buffer Size [WORD] (_TXL) */
+
+            Descriptor->UartSerialBus.TxFifoSize = (UINT16) InitializerOp->Asl.Value.Integer;
+            RsCreateWordField (InitializerOp, ACPI_RESTAG_LENGTH_TX,
+                CurrentByteOffset + ASL_RESDESC_OFFSET (UartSerialBus.TxFifoSize));
+            break;
+
+        case 9: /* ResSource [Optional Field - STRING] */
+
+            if (ResSourceLength)
+            {
+                /* Copy string to the descriptor */
+
+                strcpy (ResourceSource,
+                    InitializerOp->Asl.Value.String);
+            }
+            break;
+
+        case 10: /* Resource Index */
+
+            if (InitializerOp->Asl.ParseOpcode != PARSEOP_DEFAULT_ARG)
+            {
+                Descriptor->UartSerialBus.ResSourceIndex = (UINT8) InitializerOp->Asl.Value.Integer;
+            }
+            break;
+
+        case 11: /* Resource Usage (consumer/producer) */
+
+            RsSetFlagBits (&Descriptor->UartSerialBus.Flags, InitializerOp, 1, 1);
+
+            /*
+             * Slave Mode [Flag] (_SLV)
+             *
+             * Note: There is no SlaveMode argument to the UartSerialBus macro, but
+             * we add this name anyway to allow the flag to be set by ASL in the
+             * rare case where there is a slave mode associated with the UART.
+             */
+            RsCreateBitField (InitializerOp, ACPI_RESTAG_SLAVEMODE,
+                CurrentByteOffset + ASL_RESDESC_OFFSET (UartSerialBus.Flags), 0);
+            break;
+
+        case 12: /* ResourceTag (Descriptor Name) */
+
+            UtAttachNamepathToOwner (Op, InitializerOp);
+            break;
+
+        case 13: /* Vendor Data (Optional - Buffer of BYTEs) (_VEN) */
+
+            RsGetVendorData (InitializerOp, VendorData,
+                CurrentByteOffset + sizeof (AML_RESOURCE_UART_SERIALBUS));
+            break;
+
+        default:    /* Ignore any extra nodes */
+            break;
+        }
+
+        InitializerOp = RsCompleteNodeAndGetNext (InitializerOp);
+    }
+
+    return (Rnode);
+}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/compiler/aslrestype2w.c
--- a/head/sys/contrib/dev/acpica/compiler/aslrestype2w.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/compiler/aslrestype2w.c	Tue Dec 06 20:26:16 2011 +0200
@@ -144,14 +144,14 @@
         case 4: /* Range Type */
 
             RsSetFlagBits (&Descriptor->Address16.SpecificFlags, InitializerOp, 0, 3);
-            RsCreateBitField (InitializerOp, ACPI_RESTAG_RANGETYPE,
-                CurrentByteOffset + ASL_RESDESC_OFFSET (Address16.SpecificFlags), 0);
+            RsCreateMultiBitField (InitializerOp, ACPI_RESTAG_RANGETYPE,
+                CurrentByteOffset + ASL_RESDESC_OFFSET (Address16.SpecificFlags), 0, 2);
             break;
 
         case 5: /* Address Granularity */
 
             Descriptor->Address16.Granularity = (UINT16) InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_GRANULARITY,
+            RsCreateWordField (InitializerOp, ACPI_RESTAG_GRANULARITY,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Address16.Granularity));
             GranOp = InitializerOp;
             break;
@@ -159,7 +159,7 @@
         case 6: /* Address Min */
 
             Descriptor->Address16.Minimum = (UINT16) InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_MINADDR,
+            RsCreateWordField (InitializerOp, ACPI_RESTAG_MINADDR,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Address16.Minimum));
             MinOp = InitializerOp;
             break;
@@ -167,7 +167,7 @@
         case 7: /* Address Max */
 
             Descriptor->Address16.Maximum = (UINT16) InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_MAXADDR,
+            RsCreateWordField (InitializerOp, ACPI_RESTAG_MAXADDR,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Address16.Maximum));
             MaxOp = InitializerOp;
             break;
@@ -175,14 +175,14 @@
         case 8: /* Translation Offset */
 
             Descriptor->Address16.TranslationOffset = (UINT16) InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_TRANSLATION,
+            RsCreateWordField (InitializerOp, ACPI_RESTAG_TRANSLATION,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Address16.TranslationOffset));
             break;
 
         case 9: /* Address Length */
 
             Descriptor->Address16.AddressLength = (UINT16) InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_LENGTH,
+            RsCreateWordField (InitializerOp, ACPI_RESTAG_LENGTH,
                  CurrentByteOffset + ASL_RESDESC_OFFSET (Address16.AddressLength));
             LengthOp = InitializerOp;
             break;
@@ -367,7 +367,7 @@
 
             Descriptor->Address16.Granularity =
                 (UINT16) InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_GRANULARITY,
+            RsCreateWordField (InitializerOp, ACPI_RESTAG_GRANULARITY,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Address16.Granularity));
             GranOp = InitializerOp;
             break;
@@ -376,7 +376,7 @@
 
             Descriptor->Address16.Minimum =
                 (UINT16) InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_MINADDR,
+            RsCreateWordField (InitializerOp, ACPI_RESTAG_MINADDR,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Address16.Minimum));
             MinOp = InitializerOp;
             break;
@@ -385,7 +385,7 @@
 
             Descriptor->Address16.Maximum =
                 (UINT16) InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_MAXADDR,
+            RsCreateWordField (InitializerOp, ACPI_RESTAG_MAXADDR,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Address16.Maximum));
             MaxOp = InitializerOp;
             break;
@@ -394,7 +394,7 @@
 
             Descriptor->Address16.TranslationOffset =
                 (UINT16) InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_TRANSLATION,
+            RsCreateWordField (InitializerOp, ACPI_RESTAG_TRANSLATION,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Address16.TranslationOffset));
             break;
 
@@ -402,7 +402,7 @@
 
             Descriptor->Address16.AddressLength =
                 (UINT16) InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_LENGTH,
+            RsCreateWordField (InitializerOp, ACPI_RESTAG_LENGTH,
                  CurrentByteOffset + ASL_RESDESC_OFFSET (Address16.AddressLength));
             LengthOp = InitializerOp;
             break;
@@ -584,7 +584,7 @@
 
             Descriptor->Address16.Granularity =
                 (UINT16) InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_GRANULARITY,
+            RsCreateWordField (InitializerOp, ACPI_RESTAG_GRANULARITY,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Address16.Granularity));
             GranOp = InitializerOp;
             break;
@@ -593,7 +593,7 @@
 
             Descriptor->Address16.Minimum =
                 (UINT16) InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_MINADDR,
+            RsCreateWordField (InitializerOp, ACPI_RESTAG_MINADDR,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Address16.Minimum));
             MinOp = InitializerOp;
             break;
@@ -602,7 +602,7 @@
 
             Descriptor->Address16.Maximum =
                 (UINT16) InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_MAXADDR,
+            RsCreateWordField (InitializerOp, ACPI_RESTAG_MAXADDR,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Address16.Maximum));
             MaxOp = InitializerOp;
             break;
@@ -611,7 +611,7 @@
 
             Descriptor->Address16.TranslationOffset =
                 (UINT16) InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_TRANSLATION,
+            RsCreateWordField (InitializerOp, ACPI_RESTAG_TRANSLATION,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Address16.TranslationOffset));
             break;
 
@@ -619,7 +619,7 @@
 
             Descriptor->Address16.AddressLength =
                 (UINT16) InitializerOp->Asl.Value.Integer;
-            RsCreateByteField (InitializerOp, ACPI_RESTAG_LENGTH,
+            RsCreateWordField (InitializerOp, ACPI_RESTAG_LENGTH,
                 CurrentByteOffset + ASL_RESDESC_OFFSET (Address16.AddressLength));
             LengthOp = InitializerOp;
             break;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/compiler/aslstubs.c
--- a/head/sys/contrib/dev/acpica/compiler/aslstubs.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/compiler/aslstubs.c	Tue Dec 06 20:26:16 2011 +0200
@@ -232,3 +232,20 @@
     return (AE_SUPPORT);
 }
 
+/* OSL interfaces */
+
+ACPI_THREAD_ID
+AcpiOsGetThreadId (
+    void)
+{
+    return (0xFFFF);
+}
+
+ACPI_STATUS
+AcpiOsExecute (
+    ACPI_EXECUTE_TYPE       Type,
+    ACPI_OSD_EXEC_CALLBACK  Function,
+    void                    *Context)
+{
+    return (AE_SUPPORT);
+}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/compiler/asltransform.c
--- a/head/sys/contrib/dev/acpica/compiler/asltransform.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/compiler/asltransform.c	Tue Dec 06 20:26:16 2011 +0200
@@ -398,6 +398,7 @@
     ACPI_PARSE_OBJECT       *MethodOp;
     ACPI_PARSE_OBJECT       *StoreOp;
     ACPI_PARSE_OBJECT       *BreakOp;
+    ACPI_PARSE_OBJECT       *BufferOp;
     char                    *PredicateValueName;
     UINT16                  Index;
     UINT32                  Btype;
@@ -647,6 +648,7 @@
 
     Predicate = StartNode->Asl.Child;
     NewOp = TrCreateLeafNode (PARSEOP_NAME);
+    TrAmlInitLineNumbers (NewOp, StartNode);
 
     /* Find the parent method */
 
@@ -690,6 +692,7 @@
 
     NewOp2 = TrCreateValuedLeafNode (PARSEOP_NAMESEG,
                 (UINT64) ACPI_TO_INTEGER (PredicateValueName));
+    TrAmlInitLineNumbers (NewOp2, NewOp);
     NewOp2->Asl.CompileFlags |= NODE_IS_NAME_DECLARATION;
     NewOp->Asl.Child  = NewOp2;
 
@@ -700,21 +703,27 @@
     case ACPI_BTYPE_INTEGER:
         NewOp2->Asl.Next = TrCreateValuedLeafNode (PARSEOP_ZERO,
                                 (UINT64) 0);
+        TrAmlInitLineNumbers (NewOp2->Asl.Next, NewOp);
         break;
 
     case ACPI_BTYPE_STRING:
         NewOp2->Asl.Next = TrCreateValuedLeafNode (PARSEOP_STRING_LITERAL,
                                 (UINT64) ACPI_TO_INTEGER (""));
+        TrAmlInitLineNumbers (NewOp2->Asl.Next, NewOp);
         break;
 
     case ACPI_BTYPE_BUFFER:
         (void) TrLinkPeerNode (NewOp2, TrCreateValuedLeafNode (PARSEOP_BUFFER,
                                     (UINT64) 0));
         Next = NewOp2->Asl.Next;
+        TrAmlInitLineNumbers (Next, NewOp2);
         (void) TrLinkChildren (Next, 1, TrCreateValuedLeafNode (PARSEOP_ZERO,
                                     (UINT64) 1));
-        (void) TrLinkPeerNode (Next->Asl.Child,
-            TrCreateValuedLeafNode (PARSEOP_DEFAULT_ARG, (UINT64) 0));
+        TrAmlInitLineNumbers (Next->Asl.Child, Next);
+
+        BufferOp = TrCreateValuedLeafNode (PARSEOP_DEFAULT_ARG, (UINT64) 0);
+        TrAmlInitLineNumbers (BufferOp, Next->Asl.Child);
+        (void) TrLinkPeerNode (Next->Asl.Child, BufferOp);
 
         TrAmlSetSubtreeParent (Next->Asl.Child, Next);
         break;
@@ -733,6 +742,7 @@
      */
     TrAmlInitNode (StartNode, PARSEOP_WHILE);
     NewOp = TrCreateLeafNode (PARSEOP_ONE);
+    TrAmlInitLineNumbers (NewOp, StartNode);
     NewOp->Asl.Next = Predicate->Asl.Next;
     NewOp->Asl.Parent = StartNode;
     StartNode->Asl.Child = NewOp;
@@ -740,6 +750,7 @@
     /* Create a Store() node */
 
     StoreOp = TrCreateLeafNode (PARSEOP_STORE);
+    TrAmlInitLineNumbers (StoreOp, NewOp);
     StoreOp->Asl.Parent = StartNode;
     TrAmlInsertPeer (NewOp, StoreOp);
 
@@ -750,6 +761,7 @@
 
     NewOp = TrCreateValuedLeafNode (PARSEOP_NAMESEG,
                 (UINT64) ACPI_TO_INTEGER (PredicateValueName));
+    TrAmlInitLineNumbers (NewOp, StoreOp);
     NewOp->Asl.Parent    = StoreOp;
     Predicate->Asl.Next  = NewOp;
 
@@ -762,6 +774,7 @@
     }
 
     BreakOp = TrCreateLeafNode (PARSEOP_BREAK);
+    TrAmlInitLineNumbers (BreakOp, NewOp);
     BreakOp->Asl.Parent = StartNode;
     TrAmlInsertPeer (Conditional, BreakOp);
 }
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/compiler/asltree.c
--- a/head/sys/contrib/dev/acpica/compiler/asltree.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/compiler/asltree.c	Tue Dec 06 20:26:16 2011 +0200
@@ -45,6 +45,7 @@
 
 #include <contrib/dev/acpica/compiler/aslcompiler.h>
 #include "aslcompiler.y.h"
+#include <contrib/dev/acpica/include/acapps.h>
 #include <time.h>
 
 #define _COMPONENT          ACPI_COMPILER
@@ -287,9 +288,6 @@
     case NODE_METHOD_TYPED:
         return ("NODE_METHOD_TYPED");
 
-    case NODE_IS_BIT_OFFSET:
-        return ("NODE_IS_BIT_OFFSET");
-
     case NODE_COMPILE_TIME_CONST:
         return ("NODE_COMPILE_TIME_CONST");
 
@@ -428,6 +426,8 @@
     time_t                  CurrentTime;
     char                    *StaticTimeString;
     char                    *TimeString;
+    char                    *Path;
+    char                    *Filename;
 
 
     switch (ParseOpcode)
@@ -437,7 +437,7 @@
         Op->Asl.Value.Integer = Op->Asl.LineNumber;
         break;
 
-    case PARSEOP___FILE__:
+    case PARSEOP___PATH__:
         Op = TrAllocateNode (PARSEOP_STRING_LITERAL);
 
         /* Op.Asl.Filename contains the full pathname to the file */
@@ -445,7 +445,17 @@
         Op->Asl.Value.String = Op->Asl.Filename;
         break;
 
-   case PARSEOP___DATE__:
+    case PARSEOP___FILE__:
+        Op = TrAllocateNode (PARSEOP_STRING_LITERAL);
+
+        /* Get the simple filename from the full path */
+
+        FlSplitInputPathname (Op->Asl.Filename, &Path, &Filename);
+        ACPI_FREE (Path);
+        Op->Asl.Value.String = Filename;
+        break;
+
+    case PARSEOP___DATE__:
         Op = TrAllocateNode (PARSEOP_STRING_LITERAL);
 
         /* Get a copy of the current time */
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/compiler/asltypes.h
--- a/head/sys/contrib/dev/acpica/compiler/asltypes.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/compiler/asltypes.h	Tue Dec 06 20:26:16 2011 +0200
@@ -68,7 +68,7 @@
 #define NODE_METHOD_SOME_NO_RETVAL  0x00000200
 #define NODE_RESULT_NOT_USED        0x00000400
 #define NODE_METHOD_TYPED           0x00000800
-#define NODE_IS_BIT_OFFSET          0x00001000
+#define NODE_UNUSED_FLAG            0x00001000
 #define NODE_COMPILE_TIME_CONST     0x00002000
 #define NODE_IS_TERM_ARG            0x00004000
 #define NODE_WAS_ONES_OP            0x00008000
@@ -144,8 +144,10 @@
 } ASL_FILE_STATUS;
 
 
-/* File types */
-
+/*
+ * File types. Note: Any changes to this table must also be reflected
+ * in the AslFileTypeNames array.
+ */
 typedef enum
 {
     ASL_FILE_STDOUT             = 0,
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/compiler/aslutils.c
--- a/head/sys/contrib/dev/acpica/compiler/aslutils.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/compiler/aslutils.c	Tue Dec 06 20:26:16 2011 +0200
@@ -53,11 +53,31 @@
 #define _COMPONENT          ACPI_COMPILER
         ACPI_MODULE_NAME    ("aslutils")
 
+
 char                        AslHexLookup[] =
 {
     '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'
 };
 
+/* Table below must match ASL_FILE_TYPES in asltypes.h */
+
+static const char       *AslFileTypeNames [ASL_NUM_FILES] =
+{
+    "stdout:       ",
+    "stderr:       ",
+    "Table Input:  ",
+    "Binary Output:",
+    "Source Output:",
+    "Listing File: ",
+    "Hex Dump:     ",
+    "Namespace:    ",
+    "Debug File:   ",
+    "ASM Source:   ",
+    "C Source:     ",
+    "ASM Include:  ",
+    "C Include:    "
+};
+
 
 /* Local prototypes */
 
@@ -451,35 +471,40 @@
 UtDisplaySummary (
     UINT32                  FileId)
 {
+    UINT32                  i;
+
 
     if (FileId != ASL_FILE_STDOUT)
     {
         /* Compiler name and version number */
 
-        FlPrintFile (FileId, "%s version %X%s\n",
+        FlPrintFile (FileId, "%s version %X%s\n\n",
             ASL_COMPILER_NAME, (UINT32) ACPI_CA_VERSION, ACPI_WIDTH);
     }
 
+    /* Summary of main input and output files */
+
     if (Gbl_FileType == ASL_INPUT_TYPE_ASCII_DATA)
     {
         FlPrintFile (FileId,
-            "Table Input:   %s - %u lines, %u bytes, %u fields\n",
+            "%-14s %s - %u lines, %u bytes, %u fields\n",
+            "Table Input:",
             Gbl_Files[ASL_FILE_INPUT].Filename, Gbl_CurrentLineNumber,
             Gbl_InputByteCount, Gbl_InputFieldCount);
 
         if ((Gbl_ExceptionCount[ASL_ERROR] == 0) || (Gbl_IgnoreErrors))
         {
             FlPrintFile (FileId,
-                "Binary Output: %s - %u bytes\n\n",
+                "%-14s %s - %u bytes\n",
+                "Binary Output:",
                 Gbl_Files[ASL_FILE_AML_OUTPUT].Filename, Gbl_TableLength);
         }
     }
     else
     {
-        /* Input/Output summary */
-
         FlPrintFile (FileId,
-            "ASL Input:  %s - %u lines, %u bytes, %u keywords\n",
+            "%-14s %s - %u lines, %u bytes, %u keywords\n",
+            "ASL Input:",
             Gbl_Files[ASL_FILE_INPUT].Filename, Gbl_CurrentLineNumber,
             Gbl_InputByteCount, TotalKeywords);
 
@@ -488,16 +513,38 @@
         if ((Gbl_ExceptionCount[ASL_ERROR] == 0) || (Gbl_IgnoreErrors))
         {
             FlPrintFile (FileId,
-                "AML Output: %s - %u bytes, %u named objects, %u executable opcodes\n\n",
+                "%-14s %s - %u bytes, %u named objects, %u executable opcodes\n",
+                "AML Output:",
                 Gbl_Files[ASL_FILE_AML_OUTPUT].Filename, Gbl_TableLength,
                 TotalNamedObjects, TotalExecutableOpcodes);
         }
     }
 
+    /* Display summary of any optional files */
+
+    for (i = ASL_FILE_SOURCE_OUTPUT; i <= ASL_MAX_FILE_TYPE; i++)
+    {
+        if (!Gbl_Files[i].Filename || !Gbl_Files[i].Handle)
+        {
+            continue;
+        }
+
+        /* .SRC is a temp file unless specifically requested */
+
+        if ((i == ASL_FILE_SOURCE_OUTPUT) && (!Gbl_SourceOutputFlag))
+        {
+            continue;
+        }
+
+        FlPrintFile (FileId, "%14s %s - %u bytes\n",
+            AslFileTypeNames [i],
+            Gbl_Files[i].Filename, FlGetFileSize (i));
+    }
+
     /* Error summary */
 
     FlPrintFile (FileId,
-        "Compilation complete. %u Errors, %u Warnings, %u Remarks",
+        "\nCompilation complete. %u Errors, %u Warnings, %u Remarks",
         Gbl_ExceptionCount[ASL_ERROR],
         Gbl_ExceptionCount[ASL_WARNING] +
             Gbl_ExceptionCount[ASL_WARNING2] +
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/compiler/aslwalks.c
--- a/head/sys/contrib/dev/acpica/compiler/aslwalks.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/compiler/aslwalks.c	Tue Dec 06 20:26:16 2011 +0200
@@ -1032,6 +1032,7 @@
     ACPI_PARSE_OBJECT       *ArgNode;
     ACPI_PARSE_OBJECT       *PrevArgNode = NULL;
     const ACPI_OPCODE_INFO  *OpInfo;
+    ACPI_NAMESPACE_NODE     *Node;
 
 
     OpInfo = AcpiPsGetOpcodeInfo (Op->Asl.AmlOpcode);
@@ -1156,6 +1157,78 @@
         }
         break;
 
+    case PARSEOP_CONNECTION:
+        /*
+         * Ensure that the referenced operation region has the correct SPACE_ID.
+         * From the grammar/parser, we know the parent is a FIELD definition.
+         */
+        ArgNode = Op->Asl.Parent;       /* Field definition */
+        ArgNode = ArgNode->Asl.Child;   /* First child is the OpRegion Name */
+        Node = ArgNode->Asl.Node;       /* OpRegion namespace node */
+
+        ArgNode = Node->Op;             /* OpRegion definition */
+        ArgNode = ArgNode->Asl.Child;   /* First child is the OpRegion Name */
+        ArgNode = ArgNode->Asl.Next;    /* Next peer is the SPACE_ID (what we want) */
+
+        /*
+         * The Connection() operator is only valid for the following operation
+         * region SpaceIds: GeneralPurposeIo and GenericSerialBus.
+         */
+        if ((ArgNode->Asl.Value.Integer != ACPI_ADR_SPACE_GPIO) &&
+            (ArgNode->Asl.Value.Integer != ACPI_ADR_SPACE_GSBUS))
+        {
+            AslError (ASL_ERROR, ASL_MSG_CONNECTION_INVALID, Op, NULL);
+        }
+        break;
+
+    case PARSEOP_FIELD:
+        /*
+         * Ensure that fields for GeneralPurposeIo and GenericSerialBus
+         * contain at least one Connection() operator
+         */
+        ArgNode = Op->Asl.Child;        /* 1st child is the OpRegion Name */
+        Node = ArgNode->Asl.Node;       /* OpRegion namespace node */
+        if (!Node)
+        {
+            break;
+        }
+
+        ArgNode = Node->Op;             /* OpRegion definition */
+        ArgNode = ArgNode->Asl.Child;   /* First child is the OpRegion Name */
+        ArgNode = ArgNode->Asl.Next;    /* Next peer is the SPACE_ID (what we want) */
+
+        /* We are only interested in GeneralPurposeIo and GenericSerialBus */
+
+        if ((ArgNode->Asl.Value.Integer != ACPI_ADR_SPACE_GPIO) &&
+            (ArgNode->Asl.Value.Integer != ACPI_ADR_SPACE_GSBUS))
+        {
+            break;
+        }
+
+        ArgNode = Op->Asl.Child;        /* 1st child is the OpRegion Name */
+        ArgNode = ArgNode->Asl.Next;    /* AccessType */
+        ArgNode = ArgNode->Asl.Next;    /* LockRule */
+        ArgNode = ArgNode->Asl.Next;    /* UpdateRule */
+        ArgNode = ArgNode->Asl.Next;    /* Start of FieldUnitList */
+
+        /* Walk the FieldUnitList */
+
+        while (ArgNode)
+        {
+            if (ArgNode->Asl.ParseOpcode == PARSEOP_CONNECTION)
+            {
+                break;
+            }
+            else if (ArgNode->Asl.ParseOpcode == PARSEOP_NAMESEG)
+            {
+                AslError (ASL_ERROR, ASL_MSG_CONNECTION_MISSING, ArgNode, NULL);
+                break;
+            }
+
+            ArgNode = ArgNode->Asl.Next;
+        }
+        break;
+
     default:
         break;
     }
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/compiler/dtcompile.c
--- a/head/sys/contrib/dev/acpica/compiler/dtcompile.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/compiler/dtcompile.c	Tue Dec 06 20:26:16 2011 +0200
@@ -310,6 +310,17 @@
         Status = DtCompileRsdp (FieldList);
         return (Status);
     }
+    else if (ACPI_COMPARE_NAME (Signature, ACPI_SIG_S3PT))
+    {
+        Status = DtCompileS3pt (FieldList);
+        if (ACPI_FAILURE (Status))
+        {
+            return (Status);
+        }
+
+        DtSetTableLength ();
+        return (Status);
+    }
 
     /*
      * All other tables must use the common ACPI table header. Insert the
@@ -329,7 +340,7 @@
     /* Validate the signature via the ACPI table list */
 
     TableData = AcpiDmGetTableData (Signature);
-    if (!TableData)
+    if (!TableData || Gbl_CompileGeneric)
     {
         DtCompileGeneric ((void **) FieldList);
         goto Out;
@@ -411,6 +422,7 @@
     UINT8                   FieldType;
     UINT8                   *Buffer;
     UINT8                   *FlagBuffer = NULL;
+    UINT32                  CurrentFlagByteOffset = 0;
     ACPI_STATUS             Status;
 
 
@@ -442,6 +454,11 @@
      */
     for (; Info->Name; Info++)
     {
+        if (Info->Opcode == ACPI_DMT_EXTRA_TEXT)
+        {
+            continue;
+        }
+
         if (!LocalField)
         {
             sprintf (MsgBuffer, "Found NULL field - Field name \"%s\" needed",
@@ -472,6 +489,7 @@
             *Field = LocalField;
 
             FlagBuffer = Buffer;
+            CurrentFlagByteOffset = Info->Offset;
             break;
 
         case DT_FIELD_TYPE_FLAG:
@@ -480,6 +498,14 @@
 
             if (FlagBuffer)
             {
+                /*
+                 * We must increment the FlagBuffer when we have crossed
+                 * into the next flags byte within the flags field
+                 * of type DT_FIELD_TYPE_FLAGS_INTEGER.
+                 */
+                FlagBuffer += (Info->Offset - CurrentFlagByteOffset);
+                CurrentFlagByteOffset = Info->Offset;
+
                 DtCompileFlag (FlagBuffer, LocalField, Info);
             }
             else
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/compiler/dtcompiler.h
--- a/head/sys/contrib/dev/acpica/compiler/dtcompiler.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/compiler/dtcompiler.h	Tue Dec 06 20:26:16 2011 +0200
@@ -399,6 +399,10 @@
     void                    **PFieldList);
 
 ACPI_STATUS
+DtCompileFpdt (
+    void                    **PFieldList);
+
+ACPI_STATUS
 DtCompileHest (
     void                    **PFieldList);
 
@@ -415,14 +419,26 @@
     void                    **PFieldList);
 
 ACPI_STATUS
+DtCompileMpst (
+    void                    **PFieldList);
+
+ACPI_STATUS
 DtCompileMsct (
     void                    **PFieldList);
 
 ACPI_STATUS
+DtCompilePmtt (
+    void                    **PFieldList);
+
+ACPI_STATUS
 DtCompileRsdt (
     void                    **PFieldList);
 
 ACPI_STATUS
+DtCompileS3pt (
+    DT_FIELD                **PFieldList);
+
+ACPI_STATUS
 DtCompileSlic (
     void                    **PFieldList);
 
@@ -459,6 +475,7 @@
 extern const unsigned char  TemplateAsf[];
 extern const unsigned char  TemplateBoot[];
 extern const unsigned char  TemplateBert[];
+extern const unsigned char  TemplateBgrt[];
 extern const unsigned char  TemplateCpep[];
 extern const unsigned char  TemplateDbgp[];
 extern const unsigned char  TemplateDmar[];
@@ -466,14 +483,19 @@
 extern const unsigned char  TemplateEinj[];
 extern const unsigned char  TemplateErst[];
 extern const unsigned char  TemplateFadt[];
+extern const unsigned char  TemplateFpdt[];
+extern const unsigned char  TemplateGtdt[];
 extern const unsigned char  TemplateHest[];
 extern const unsigned char  TemplateHpet[];
 extern const unsigned char  TemplateIvrs[];
 extern const unsigned char  TemplateMadt[];
 extern const unsigned char  TemplateMcfg[];
 extern const unsigned char  TemplateMchi[];
+extern const unsigned char  TemplateMpst[];
 extern const unsigned char  TemplateMsct[];
+extern const unsigned char  TemplatePmtt[];
 extern const unsigned char  TemplateRsdt[];
+extern const unsigned char  TemplateS3pt[];
 extern const unsigned char  TemplateSbst[];
 extern const unsigned char  TemplateSlic[];
 extern const unsigned char  TemplateSlit[];
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/compiler/dtfield.c
--- a/head/sys/contrib/dev/acpica/compiler/dtfield.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/compiler/dtfield.c	Tue Dec 06 20:26:16 2011 +0200
@@ -523,12 +523,25 @@
         break;
 
 
+    case ACPI_DMT_FLAGS1:
+
+        BitPosition = 1;
+        BitLength = 2;
+        break;
+
+
     case ACPI_DMT_FLAGS2:
 
         BitPosition = 2;
         BitLength = 2;
         break;
 
+    case ACPI_DMT_FLAGS4:
+
+        BitPosition = 4;
+        BitLength = 2;
+        break;
+
     default:
 
         DtFatal (ASL_MSG_COMPILER_INTERNAL, Field, "Invalid flag opcode");
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/compiler/dtsubtable.c
--- a/head/sys/contrib/dev/acpica/compiler/dtsubtable.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/compiler/dtsubtable.c	Tue Dec 06 20:26:16 2011 +0200
@@ -296,6 +296,11 @@
 
     for (; Info->Name; Info++)
     {
+        if (Info->Opcode == ACPI_DMT_EXTRA_TEXT)
+        {
+            continue;
+        }
+
         if (!Field)
         {
             goto Error;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/compiler/dttable.c
--- a/head/sys/contrib/dev/acpica/compiler/dttable.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/compiler/dttable.c	Tue Dec 06 20:26:16 2011 +0200
@@ -660,6 +660,90 @@
         }
 
         DtInsertSubtable (ParentTable, Subtable);
+
+        if (Revision >= 5)
+        {
+            Status = DtCompileTable (PFieldList, AcpiDmTableInfoFadt5,
+                        &Subtable, TRUE);
+            if (ACPI_FAILURE (Status))
+            {
+                return (Status);
+            }
+
+            DtInsertSubtable (ParentTable, Subtable);
+        }
+    }
+
+    return (AE_OK);
+}
+
+
+/******************************************************************************
+ *
+ * FUNCTION:    DtCompileFpdt
+ *
+ * PARAMETERS:  List                - Current field list pointer
+ *
+ * RETURN:      Status
+ *
+ * DESCRIPTION: Compile FPDT.
+ *
+ *****************************************************************************/
+
+ACPI_STATUS
+DtCompileFpdt (
+    void                    **List)
+{
+    ACPI_STATUS             Status;
+    ACPI_FPDT_HEADER        *FpdtHeader;
+    DT_SUBTABLE             *Subtable;
+    DT_SUBTABLE             *ParentTable;
+    ACPI_DMTABLE_INFO       *InfoTable;
+    DT_FIELD                **PFieldList = (DT_FIELD **) List;
+    DT_FIELD                *SubtableStart;
+
+
+    while (*PFieldList)
+    {
+        SubtableStart = *PFieldList;
+        Status = DtCompileTable (PFieldList, AcpiDmTableInfoFpdtHdr,
+                    &Subtable, TRUE);
+        if (ACPI_FAILURE (Status))
+        {
+            return (Status);
+        }
+
+        ParentTable = DtPeekSubtable ();
+        DtInsertSubtable (ParentTable, Subtable);
+        DtPushSubtable (Subtable);
+
+        FpdtHeader = ACPI_CAST_PTR (ACPI_FPDT_HEADER, Subtable->Buffer);
+
+        switch (FpdtHeader->Type)
+        {
+        case ACPI_FPDT_TYPE_BOOT:
+            InfoTable = AcpiDmTableInfoFpdt0;
+            break;
+
+        case ACPI_FPDT_TYPE_S3PERF:
+            InfoTable = AcpiDmTableInfoFpdt1;
+            break;
+
+        default:
+            DtFatal (ASL_MSG_UNKNOWN_SUBTABLE, SubtableStart, "FPDT");
+            return (AE_ERROR);
+            break;
+        }
+
+        Status = DtCompileTable (PFieldList, InfoTable, &Subtable, TRUE);
+        if (ACPI_FAILURE (Status))
+        {
+            return (Status);
+        }
+
+        ParentTable = DtPeekSubtable ();
+        DtInsertSubtable (ParentTable, Subtable);
+        DtPopSubtable ();
     }
 
     return (AE_OK);
@@ -1025,6 +1109,12 @@
         case ACPI_MADT_TYPE_LOCAL_X2APIC_NMI:
             InfoTable = AcpiDmTableInfoMadt10;
             break;
+        case ACPI_MADT_TYPE_GENERIC_INTERRUPT:
+            InfoTable = AcpiDmTableInfoMadt11;
+            break;
+        case ACPI_MADT_TYPE_GENERIC_DISTRIBUTOR:
+            InfoTable = AcpiDmTableInfoMadt12;
+            break;
         default:
             DtFatal (ASL_MSG_UNKNOWN_SUBTABLE, SubtableStart, "MADT");
             return (AE_ERROR);
@@ -1072,6 +1162,143 @@
 
 /******************************************************************************
  *
+ * FUNCTION:    DtCompileMpst
+ *
+ * PARAMETERS:  List                - Current field list pointer
+ *
+ * RETURN:      Status
+ *
+ * DESCRIPTION: Compile MPST.
+ *
+ *****************************************************************************/
+
+ACPI_STATUS
+DtCompileMpst (
+    void                    **List)
+{
+    ACPI_STATUS             Status;
+    DT_SUBTABLE             *Subtable;
+    DT_SUBTABLE             *ParentTable;
+    DT_FIELD                **PFieldList = (DT_FIELD **) List;
+    ACPI_MPST_CHANNEL       *MpstChannelInfo;
+    ACPI_MPST_POWER_NODE    *MpstPowerNode;
+    ACPI_MPST_DATA_HDR      *MpstDataHeader;
+    UINT16                  SubtableCount;
+    UINT8                   PowerStateCount;
+    UINT8                   ComponentCount;
+
+
+    /* Main table */
+
+    Status = DtCompileTable (PFieldList, AcpiDmTableInfoMpst, &Subtable, TRUE);
+    if (ACPI_FAILURE (Status))
+    {
+        return (Status);
+    }
+
+    ParentTable = DtPeekSubtable ();
+    DtInsertSubtable (ParentTable, Subtable);
+    DtPushSubtable (Subtable);
+
+    MpstChannelInfo = ACPI_CAST_PTR (ACPI_MPST_CHANNEL, Subtable->Buffer);
+    SubtableCount = MpstChannelInfo->PowerNodeCount;
+
+    while (*PFieldList && SubtableCount)
+    {
+        /* Subtable: Memory Power Node(s) */
+
+        Status = DtCompileTable (PFieldList, AcpiDmTableInfoMpst0,
+                    &Subtable, TRUE);
+        if (ACPI_FAILURE (Status))
+        {
+            return (Status);
+        }
+
+        ParentTable = DtPeekSubtable ();
+        DtInsertSubtable (ParentTable, Subtable);
+        DtPushSubtable (Subtable);
+
+        MpstPowerNode = ACPI_CAST_PTR (ACPI_MPST_POWER_NODE, Subtable->Buffer);
+        PowerStateCount = MpstPowerNode->NumPowerStates;
+        ComponentCount = MpstPowerNode->NumPhysicalComponents;
+
+        ParentTable = DtPeekSubtable ();
+
+        /* Sub-subtables - Memory Power State Structure(s) */
+
+        while (*PFieldList && PowerStateCount)
+        {
+            Status = DtCompileTable (PFieldList, AcpiDmTableInfoMpst0A,
+                        &Subtable, TRUE);
+            if (ACPI_FAILURE (Status))
+            {
+                return (Status);
+            }
+
+            DtInsertSubtable (ParentTable, Subtable);
+            PowerStateCount--;
+        }
+
+        /* Sub-subtables - Physical Component ID Structure(s) */
+
+        while (*PFieldList && ComponentCount)
+        {
+            Status = DtCompileTable (PFieldList, AcpiDmTableInfoMpst0B,
+                        &Subtable, TRUE);
+            if (ACPI_FAILURE (Status))
+            {
+                return (Status);
+            }
+
+            DtInsertSubtable (ParentTable, Subtable);
+            ComponentCount--;
+        }
+
+        SubtableCount--;
+        DtPopSubtable ();
+    }
+
+    /* Subtable: Count of Memory Power State Characteristic structures */
+
+    DtPopSubtable ();
+
+    Status = DtCompileTable (PFieldList, AcpiDmTableInfoMpst1, &Subtable, TRUE);
+    if (ACPI_FAILURE (Status))
+    {
+        return (Status);
+    }
+
+    ParentTable = DtPeekSubtable ();
+    DtInsertSubtable (ParentTable, Subtable);
+    DtPushSubtable (Subtable);
+
+    MpstDataHeader = ACPI_CAST_PTR (ACPI_MPST_DATA_HDR, Subtable->Buffer);
+    SubtableCount = MpstDataHeader->CharacteristicsCount;
+
+    ParentTable = DtPeekSubtable ();
+
+    /* Subtable: Memory Power State Characteristics structure(s) */
+
+    while (*PFieldList && SubtableCount)
+    {
+        Status = DtCompileTable (PFieldList, AcpiDmTableInfoMpst2,
+                    &Subtable, TRUE);
+        if (ACPI_FAILURE (Status))
+        {
+            return (Status);
+        }
+
+        DtInsertSubtable (ParentTable, Subtable);
+        SubtableCount--;
+    }
+
+    DtPopSubtable ();
+    return (AE_OK);
+}
+
+
+/******************************************************************************
+ *
  * FUNCTION:    DtCompileMsct
  *
  * PARAMETERS:  List                - Current field list pointer
@@ -1097,6 +1324,147 @@
 
 /******************************************************************************
  *
+ * FUNCTION:    DtCompilePmtt
+ *
+ * PARAMETERS:  List                - Current field list pointer
+ *
+ * RETURN:      Status
+ *
+ * DESCRIPTION: Compile PMTT.
+ *
+ *****************************************************************************/
+
+ACPI_STATUS
+DtCompilePmtt (
+    void                    **List)
+{
+    ACPI_STATUS             Status;
+    DT_SUBTABLE             *Subtable;
+    DT_SUBTABLE             *ParentTable;
+    DT_FIELD                **PFieldList = (DT_FIELD **) List;
+    DT_FIELD                *SubtableStart;
+    ACPI_PMTT_HEADER        *PmttHeader;
+    ACPI_PMTT_CONTROLLER    *PmttController;
+    UINT16                  DomainCount;
+    UINT8                   PrevType = ACPI_PMTT_TYPE_SOCKET;
+
+
+    /* Main table */
+
+    Status = DtCompileTable (PFieldList, AcpiDmTableInfoPmtt, &Subtable, TRUE);
+    if (ACPI_FAILURE (Status))
+    {
+        return (Status);
+    }
+
+    ParentTable = DtPeekSubtable ();
+    DtInsertSubtable (ParentTable, Subtable);
+    DtPushSubtable (Subtable);
+
+    while (*PFieldList)
+    {
+        SubtableStart = *PFieldList;
+        Status = DtCompileTable (PFieldList, AcpiDmTableInfoPmttHdr,
+                    &Subtable, TRUE);
+        if (ACPI_FAILURE (Status))
+        {
+            return (Status);
+        }
+
+        PmttHeader = ACPI_CAST_PTR (ACPI_PMTT_HEADER, Subtable->Buffer);
+        while (PrevType >= PmttHeader->Type)
+        {
+            DtPopSubtable ();
+
+            if (PrevType == ACPI_PMTT_TYPE_SOCKET)
+            {
+                break;
+            }
+            PrevType--;
+        }
+        PrevType = PmttHeader->Type;
+
+        ParentTable = DtPeekSubtable ();
+        DtInsertSubtable (ParentTable, Subtable);
+        DtPushSubtable (Subtable);
+
+        switch (PmttHeader->Type)
+        {
+        case ACPI_PMTT_TYPE_SOCKET:
+
+            /* Subtable: Socket Structure */
+
+            Status = DtCompileTable (PFieldList, AcpiDmTableInfoPmtt0,
+                    &Subtable, TRUE);
+            if (ACPI_FAILURE (Status))
+            {
+                return (Status);
+            }
+
+            ParentTable = DtPeekSubtable ();
+            DtInsertSubtable (ParentTable, Subtable);
+            break;
+
+        case ACPI_PMTT_TYPE_CONTROLLER:
+
+            /* Subtable: Memory Controller Structure */
+
+            Status = DtCompileTable (PFieldList, AcpiDmTableInfoPmtt1,
+                    &Subtable, TRUE);
+            if (ACPI_FAILURE (Status))
+            {
+                return (Status);
+            }
+
+            ParentTable = DtPeekSubtable ();
+            DtInsertSubtable (ParentTable, Subtable);
+
+            PmttController = ACPI_CAST_PTR (ACPI_PMTT_CONTROLLER,
+                (Subtable->Buffer - sizeof (ACPI_PMTT_HEADER)));
+            DomainCount = PmttController->DomainCount;
+
+            while (DomainCount)
+            {
+                Status = DtCompileTable (PFieldList, AcpiDmTableInfoPmtt1a,
+                    &Subtable, TRUE);
+                if (ACPI_FAILURE (Status))
+                {
+                    return (Status);
+                }
+
+                DtInsertSubtable (ParentTable, Subtable);
+                DomainCount--;
+            }
+            break;
+
+        case ACPI_PMTT_TYPE_DIMM:
+
+            /* Subtable: Physical Component Structure */
+
+            Status = DtCompileTable (PFieldList, AcpiDmTableInfoPmtt2,
+                    &Subtable, TRUE);
+            if (ACPI_FAILURE (Status))
+            {
+                return (Status);
+            }
+
+            ParentTable = DtPeekSubtable ();
+            DtInsertSubtable (ParentTable, Subtable);
+            break;
+
+        default:
+
+            DtFatal (ASL_MSG_UNKNOWN_SUBTABLE, SubtableStart, "PMTT");
+            return (AE_ERROR);
+        }
+    }
+
+    return (Status);
+}
+
+
+/******************************************************************************
+ *
  * FUNCTION:    DtCompileRsdt
  *
  * PARAMETERS:  List                - Current field list pointer
@@ -1134,6 +1502,85 @@
 
 /******************************************************************************
  *
+ * FUNCTION:    DtCompileS3pt
+ *
+ * PARAMETERS:  PFieldList          - Current field list pointer
+ *
+ * RETURN:      Status
+ *
+ * DESCRIPTION: Compile S3PT (Pointed to by FPDT)
+ *
+ *****************************************************************************/
+
+ACPI_STATUS
+DtCompileS3pt (
+    DT_FIELD                **PFieldList)
+{
+    ACPI_STATUS             Status;
+    ACPI_S3PT_HEADER        *S3ptHeader;
+    DT_SUBTABLE             *Subtable;
+    DT_SUBTABLE             *ParentTable;
+    ACPI_DMTABLE_INFO       *InfoTable;
+    DT_FIELD                *SubtableStart;
+
+
+    Status = DtCompileTable (PFieldList, AcpiDmTableInfoS3pt,
+                &Gbl_RootTable, TRUE);
+    if (ACPI_FAILURE (Status))
+    {
+        return (Status);
+    }
+
+    DtPushSubtable (Gbl_RootTable);
+
+    while (*PFieldList)
+    {
+        SubtableStart = *PFieldList;
+        Status = DtCompileTable (PFieldList, AcpiDmTableInfoS3ptHdr,
+                    &Subtable, TRUE);
+        if (ACPI_FAILURE (Status))
+        {
+            return (Status);
+        }
+
+        ParentTable = DtPeekSubtable ();
+        DtInsertSubtable (ParentTable, Subtable);
+        DtPushSubtable (Subtable);
+
+        S3ptHeader = ACPI_CAST_PTR (ACPI_S3PT_HEADER, Subtable->Buffer);
+
+        switch (S3ptHeader->Type)
+        {
+        case ACPI_S3PT_TYPE_RESUME:
+            InfoTable = AcpiDmTableInfoS3pt0;
+            break;
+
+        case ACPI_S3PT_TYPE_SUSPEND:
+            InfoTable = AcpiDmTableInfoS3pt1;
+            break;
+
+        default:
+            DtFatal (ASL_MSG_UNKNOWN_SUBTABLE, SubtableStart, "S3PT");
+            return (AE_ERROR);
+        }
+
+        Status = DtCompileTable (PFieldList, InfoTable, &Subtable, TRUE);
+        if (ACPI_FAILURE (Status))
+        {
+            return (Status);
+        }
+
+        ParentTable = DtPeekSubtable ();
+        DtInsertSubtable (ParentTable, Subtable);
+        DtPopSubtable ();
+    }
+
+    return (AE_OK);
+}
+
+
+/******************************************************************************
+ *
  * FUNCTION:    DtCompileSlic
  *
  * PARAMETERS:  List                - Current field list pointer
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/compiler/dttemplate.h
--- a/head/sys/contrib/dev/acpica/compiler/dttemplate.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/compiler/dttemplate.h	Tue Dec 06 20:26:16 2011 +0200
@@ -87,6 +87,17 @@
     0x01,0x00                                 /* 00000070    ".."       */
 };
 
+const unsigned char TemplateBgrt[] =
+{
+    0x42,0x47,0x52,0x54,0x38,0x00,0x00,0x00,  /* 00000000    "BGRT8..." */
+    0x01,0x0D,0x49,0x4E,0x54,0x45,0x4C,0x20,  /* 00000008    "..INTEL " */
+    0x54,0x45,0x4D,0x50,0x4C,0x41,0x54,0x45,  /* 00000010    "TEMPLATE" */
+    0x01,0x00,0x00,0x00,0x49,0x4E,0x54,0x4C,  /* 00000018    "....INTL" */
+    0x23,0x06,0x11,0x20,0x01,0x00,0x00,0x00,  /* 00000020    "#.. ...." */
+    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,  /* 00000028    "........" */
+    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00   /* 00000030    "........" */
+};
+
 const unsigned char TemplateBert[] =
 {
     0x42,0x45,0x52,0x54,0x30,0x00,0x00,0x00,  /* 00000000    "BERT0..." */
@@ -326,6 +337,37 @@
     0x00,0x00,0x00,0x00                       /* 000000F0    "...."     */
 };
 
+const unsigned char TemplateFpdt[] =
+{
+    0x46,0x50,0x44,0x54,0x64,0x00,0x00,0x00,  /* 00000000    "FPDTd..." */
+    0x01,0xBD,0x49,0x4E,0x54,0x45,0x4C,0x20,  /* 00000008    "..INTEL " */
+    0x54,0x45,0x4D,0x50,0x4C,0x41,0x54,0x45,  /* 00000010    "TEMPLATE" */
+    0x01,0x00,0x00,0x00,0x49,0x4E,0x54,0x4C,  /* 00000018    "....INTL" */
+    0x04,0x08,0x11,0x20,0x00,0x00,0x30,0x01,  /* 00000020    "... ..0." */
+    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,  /* 00000028    "........" */
+    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,  /* 00000030    "........" */
+    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,  /* 00000038    "........" */
+    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,  /* 00000040    "........" */
+    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,  /* 00000048    "........" */
+    0x00,0x00,0x00,0x00,0x01,0x00,0x10,0x01,  /* 00000050    "........" */
+    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,  /* 00000058    "........" */
+    0x00,0x00,0x00,0x00                       /* 00000060    "...."     */
+};
+
+const unsigned char TemplateGtdt[] =
+{
+    0x47,0x54,0x44,0x54,0x50,0x00,0x00,0x00,  /* 00000000    "GTDTP..." */
+    0x01,0xF1,0x49,0x4E,0x54,0x45,0x4C,0x20,  /* 00000008    "..INTEL " */
+    0x54,0x45,0x4D,0x50,0x4C,0x41,0x54,0x45,  /* 00000010    "TEMPLATE" */
+    0x01,0x00,0x00,0x00,0x49,0x4E,0x54,0x4C,  /* 00000018    "....INTL" */
+    0x23,0x06,0x11,0x20,0x00,0x00,0x00,0x00,  /* 00000020    "#.. ...." */
+    0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,  /* 00000028    "........" */
+    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,  /* 00000030    "........" */
+    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,  /* 00000038    "........" */
+    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,  /* 00000040    "........" */
+    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00   /* 00000048    "........" */
+};
+
 const unsigned char TemplateHest[] =
 {
     0x48,0x45,0x53,0x54,0xD4,0x01,0x00,0x00,  /* 00000000    "HEST...." */
@@ -428,13 +470,15 @@
     0x00,0x00,0x00,0x00                       /* 000000B8    "...."     */
 };
 
+/* MADT with ACPI 5.0 subtables */
+
 const unsigned char TemplateMadt[] =
 {
-    0x41,0x50,0x49,0x43,0xB6,0x00,0x00,0x00,  /* 00000000    "APIC...." */
-    0x01,0x45,0x49,0x4E,0x54,0x45,0x4C,0x20,  /* 00000008    ".EINTEL " */
+    0x41,0x50,0x49,0x43,0xF6,0x00,0x00,0x00,  /* 00000000    "APIC...." */
+    0x01,0xB0,0x49,0x4E,0x54,0x45,0x4C,0x20,  /* 00000008    "..INTEL " */
     0x54,0x45,0x4D,0x50,0x4C,0x41,0x54,0x45,  /* 00000010    "TEMPLATE" */
     0x01,0x00,0x00,0x00,0x49,0x4E,0x54,0x4C,  /* 00000018    "....INTL" */
-    0x28,0x05,0x10,0x20,0x00,0x00,0x00,0x00,  /* 00000020    "(.. ...." */
+    0x23,0x06,0x11,0x20,0x00,0x00,0x00,0x00,  /* 00000020    "#.. ...." */
     0x01,0x00,0x00,0x00,0x00,0x08,0x00,0x00,  /* 00000028    "........" */
     0x01,0x00,0x00,0x00,0x01,0x0C,0x01,0x00,  /* 00000030    "........" */
     0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,  /* 00000038    "........" */
@@ -452,7 +496,15 @@
     0x00,0x00,0x09,0x10,0x00,0x00,0x00,0x00,  /* 00000098    "........" */
     0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,  /* 000000A0    "........" */
     0x00,0x00,0x0A,0x0C,0x05,0x00,0x00,0x00,  /* 000000A8    "........" */
-    0x00,0x00,0x00,0x00,0x00,0x00             /* 000000B0    "......"   */
+    0x00,0x00,0x00,0x00,0x00,0x00,0x0B,0x28,  /* 000000B0    ".......(" */
+    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,  /* 000000B8    "........" */
+    0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,  /* 000000C0    "........" */
+    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,  /* 000000C8    "........" */
+    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,  /* 000000D0    "........" */
+    0x00,0x00,0x00,0x00,0x00,0x00,0x0C,0x18,  /* 000000D8    "........" */
+    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,  /* 000000E0    "........" */
+    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,  /* 000000E8    "........" */
+    0x00,0x00,0x00,0x00,0x00,0x00             /* 000000F0    "......"   */
 };
 
 const unsigned char TemplateMcfg[] =
@@ -480,6 +532,24 @@
     0x00,0x00,0x00,0x00,0x00                  /* 00000040    "....."    */
 };
 
+const unsigned char TemplateMpst[] =
+{
+    0x4D,0x50,0x53,0x54,0x6E,0x00,0x00,0x00,  /* 00000000    "MPSTn..." */
+    0x01,0x98,0x49,0x4E,0x54,0x45,0x4C,0x20,  /* 00000008    "..INTEL " */
+    0x54,0x45,0x4D,0x50,0x4C,0x41,0x54,0x45,  /* 00000010    "TEMPLATE" */
+    0x01,0x00,0x00,0x00,0x49,0x4E,0x54,0x4C,  /* 00000018    "....INTL" */
+    0x04,0x08,0x11,0x20,0x00,0x00,0x00,0x00,  /* 00000020    "... ...." */
+    0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,  /* 00000028    "........" */
+    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,  /* 00000030    "........" */
+    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,  /* 00000038    "........" */
+    0x00,0x00,0x02,0x03,0x00,0x00,0x00,0x00,  /* 00000040    "........" */
+    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,  /* 00000048    "........" */
+    0x01,0x00,0x41,0x00,0x00,0x00,0x00,0x00,  /* 00000050    "..A....." */
+    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,  /* 00000058    "........" */
+    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,  /* 00000060    "........" */
+    0x00,0x00,0x00,0x00,0x00,0x00             /* 00000068    "......"   */
+};
+
 const unsigned char TemplateMsct[] =
 {
     0x4D,0x53,0x43,0x54,0x90,0x00,0x00,0x00,  /* 00000000    "MSCT...." */
@@ -502,6 +572,33 @@
     0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00   /* 00000088    "........" */
 };
 
+const unsigned char TemplatePmtt[] =
+{
+    0x50,0x4D,0x54,0x54,0xB4,0x00,0x00,0x00,  /* 00000000    "PMTT...." */
+    0x01,0x3A,0x49,0x4E,0x54,0x45,0x4C,0x20,  /* 00000008    ".:INTEL " */
+    0x54,0x45,0x4D,0x50,0x4C,0x41,0x54,0x45,  /* 00000010    "TEMPLATE" */
+    0x01,0x00,0x00,0x00,0x49,0x4E,0x54,0x4C,  /* 00000018    "....INTL" */
+    0x26,0x08,0x11,0x20,0x00,0x00,0x00,0x00,  /* 00000020    "&.. ...." */
+    0x00,0x00,0x80,0x00,0x01,0x00,0x00,0x00,  /* 00000028    "........" */
+    0x00,0x00,0x00,0x00,0x01,0x00,0x54,0x00,  /* 00000030    "......T." */
+    0x05,0x00,0x00,0x00,0x00,0x00,0x00,0x00,  /* 00000038    "........" */
+    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,  /* 00000040    "........" */
+    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,  /* 00000048    "........" */
+    0x00,0x00,0x03,0x00,0x00,0x00,0x00,0x00,  /* 00000050    "........" */
+    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,  /* 00000058    "........" */
+    0x02,0x00,0x14,0x00,0x02,0x00,0x00,0x00,  /* 00000060    "........" */
+    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,  /* 00000068    "........" */
+    0x00,0x00,0x00,0x00,0x02,0x00,0x14,0x00,  /* 00000070    "........" */
+    0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x00,  /* 00000078    "........" */
+    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,  /* 00000080    "........" */
+    0x01,0x00,0x20,0x00,0x01,0x00,0x00,0x00,  /* 00000088    ".. ....." */
+    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,  /* 00000090    "........" */
+    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,  /* 00000098    "........" */
+    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,  /* 000000A0    "........" */
+    0x00,0x00,0x0C,0x00,0x01,0x00,0x00,0x00,  /* 000000A8    "........" */
+    0x00,0x00,0x00,0x00                       /* 000000B0    "...."     */
+};
+
 const unsigned char TemplateRsdp[] =
 {
     0x52,0x53,0x44,0x20,0x50,0x54,0x52,0x20,  /* 00000000    "RSD PTR " */
@@ -524,6 +621,17 @@
     0x80,0x00,0x00,0x00                       /* 00000040    "...."     */
 };
 
+const unsigned char TemplateS3pt[] =
+{
+    0x53,0x33,0x50,0x54,0x34,0x00,0x00,0x00,  /* 00000000    "S3PT4..." */
+    0x00,0x00,0x18,0x01,0x00,0x00,0x00,0x00,  /* 00000008    "........" */
+    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,  /* 00000010    "........" */
+    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,  /* 00000018    "........" */
+    0x01,0x00,0x14,0x01,0x00,0x00,0x00,0x00,  /* 00000020    "........" */
+    0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,  /* 00000028    "........" */
+    0x00,0x00,0x00,0x00                       /* 00000030    "...."     */
+};
+
 const unsigned char TemplateSbst[] =
 {
     0x53,0x42,0x53,0x54,0x30,0x00,0x00,0x00,  /* 00000000    "SBST0..." */
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/compiler/dtutils.c
--- a/head/sys/contrib/dev/acpica/compiler/dtutils.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/compiler/dtutils.c	Tue Dec 06 20:26:16 2011 +0200
@@ -384,7 +384,9 @@
     case ACPI_DMT_FLAG6:
     case ACPI_DMT_FLAG7:
     case ACPI_DMT_FLAGS0:
+    case ACPI_DMT_FLAGS1:
     case ACPI_DMT_FLAGS2:
+    case ACPI_DMT_FLAGS4:
         Type = DT_FIELD_TYPE_FLAG;
         break;
 
@@ -510,8 +512,11 @@
     case ACPI_DMT_FLAG6:
     case ACPI_DMT_FLAG7:
     case ACPI_DMT_FLAGS0:
+    case ACPI_DMT_FLAGS1:
     case ACPI_DMT_FLAGS2:
+    case ACPI_DMT_FLAGS4:
     case ACPI_DMT_LABEL:
+    case ACPI_DMT_EXTRA_TEXT:
         ByteLength = 0;
         break;
 
@@ -521,6 +526,7 @@
     case ACPI_DMT_ACCWIDTH:
     case ACPI_DMT_IVRS:
     case ACPI_DMT_MADT:
+    case ACPI_DMT_PMTT:
     case ACPI_DMT_SRAT:
     case ACPI_DMT_ASF:
     case ACPI_DMT_HESTNTYP:
@@ -550,6 +556,11 @@
         ByteLength = 4;
         break;
 
+    case ACPI_DMT_UINT40:
+        ByteLength = 5;
+        break;
+
+    case ACPI_DMT_UINT48:
     case ACPI_DMT_NAME6:
         ByteLength = 6;
         break;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/debugger/dbcmds.c
--- a/head/sys/contrib/dev/acpica/debugger/dbcmds.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/debugger/dbcmds.c	Tue Dec 06 20:26:16 2011 +0200
@@ -46,6 +46,7 @@
 #include <contrib/dev/acpica/include/accommon.h>
 #include <contrib/dev/acpica/include/acevents.h>
 #include <contrib/dev/acpica/include/acdebug.h>
+#include <contrib/dev/acpica/include/acnamesp.h>
 #include <contrib/dev/acpica/include/acresrc.h>
 #include <contrib/dev/acpica/include/actables.h>
 
@@ -69,6 +70,18 @@
     ACPI_NAMESPACE_NODE     *Node,
     char                    *Name);
 
+static ACPI_STATUS
+AcpiDbResourceCallback (
+    ACPI_RESOURCE           *Resource,
+    void                    *Context);
+
+static ACPI_STATUS
+AcpiDbDeviceResources (
+    ACPI_HANDLE             ObjHandle,
+    UINT32                  NestingLevel,
+    void                    *Context,
+    void                    **ReturnValue);
+
 
 /*******************************************************************************
  *
@@ -456,6 +469,78 @@
 
 /*******************************************************************************
  *
+ * FUNCTION:    AcpiDbDisplayTemplate
+ *
+ * PARAMETERS:  BufferArg           - Buffer name or addrss
+ *
+ * RETURN:      None
+ *
+ * DESCRIPTION: Dump a buffer that contains a resource template
+ *
+ ******************************************************************************/
+
+void
+AcpiDbDisplayTemplate (
+    char                    *BufferArg)
+{
+    ACPI_NAMESPACE_NODE     *Node;
+    ACPI_STATUS             Status;
+    ACPI_BUFFER             ReturnObj;
+
+
+    /* Translate BufferArg to an Named object */
+
+    Node = AcpiDbConvertToNode (BufferArg);
+    if (!Node || (Node == AcpiGbl_RootNode))
+    {
+        AcpiOsPrintf ("Invalid argument: %s\n", BufferArg);
+        return;
+    }
+
+    /* We must have a buffer object */
+
+    if (Node->Type != ACPI_TYPE_BUFFER)
+    {
+        AcpiOsPrintf ("Not a Buffer object, cannot be a template: %s\n",
+            BufferArg);
+        return;
+    }
+
+    ReturnObj.Length = ACPI_DEBUG_BUFFER_SIZE;
+    ReturnObj.Pointer = AcpiGbl_DbBuffer;
+
+    /* Attempt to convert the raw buffer to a resource list */
+
+    Status = AcpiRsCreateResourceList (Node->Object, &ReturnObj);
+
+    AcpiDbSetOutputDestination (ACPI_DB_REDIRECTABLE_OUTPUT);
+    AcpiDbgLevel |= ACPI_LV_RESOURCES;
+
+    if (ACPI_FAILURE (Status))
+    {
+        AcpiOsPrintf ("Could not convert Buffer to a resource list: %s, %s\n",
+            BufferArg, AcpiFormatException (Status));
+        goto DumpBuffer;
+    }
+
+    /* Now we can dump the resource list */
+
+    AcpiRsDumpResourceList (ACPI_CAST_PTR (ACPI_RESOURCE,
+        ReturnObj.Pointer));
+
+DumpBuffer:
+    AcpiOsPrintf ("\nRaw data buffer:\n");
+    AcpiUtDumpBuffer ((UINT8 *) Node->Object->Buffer.Pointer,
+        Node->Object->Buffer.Length,
+        DB_BYTE_DISPLAY, ACPI_UINT32_MAX);
+
+    AcpiDbSetOutputDestination (ACPI_DB_CONSOLE_OUTPUT);
+    return;
+}
+
+
+/*******************************************************************************
+ *
  * FUNCTION:    AcpiDmCompareAmlResources
  *
  * PARAMETERS:  Aml1Buffer          - Contains first resource list
@@ -479,11 +564,14 @@
 {
     UINT8                   *Aml1;
     UINT8                   *Aml2;
+    UINT8                   *Aml1End;
+    UINT8                   *Aml2End;
     ACPI_RSDESC_SIZE        Aml1Length;
     ACPI_RSDESC_SIZE        Aml2Length;
     ACPI_RSDESC_SIZE        Offset = 0;
     UINT8                   ResourceType;
     UINT32                  Count = 0;
+    UINT32                  i;
 
 
     /* Compare overall buffer sizes (may be different due to size rounding) */
@@ -491,16 +579,18 @@
     if (Aml1BufferLength != Aml2BufferLength)
     {
         AcpiOsPrintf (
-            "**** Buffer length mismatch in converted AML: original %X new %X ****\n",
+            "**** Buffer length mismatch in converted AML: Original %X, New %X ****\n",
             Aml1BufferLength, Aml2BufferLength);
     }
 
     Aml1 = Aml1Buffer;
     Aml2 = Aml2Buffer;
+    Aml1End = Aml1Buffer + Aml1BufferLength;
+    Aml2End = Aml2Buffer + Aml2BufferLength;
 
     /* Walk the descriptor lists, comparing each descriptor */
 
-    while (Aml1 < (Aml1Buffer + Aml1BufferLength))
+    while ((Aml1 < Aml1End) && (Aml2 < Aml2End))
     {
         /* Get the lengths of each descriptor */
 
@@ -513,7 +603,7 @@
         if (Aml1Length != Aml2Length)
         {
             AcpiOsPrintf (
-                "**** Length mismatch in descriptor [%.2X] type %2.2X, Offset %8.8X L1 %X L2 %X ****\n",
+                "**** Length mismatch in descriptor [%.2X] type %2.2X, Offset %8.8X Len1 %X, Len2 %X ****\n",
                 Count, ResourceType, Offset, Aml1Length, Aml2Length);
         }
 
@@ -524,6 +614,15 @@
             AcpiOsPrintf (
                 "**** Data mismatch in descriptor [%.2X] type %2.2X, Offset %8.8X ****\n",
                 Count, ResourceType, Offset);
+
+            for (i = 0; i < Aml1Length; i++)
+            {
+                if (Aml1[i] != Aml2[i])
+                {
+                    AcpiOsPrintf ("Mismatch at byte offset %.2X: is %2.2X, should be %2.2X\n",
+                        i, Aml2[i], Aml1[i]);
+                }
+            }
         }
 
         /* Exit on EndTag descriptor */
@@ -626,9 +725,253 @@
 
 /*******************************************************************************
  *
+ * FUNCTION:    AcpiDbResourceCallback
+ *
+ * PARAMETERS:  ACPI_WALK_RESOURCE_CALLBACK
+ *
+ * RETURN:      Status
+ *
+ * DESCRIPTION: Simple callback to exercise AcpiWalkResources
+ *
+ ******************************************************************************/
+
+static ACPI_STATUS
+AcpiDbResourceCallback (
+    ACPI_RESOURCE           *Resource,
+    void                    *Context)
+{
+
+    return (AE_OK);
+}
+
+
+/*******************************************************************************
+ *
+ * FUNCTION:    AcpiDbDeviceResources
+ *
+ * PARAMETERS:  ACPI_WALK_CALLBACK
+ *
+ * RETURN:      Status
+ *
+ * DESCRIPTION: Display the _PRT/_CRS/_PRS resources for a device object.
+ *
+ ******************************************************************************/
+
+static ACPI_STATUS
+AcpiDbDeviceResources (
+    ACPI_HANDLE             ObjHandle,
+    UINT32                  NestingLevel,
+    void                    *Context,
+    void                    **ReturnValue)
+{
+    ACPI_NAMESPACE_NODE     *Node;
+    ACPI_NAMESPACE_NODE     *PrtNode = NULL;
+    ACPI_NAMESPACE_NODE     *CrsNode = NULL;
+    ACPI_NAMESPACE_NODE     *PrsNode = NULL;
+    ACPI_NAMESPACE_NODE     *AeiNode = NULL;
+    char                    *ParentPath;
+    ACPI_BUFFER             ReturnObj;
+    ACPI_STATUS             Status;
+
+
+    Node = ACPI_CAST_PTR (ACPI_NAMESPACE_NODE, ObjHandle);
+    ParentPath = AcpiNsGetExternalPathname (Node);
+    if (!ParentPath)
+    {
+        return (AE_NO_MEMORY);
+    }
+
+    /* Get handles to the resource methods for this device */
+
+    (void) AcpiGetHandle (Node, METHOD_NAME__PRT, ACPI_CAST_PTR (ACPI_HANDLE, &PrtNode));
+    (void) AcpiGetHandle (Node, METHOD_NAME__CRS, ACPI_CAST_PTR (ACPI_HANDLE, &CrsNode));
+    (void) AcpiGetHandle (Node, METHOD_NAME__PRS, ACPI_CAST_PTR (ACPI_HANDLE, &PrsNode));
+    (void) AcpiGetHandle (Node, METHOD_NAME__AEI, ACPI_CAST_PTR (ACPI_HANDLE, &AeiNode));
+    if (!PrtNode && !CrsNode && !PrsNode && !AeiNode)
+    {
+        goto Cleanup;   /* Nothing to do */
+    }
+
+    AcpiOsPrintf ("\nDevice: %s\n", ParentPath);
+
+    /* Prepare for a return object of arbitrary size */
+
+    ReturnObj.Pointer = AcpiGbl_DbBuffer;
+    ReturnObj.Length  = ACPI_DEBUG_BUFFER_SIZE;
+
+
+    /* _PRT */
+
+    if (PrtNode)
+    {
+        AcpiOsPrintf ("Evaluating _PRT\n");
+
+        Status = AcpiEvaluateObject (PrtNode, NULL, NULL, &ReturnObj);
+        if (ACPI_FAILURE (Status))
+        {
+            AcpiOsPrintf ("Could not evaluate _PRT: %s\n",
+                AcpiFormatException (Status));
+            goto GetCrs;
+        }
+
+        ReturnObj.Pointer = AcpiGbl_DbBuffer;
+        ReturnObj.Length  = ACPI_DEBUG_BUFFER_SIZE;
+
+        Status = AcpiGetIrqRoutingTable (Node, &ReturnObj);
+        if (ACPI_FAILURE (Status))
+        {
+            AcpiOsPrintf ("GetIrqRoutingTable failed: %s\n",
+                AcpiFormatException (Status));
+            goto GetCrs;
+        }
+
+        AcpiRsDumpIrqList (ACPI_CAST_PTR (UINT8, AcpiGbl_DbBuffer));
+    }
+
+
+    /* _CRS */
+
+GetCrs:
+    if (CrsNode)
+    {
+        AcpiOsPrintf ("Evaluating _CRS\n");
+
+        ReturnObj.Pointer = AcpiGbl_DbBuffer;
+        ReturnObj.Length  = ACPI_DEBUG_BUFFER_SIZE;
+
+        Status = AcpiEvaluateObject (CrsNode, NULL, NULL, &ReturnObj);
+        if (ACPI_FAILURE (Status))
+        {
+            AcpiOsPrintf ("Could not evaluate _CRS: %s\n",
+                AcpiFormatException (Status));
+            goto GetPrs;
+        }
+
+        /* This code is here to exercise the AcpiWalkResources interface */
+
+        Status = AcpiWalkResources (Node, METHOD_NAME__CRS,
+            AcpiDbResourceCallback, NULL);
+        if (ACPI_FAILURE (Status))
+        {
+            AcpiOsPrintf ("AcpiWalkResources failed: %s\n",
+                AcpiFormatException (Status));
+            goto GetPrs;
+        }
+
+        /* Get the _CRS resource list */
+
+        ReturnObj.Pointer = AcpiGbl_DbBuffer;
+        ReturnObj.Length  = ACPI_DEBUG_BUFFER_SIZE;
+
+        Status = AcpiGetCurrentResources (Node, &ReturnObj);
+        if (ACPI_FAILURE (Status))
+        {
+            AcpiOsPrintf ("AcpiGetCurrentResources failed: %s\n",
+                AcpiFormatException (Status));
+            goto GetPrs;
+        }
+
+        /* Dump the _CRS resource list */
+
+        AcpiRsDumpResourceList (ACPI_CAST_PTR (ACPI_RESOURCE,
+            ReturnObj.Pointer));
+
+        /*
+         * Perform comparison of original AML to newly created AML. This tests both
+         * the AML->Resource conversion and the Resource->Aml conversion.
+         */
+        Status = AcpiDmTestResourceConversion (Node, METHOD_NAME__CRS);
+
+        /* Execute _SRS with the resource list */
+
+        Status = AcpiSetCurrentResources (Node, &ReturnObj);
+        if (ACPI_FAILURE (Status))
+        {
+            AcpiOsPrintf ("AcpiSetCurrentResources failed: %s\n",
+                AcpiFormatException (Status));
+            goto GetPrs;
+        }
+    }
+
+
+    /* _PRS */
+
+GetPrs:
+    if (PrsNode)
+    {
+        AcpiOsPrintf ("Evaluating _PRS\n");
+
+        ReturnObj.Pointer = AcpiGbl_DbBuffer;
+        ReturnObj.Length  = ACPI_DEBUG_BUFFER_SIZE;
+
+        Status = AcpiEvaluateObject (PrsNode, NULL, NULL, &ReturnObj);
+        if (ACPI_FAILURE (Status))
+        {
+            AcpiOsPrintf ("Could not evaluate _PRS: %s\n",
+                AcpiFormatException (Status));
+            goto GetAei;
+        }
+
+        ReturnObj.Pointer = AcpiGbl_DbBuffer;
+        ReturnObj.Length  = ACPI_DEBUG_BUFFER_SIZE;
+
+        Status = AcpiGetPossibleResources (Node, &ReturnObj);
+        if (ACPI_FAILURE (Status))
+        {
+            AcpiOsPrintf ("AcpiGetPossibleResources failed: %s\n",
+                AcpiFormatException (Status));
+            goto GetAei;
+        }
+
+        AcpiRsDumpResourceList (ACPI_CAST_PTR (ACPI_RESOURCE, AcpiGbl_DbBuffer));
+    }
+
+
+    /* _AEI */
+
+GetAei:
+    if (AeiNode)
+    {
+        AcpiOsPrintf ("Evaluating _AEI\n");
+
+        ReturnObj.Pointer = AcpiGbl_DbBuffer;
+        ReturnObj.Length  = ACPI_DEBUG_BUFFER_SIZE;
+
+        Status = AcpiEvaluateObject (AeiNode, NULL, NULL, &ReturnObj);
+        if (ACPI_FAILURE (Status))
+        {
+            AcpiOsPrintf ("Could not evaluate _AEI: %s\n",
+                AcpiFormatException (Status));
+            goto Cleanup;
+        }
+
+        ReturnObj.Pointer = AcpiGbl_DbBuffer;
+        ReturnObj.Length  = ACPI_DEBUG_BUFFER_SIZE;
+
+        Status = AcpiGetEventResources (Node, &ReturnObj);
+        if (ACPI_FAILURE (Status))
+        {
+            AcpiOsPrintf ("AcpiGetEventResources failed: %s\n",
+                AcpiFormatException (Status));
+            goto Cleanup;
+        }
+
+        AcpiRsDumpResourceList (ACPI_CAST_PTR (ACPI_RESOURCE, AcpiGbl_DbBuffer));
+    }
+
+
+Cleanup:
+    ACPI_FREE (ParentPath);
+    return (AE_OK);
+}
+
+
+/*******************************************************************************
+ *
  * FUNCTION:    AcpiDbDisplayResources
  *
- * PARAMETERS:  ObjectArg       - String with hex value of the object
+ * PARAMETERS:  ObjectArg       - String object name or object pointer.
+ *                                "*" means "display resources for all devices"
  *
  * RETURN:      None
  *
@@ -641,142 +984,38 @@
     char                    *ObjectArg)
 {
     ACPI_NAMESPACE_NODE     *Node;
-    ACPI_STATUS             Status;
-    ACPI_BUFFER             ReturnObj;
 
 
     AcpiDbSetOutputDestination (ACPI_DB_REDIRECTABLE_OUTPUT);
     AcpiDbgLevel |= ACPI_LV_RESOURCES;
 
-    /* Convert string to object pointer */
+    /* Asterisk means "display resources for all devices" */
 
-    Node = AcpiDbConvertToNode (ObjectArg);
-    if (!Node)
+    if (!ACPI_STRCMP (ObjectArg, "*"))
     {
-        return;
+        (void) AcpiWalkNamespace (ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT,
+                    ACPI_UINT32_MAX, AcpiDbDeviceResources, NULL, NULL, NULL);
+    }
+    else
+    {
+        /* Convert string to object pointer */
+
+        Node = AcpiDbConvertToNode (ObjectArg);
+        if (Node)
+        {
+            if (Node->Type != ACPI_TYPE_DEVICE)
+            {
+                AcpiOsPrintf ("%4.4s: Name is not a device object (%s)\n",
+                    Node->Name.Ascii, AcpiUtGetTypeName (Node->Type));
+            }
+            else
+            {
+                (void) AcpiDbDeviceResources (Node, 0, NULL, NULL);
+            }
+        }
     }
 
-    /* Prepare for a return object of arbitrary size */
-
-    ReturnObj.Pointer = AcpiGbl_DbBuffer;
-    ReturnObj.Length  = ACPI_DEBUG_BUFFER_SIZE;
-
-    /* _PRT */
-
-    AcpiOsPrintf ("Evaluating _PRT\n");
-
-    /* Check if _PRT exists */
-
-    Status = AcpiEvaluateObject (Node, METHOD_NAME__PRT, NULL, &ReturnObj);
-    if (ACPI_FAILURE (Status))
-    {
-        AcpiOsPrintf ("Could not obtain _PRT: %s\n",
-            AcpiFormatException (Status));
-        goto GetCrs;
-    }
-
-    ReturnObj.Pointer = AcpiGbl_DbBuffer;
-    ReturnObj.Length  = ACPI_DEBUG_BUFFER_SIZE;
-
-    Status = AcpiGetIrqRoutingTable (Node, &ReturnObj);
-    if (ACPI_FAILURE (Status))
-    {
-        AcpiOsPrintf ("GetIrqRoutingTable failed: %s\n",
-            AcpiFormatException (Status));
-        goto GetCrs;
-    }
-
-    AcpiRsDumpIrqList (ACPI_CAST_PTR (UINT8, AcpiGbl_DbBuffer));
-
-
-    /* _CRS */
-
-GetCrs:
-    AcpiOsPrintf ("Evaluating _CRS\n");
-
-    ReturnObj.Pointer = AcpiGbl_DbBuffer;
-    ReturnObj.Length  = ACPI_DEBUG_BUFFER_SIZE;
-
-    /* Check if _CRS exists */
-
-    Status = AcpiEvaluateObject (Node, METHOD_NAME__CRS, NULL, &ReturnObj);
-    if (ACPI_FAILURE (Status))
-    {
-        AcpiOsPrintf ("Could not obtain _CRS: %s\n",
-            AcpiFormatException (Status));
-        goto GetPrs;
-    }
-
-    /* Get the _CRS resource list */
-
-    ReturnObj.Pointer = AcpiGbl_DbBuffer;
-    ReturnObj.Length  = ACPI_DEBUG_BUFFER_SIZE;
-
-    Status = AcpiGetCurrentResources (Node, &ReturnObj);
-    if (ACPI_FAILURE (Status))
-    {
-        AcpiOsPrintf ("AcpiGetCurrentResources failed: %s\n",
-            AcpiFormatException (Status));
-        goto GetPrs;
-    }
-
-    /* Dump the _CRS resource list */
-
-    AcpiRsDumpResourceList (ACPI_CAST_PTR (ACPI_RESOURCE,
-        ReturnObj.Pointer));
-
-    /*
-     * Perform comparison of original AML to newly created AML. This tests both
-     * the AML->Resource conversion and the Resource->Aml conversion.
-     */
-    Status = AcpiDmTestResourceConversion (Node, METHOD_NAME__CRS);
-
-    /* Execute _SRS with the resource list */
-
-    Status = AcpiSetCurrentResources (Node, &ReturnObj);
-    if (ACPI_FAILURE (Status))
-    {
-        AcpiOsPrintf ("AcpiSetCurrentResources failed: %s\n",
-            AcpiFormatException (Status));
-        goto GetPrs;
-    }
-
-
-    /* _PRS */
-
-GetPrs:
-    AcpiOsPrintf ("Evaluating _PRS\n");
-
-    ReturnObj.Pointer = AcpiGbl_DbBuffer;
-    ReturnObj.Length  = ACPI_DEBUG_BUFFER_SIZE;
-
-    /* Check if _PRS exists */
-
-    Status = AcpiEvaluateObject (Node, METHOD_NAME__PRS, NULL, &ReturnObj);
-    if (ACPI_FAILURE (Status))
-    {
-        AcpiOsPrintf ("Could not obtain _PRS: %s\n",
-            AcpiFormatException (Status));
-        goto Cleanup;
-    }
-
-    ReturnObj.Pointer = AcpiGbl_DbBuffer;
-    ReturnObj.Length  = ACPI_DEBUG_BUFFER_SIZE;
-
-    Status = AcpiGetPossibleResources (Node, &ReturnObj);
-    if (ACPI_FAILURE (Status))
-    {
-        AcpiOsPrintf ("AcpiGetPossibleResources failed: %s\n",
-            AcpiFormatException (Status));
-        goto Cleanup;
-    }
-
-    AcpiRsDumpResourceList (ACPI_CAST_PTR (ACPI_RESOURCE, AcpiGbl_DbBuffer));
-
-Cleanup:
-
     AcpiDbSetOutputDestination (ACPI_DB_CONSOLE_OUTPUT);
-    return;
 }
 
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/debugger/dbdisply.c
--- a/head/sys/contrib/dev/acpica/debugger/dbdisply.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/debugger/dbdisply.c	Tue Dec 06 20:26:16 2011 +0200
@@ -90,6 +90,8 @@
     ACPI_ADR_SPACE_CMOS,
     ACPI_ADR_SPACE_PCI_BAR_TARGET,
     ACPI_ADR_SPACE_IPMI,
+    ACPI_ADR_SPACE_GPIO,
+    ACPI_ADR_SPACE_GSBUS,
     ACPI_ADR_SPACE_DATA_TABLE,
     ACPI_ADR_SPACE_FIXED_HARDWARE
 };
@@ -971,7 +973,7 @@
 
             while (HandlerObj)
             {
-                if (i == HandlerObj->AddressSpace.SpaceId)
+                if (AcpiGbl_SpaceIdList[i] == HandlerObj->AddressSpace.SpaceId)
                 {
                     AcpiOsPrintf (ACPI_HANDLER_PRESENT_STRING,
                         (HandlerObj->AddressSpace.HandlerFlags &
@@ -989,6 +991,24 @@
 
         FoundHandler:;
         }
+
+        /* Find all handlers for user-defined SpaceIDs */
+
+        HandlerObj = ObjDesc->Device.Handler;
+        while (HandlerObj)
+        {
+            if (HandlerObj->AddressSpace.SpaceId >= ACPI_USER_REGION_BEGIN)
+            {
+                AcpiOsPrintf (ACPI_PREDEFINED_PREFIX,
+                    "User-defined ID", HandlerObj->AddressSpace.SpaceId);
+                AcpiOsPrintf (ACPI_HANDLER_PRESENT_STRING,
+                    (HandlerObj->AddressSpace.HandlerFlags &
+                        ACPI_ADDR_HANDLER_DEFAULT_INSTALLED) ? "Default" : "User",
+                    HandlerObj->AddressSpace.Handler);
+            }
+
+            HandlerObj = HandlerObj->AddressSpace.Next;
+        }
     }
 
     /* Fixed event handlers */
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/debugger/dbfileio.c
--- a/head/sys/contrib/dev/acpica/debugger/dbfileio.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/debugger/dbfileio.c	Tue Dec 06 20:26:16 2011 +0200
@@ -271,10 +271,11 @@
 
     fseek (fp, 0, SEEK_SET);
 
-    /* The RSDT and FACS tables do not have standard ACPI headers */
+    /* The RSDT, FACS and S3PT tables do not have standard ACPI headers */
 
     if (ACPI_COMPARE_NAME (TableHeader.Signature, "RSD ") ||
-        ACPI_COMPARE_NAME (TableHeader.Signature, "FACS"))
+        ACPI_COMPARE_NAME (TableHeader.Signature, "FACS") ||
+        ACPI_COMPARE_NAME (TableHeader.Signature, "S3PT"))
     {
         *TableLength = FileSize;
         StandardHeader = FALSE;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/debugger/dbinput.c
--- a/head/sys/contrib/dev/acpica/debugger/dbinput.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/debugger/dbinput.c	Tue Dec 06 20:26:16 2011 +0200
@@ -131,6 +131,7 @@
     CMD_STATS,
     CMD_STOP,
     CMD_TABLES,
+    CMD_TEMPLATE,
     CMD_TERMINATE,
     CMD_THREADS,
     CMD_TRACE,
@@ -199,6 +200,7 @@
     {"STATS",        0},
     {"STOP",         0},
     {"TABLES",       0},
+    {"TEMPLATE",     1},
     {"TERMINATE",    0},
     {"THREADS",      3},
     {"TRACE",        1},
@@ -268,9 +270,10 @@
     AcpiOsPrintf ("  Predefined                          Check all predefined names\n");
     AcpiOsPrintf ("  Prefix [<NamePath>]                 Set or Get current execution prefix\n");
     AcpiOsPrintf ("  References <Addr>                   Find all references to object at addr\n");
-    AcpiOsPrintf ("  Resources <Device>                  Get and display Device resources\n");
+    AcpiOsPrintf ("  Resources <DeviceName | *>          Display Device resources (* = all devices)\n");
     AcpiOsPrintf ("  Set N <NamedObject> <Value>         Set value for named integer\n");
     AcpiOsPrintf ("  Sleep <SleepState>                  Simulate sleep/wake sequence\n");
+    AcpiOsPrintf ("  Template <Object>                   Format/dump a Buffer/ResourceTemplate\n");
     AcpiOsPrintf ("  Terminate                           Delete namespace and all internal objects\n");
     AcpiOsPrintf ("  Type <Object>                       Display object type\n");
 
@@ -854,6 +857,10 @@
         AcpiDbDisplayTableInfo (AcpiGbl_DbArgs[1]);
         break;
 
+    case CMD_TEMPLATE:
+        AcpiDbDisplayTemplate (AcpiGbl_DbArgs[1]);
+        break;
+
     case CMD_TERMINATE:
         AcpiDbSetOutputDestination (ACPI_DB_REDIRECTABLE_OUTPUT);
         AcpiUtSubsystemShutdown ();
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/debugger/dbutils.c
--- a/head/sys/contrib/dev/acpica/debugger/dbutils.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/debugger/dbutils.c	Tue Dec 06 20:26:16 2011 +0200
@@ -208,7 +208,7 @@
                 AcpiOsPrintf ("\n");
             }
             AcpiUtDumpBuffer (ACPI_CAST_PTR (UINT8, ObjDesc->Buffer.Pointer),
-                    ObjDesc->Buffer.Length, DB_DWORD_DISPLAY, _COMPONENT);
+                    ObjDesc->Buffer.Length, DB_BYTE_DISPLAY, _COMPONENT);
         }
         else
         {
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/disassembler/dmbuffer.c
--- a/head/sys/contrib/dev/acpica/disassembler/dmbuffer.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/disassembler/dmbuffer.c	Tue Dec 06 20:26:16 2011 +0200
@@ -108,19 +108,19 @@
             }
 
             AcpiDmIndent (Level);
-            if (ByteCount > 7)
+            if (ByteCount > 8)
             {
-                AcpiOsPrintf ("/* %04X */    ", i);
+                AcpiOsPrintf ("/* %04X */  ", i);
             }
         }
 
-        AcpiOsPrintf ("0x%2.2X", (UINT32) ByteData[i]);
+        AcpiOsPrintf (" 0x%2.2X", (UINT32) ByteData[i]);
 
         /* Add comma if there are more bytes to display */
 
         if (i < (ByteCount -1))
         {
-            AcpiOsPrintf (", ");
+            AcpiOsPrintf (",");
         }
     }
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/disassembler/dmopcode.c
--- a/head/sys/contrib/dev/acpica/disassembler/dmopcode.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/disassembler/dmopcode.c	Tue Dec 06 20:26:16 2011 +0200
@@ -303,6 +303,7 @@
     UINT32                  Length;
     ACPI_PARSE_OBJECT       *Child;
     ACPI_STATUS             Status;
+    UINT8                   *Aml;
 
 
     if (!Op)
@@ -426,16 +427,19 @@
          * types of buffers, we have to closely look at the data in the
          * buffer to determine the type.
          */
-        Status = AcpiDmIsResourceTemplate (Op);
-        if (ACPI_SUCCESS (Status))
+        if (!AcpiGbl_NoResourceDisassembly)
         {
-            Op->Common.DisasmOpcode = ACPI_DASM_RESOURCE;
-            AcpiOsPrintf ("ResourceTemplate");
-            break;
-        }
-        else if (Status == AE_AML_NO_RESOURCE_END_TAG)
-        {
-            AcpiOsPrintf ("/**** Is ResourceTemplate, but EndTag not at buffer end ****/ ");
+            Status = AcpiDmIsResourceTemplate (Op);
+            if (ACPI_SUCCESS (Status))
+            {
+                Op->Common.DisasmOpcode = ACPI_DASM_RESOURCE;
+                AcpiOsPrintf ("ResourceTemplate");
+                break;
+            }
+            else if (Status == AE_AML_NO_RESOURCE_END_TAG)
+            {
+                AcpiOsPrintf ("/**** Is ResourceTemplate, but EndTag not at buffer end ****/ ");
+            }
         }
 
         if (AcpiDmIsUnicodeBuffer (Op))
@@ -495,7 +499,7 @@
 
         if (Info->BitOffset % 8 == 0)
         {
-            AcpiOsPrintf ("        Offset (0x%.2X)", ACPI_DIV_8 (Info->BitOffset));
+            AcpiOsPrintf ("Offset (0x%.2X)", ACPI_DIV_8 (Info->BitOffset));
         }
         else
         {
@@ -507,16 +511,59 @@
 
 
     case AML_INT_ACCESSFIELD_OP:
+    case AML_INT_EXTACCESSFIELD_OP:
 
-        AcpiOsPrintf ("        AccessAs (%s, ",
-            AcpiGbl_AccessTypes [(UINT32) (Op->Common.Value.Integer >> 8) & 0x7]);
+        AcpiOsPrintf ("AccessAs (%s, ",
+            AcpiGbl_AccessTypes [(UINT32) (Op->Common.Value.Integer & 0x7)]);
 
-        AcpiDmDecodeAttribute ((UINT8) Op->Common.Value.Integer);
+        AcpiDmDecodeAttribute ((UINT8) (Op->Common.Value.Integer >> 8));
+
+        if (Op->Common.AmlOpcode == AML_INT_EXTACCESSFIELD_OP)
+        {
+            AcpiOsPrintf (" (0x%2.2X)", (unsigned) ((Op->Common.Value.Integer >> 16) & 0xFF));
+        }
+
         AcpiOsPrintf (")");
         AcpiDmCommaIfFieldMember (Op);
         break;
 
 
+    case AML_INT_CONNECTION_OP:
+
+        /*
+         * Two types of Connection() - one with a buffer object, the
+         * other with a namestring that points to a buffer object.
+         */
+        AcpiOsPrintf ("Connection (");
+        Child = Op->Common.Value.Arg;
+
+        if (Child->Common.AmlOpcode == AML_INT_BYTELIST_OP)
+        {
+            AcpiOsPrintf ("\n");
+
+            Aml = Child->Named.Data;
+            Length = (UINT32) Child->Common.Value.Integer;
+
+            Info->Level += 1;
+            Op->Common.DisasmOpcode = ACPI_DASM_RESOURCE;
+            AcpiDmResourceTemplate (Info, Op->Common.Parent, Aml, Length);
+
+            Info->Level -= 1;
+            AcpiDmIndent (Info->Level);
+        }
+        else
+        {
+            AcpiDmNamestring (Child->Common.Value.Name);
+        }
+
+        AcpiOsPrintf (")");
+        AcpiDmCommaIfFieldMember (Op);
+        AcpiOsPrintf ("\n");
+
+        Op->Common.DisasmFlags |= ACPI_PARSEOP_IGNORE; /* for now, ignore in AcpiDmAscendingOp */
+        Child->Common.DisasmFlags |= ACPI_PARSEOP_IGNORE;
+        break;
+
     case AML_INT_BYTELIST_OP:
 
         AcpiDmByteList (Info, Op);
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/disassembler/dmresrc.c
--- a/head/sys/contrib/dev/acpica/disassembler/dmresrc.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/disassembler/dmresrc.c	Tue Dec 06 20:26:16 2011 +0200
@@ -55,12 +55,6 @@
 
 /* Dispatch tables for Resource disassembly functions */
 
-typedef
-void (*ACPI_RESOURCE_HANDLER) (
-    AML_RESOURCE            *Resource,
-    UINT32                  Length,
-    UINT32                  Level);
-
 static ACPI_RESOURCE_HANDLER    AcpiGbl_DmResourceDispatch [] =
 {
     /* Small descriptors */
@@ -75,7 +69,7 @@
     AcpiDmEndDependentDescriptor,   /* 0x07, ACPI_RESOURCE_NAME_END_DEPENDENT */
     AcpiDmIoDescriptor,             /* 0x08, ACPI_RESOURCE_NAME_IO_PORT */
     AcpiDmFixedIoDescriptor,        /* 0x09, ACPI_RESOURCE_NAME_FIXED_IO_PORT */
-    NULL,                           /* 0x0A, Reserved */
+    AcpiDmFixedDmaDescriptor,       /* 0x0A, ACPI_RESOURCE_NAME_FIXED_DMA */
     NULL,                           /* 0x0B, Reserved */
     NULL,                           /* 0x0C, Reserved */
     NULL,                           /* 0x0D, Reserved */
@@ -95,7 +89,10 @@
     AcpiDmWordDescriptor,           /* 0x08, ACPI_RESOURCE_NAME_WORD_ADDRESS_SPACE */
     AcpiDmInterruptDescriptor,      /* 0x09, ACPI_RESOURCE_NAME_EXTENDED_XRUPT */
     AcpiDmQwordDescriptor,          /* 0x0A, ACPI_RESOURCE_NAME_QWORD_ADDRESS_SPACE */
-    AcpiDmExtendedDescriptor        /* 0x0B, ACPI_RESOURCE_NAME_EXTENDED_ADDRESS_SPACE */
+    AcpiDmExtendedDescriptor,       /* 0x0B, ACPI_RESOURCE_NAME_EXTENDED_ADDRESS_SPACE */
+    AcpiDmGpioDescriptor,           /* 0x0C, ACPI_RESOURCE_NAME_GPIO */
+    NULL,                           /* 0x0D, Reserved */
+    AcpiDmSerialBusDescriptor       /* 0x0E, ACPI_RESOURCE_NAME_SERIAL_BUS */
 };
 
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/disassembler/dmresrcl.c
--- a/head/sys/contrib/dev/acpica/disassembler/dmresrcl.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/disassembler/dmresrcl.c	Tue Dec 06 20:26:16 2011 +0200
@@ -1050,4 +1050,3 @@
 }
 
 #endif
-
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/disassembler/dmresrcl2.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/sys/contrib/dev/acpica/disassembler/dmresrcl2.c	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,700 @@
+/*******************************************************************************
+ *
+ * Module Name: dmresrcl2.c - "Large" Resource Descriptor disassembly (#2)
+ *
+ ******************************************************************************/
+
+/*
+ * Copyright (C) 2000 - 2011, Intel Corp.
+ * 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.
+ * 3. Neither the names of the above-listed copyright holders nor the names
+ *    of any contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ * Alternatively, this software may be distributed under the terms of the
+ * GNU General Public License ("GPL") version 2 as published by the Free
+ * Software Foundation.
+ *
+ * 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.
+ */
+
+
+#include <contrib/dev/acpica/include/acpi.h>
+#include <contrib/dev/acpica/include/accommon.h>
+#include <contrib/dev/acpica/include/acdisasm.h>
+
+
+#ifdef ACPI_DISASSEMBLER
+
+#define _COMPONENT          ACPI_CA_DEBUGGER
+        ACPI_MODULE_NAME    ("dbresrcl2")
+
+/* Local prototypes */
+
+static void
+AcpiDmI2cSerialBusDescriptor (
+    AML_RESOURCE            *Resource,
+    UINT32                  Length,
+    UINT32                  Level);
+
+static void
+AcpiDmSpiSerialBusDescriptor (
+    AML_RESOURCE            *Resource,
+    UINT32                  Length,
+    UINT32                  Level);
+
+static void
+AcpiDmUartSerialBusDescriptor (
+    AML_RESOURCE            *Resource,
+    UINT32                  Length,
+    UINT32                  Level);
+
+static void
+AcpiDmGpioCommon (
+    AML_RESOURCE            *Resource,
+    UINT32                  Level);
+
+static void
+AcpiDmDumpRawDataBuffer (
+    UINT8                   *Buffer,
+    UINT32                  Length,
+    UINT32                  Level);
+
+
+/* Dispatch table for the serial bus descriptors */
+
+static ACPI_RESOURCE_HANDLER        SerialBusResourceDispatch [] =
+{
+    NULL,
+    AcpiDmI2cSerialBusDescriptor,
+    AcpiDmSpiSerialBusDescriptor,
+    AcpiDmUartSerialBusDescriptor
+};
+
+
+/*******************************************************************************
+ *
+ * FUNCTION:    AcpiDmDumpRawDataBuffer
+ *
+ * PARAMETERS:  Buffer              - Pointer to the data bytes
+ *              Length              - Length of the descriptor in bytes
+ *              Level               - Current source code indentation level
+ *
+ * RETURN:      None
+ *
+ * DESCRIPTION: Dump a data buffer as a RawDataBuffer() object. Used for
+ *              vendor data bytes.
+ *
+ ******************************************************************************/
+
+static void
+AcpiDmDumpRawDataBuffer (
+    UINT8                   *Buffer,
+    UINT32                  Length,
+    UINT32                  Level)
+{
+    UINT32                  Index;
+    UINT32                  i;
+    UINT32                  j;
+
+
+    if (!Length)
+    {
+        return;
+    }
+
+    AcpiOsPrintf ("RawDataBuffer (0x%.2X)  // Vendor Data", Length);
+
+    AcpiOsPrintf ("\n");
+    AcpiDmIndent (Level + 1);
+    AcpiOsPrintf ("{\n");
+    AcpiDmIndent (Level + 2);
+
+    for (i = 0; i < Length;)
+    {
+        for (j = 0; j < 8; j++)
+        {
+            Index = i + j;
+            if (Index >= Length)
+            {
+                goto Finish;
+            }
+
+            AcpiOsPrintf ("0x%2.2X", Buffer[Index]);
+            if ((Index + 1) >= Length)
+            {
+                goto Finish;
+            }
+
+            AcpiOsPrintf (", ");
+        }
+        AcpiOsPrintf ("\n");
+        AcpiDmIndent (Level + 2);
+
+        i += 8;
+    }
+
+Finish:
+    AcpiOsPrintf ("\n");
+    AcpiDmIndent (Level + 1);
+    AcpiOsPrintf ("}");
+}
+
+
+/*******************************************************************************
+ *
+ * FUNCTION:    AcpiDmGpioCommon
+ *
+ * PARAMETERS:  Resource            - Pointer to the resource descriptor
+ *              Level               - Current source code indentation level
+ *
+ * RETURN:      None
+ *
+ * DESCRIPTION: Decode common parts of a GPIO Interrupt descriptor
+ *
+ ******************************************************************************/
+
+static void
+AcpiDmGpioCommon (
+    AML_RESOURCE            *Resource,
+    UINT32                  Level)
+{
+    UINT32                  PinCount;
+    UINT16                  *PinList;
+    UINT8                   *VendorData;
+    UINT32                  i;
+
+
+    /* ResourceSource, ResourceSourceIndex, ResourceType */
+
+    AcpiDmIndent (Level + 1);
+    if (Resource->Gpio.ResSourceOffset)
+    {
+        AcpiUtPrintString (
+            ACPI_ADD_PTR (char, Resource, Resource->Gpio.ResSourceOffset),
+            ACPI_UINT8_MAX);
+    }
+
+    AcpiOsPrintf (", ");
+    AcpiOsPrintf ("0x%2.2X, ", Resource->Gpio.ResSourceIndex);
+    AcpiOsPrintf ("%s, ",
+        AcpiGbl_ConsumeDecode [(Resource->Gpio.Flags & 1)]);
+
+    /* Insert a descriptor name */
+
+    AcpiDmDescriptorName ();
+    AcpiOsPrintf (",");
+
+    /* Dump the vendor data */
+
+    if (Resource->Gpio.VendorOffset)
+    {
+        AcpiOsPrintf ("\n");
+        AcpiDmIndent (Level + 1);
+        VendorData = ACPI_ADD_PTR (UINT8, Resource,
+            Resource->Gpio.VendorOffset);
+
+        AcpiDmDumpRawDataBuffer (VendorData,
+            Resource->Gpio.VendorLength, Level);
+    }
+
+    AcpiOsPrintf (")\n");
+
+    /* Dump the interrupt list */
+
+    AcpiDmIndent (Level + 1);
+    AcpiOsPrintf ("{   // Pin list\n");
+
+    PinCount = ((UINT32) (Resource->Gpio.ResSourceOffset -
+        Resource->Gpio.PinTableOffset)) /
+        sizeof (UINT16);
+
+    PinList = (UINT16 *) ACPI_ADD_PTR (char, Resource,
+        Resource->Gpio.PinTableOffset);
+
+    for (i = 0; i < PinCount; i++)
+    {
+        AcpiDmIndent (Level + 2);
+        AcpiOsPrintf ("0x%4.4X%s\n", PinList[i], ((i + 1) < PinCount) ? "," : "");
+    }
+
+    AcpiDmIndent (Level + 1);
+    AcpiOsPrintf ("}\n");
+}
+
+
+/*******************************************************************************
+ *
+ * FUNCTION:    AcpiDmGpioIntDescriptor
+ *
+ * PARAMETERS:  Resource            - Pointer to the resource descriptor
+ *              Length              - Length of the descriptor in bytes
+ *              Level               - Current source code indentation level
+ *
+ * RETURN:      None
+ *
+ * DESCRIPTION: Decode a GPIO Interrupt descriptor
+ *
+ ******************************************************************************/
+
+static void
+AcpiDmGpioIntDescriptor (
+    AML_RESOURCE            *Resource,
+    UINT32                  Length,
+    UINT32                  Level)
+{
+
+    /* Dump the GpioInt-specific portion of the descriptor */
+
+    /* EdgeLevel, ActiveLevel, Shared */
+
+    AcpiDmIndent (Level);
+    AcpiOsPrintf ("GpioInt (%s, %s, %s, ",
+        AcpiGbl_HeDecode [(Resource->Gpio.IntFlags & 1)],
+        AcpiGbl_LlDecode [(Resource->Gpio.IntFlags >> 1) & 1],
+        AcpiGbl_ShrDecode [(Resource->Gpio.IntFlags >> 3) & 1]);
+
+    /* PinConfig, DebounceTimeout */
+
+    if (Resource->Gpio.PinConfig <= 3)
+    {
+        AcpiOsPrintf ("%s, ",
+            AcpiGbl_PpcDecode[Resource->Gpio.PinConfig]);
+    }
+    else
+    {
+        AcpiOsPrintf ("0x%2.2X, ", Resource->Gpio.PinConfig);
+    }
+    AcpiOsPrintf ("0x%4.4X,\n", Resource->Gpio.DebounceTimeout);
+
+    /* Dump the GpioInt/GpioIo common portion of the descriptor */
+
+    AcpiDmGpioCommon (Resource, Level);
+}
+
+
+/*******************************************************************************
+ *
+ * FUNCTION:    AcpiDmGpioIoDescriptor
+ *
+ * PARAMETERS:  Resource            - Pointer to the resource descriptor
+ *              Length              - Length of the descriptor in bytes
+ *              Level               - Current source code indentation level
+ *
+ * RETURN:      None
+ *
+ * DESCRIPTION: Decode a GPIO Interrupt descriptor
+ *
+ ******************************************************************************/
+
+static void
+AcpiDmGpioIoDescriptor (
+    AML_RESOURCE            *Resource,
+    UINT32                  Length,
+    UINT32                  Level)
+{
+
+    /* Dump the GpioIo-specific portion of the descriptor */
+
+    /* Shared, PinConfig */
+
+    AcpiDmIndent (Level);
+    AcpiOsPrintf ("GpioIo (%s, ",
+        AcpiGbl_ShrDecode [(Resource->Gpio.IntFlags >> 3) & 1]);
+
+    if (Resource->Gpio.PinConfig <= 3)
+    {
+        AcpiOsPrintf ("%s, ",
+            AcpiGbl_PpcDecode[Resource->Gpio.PinConfig]);
+    }
+    else
+    {
+        AcpiOsPrintf ("0x%2.2X, ", Resource->Gpio.PinConfig);
+    }
+
+    /* DebounceTimeout, DriveStrength, IoRestriction */
+
+    AcpiOsPrintf ("0x%4.4X, ", Resource->Gpio.DebounceTimeout);
+    AcpiOsPrintf ("0x%4.4X, ", Resource->Gpio.DriveStrength);
+    AcpiOsPrintf ("%s,\n",
+        AcpiGbl_IorDecode [Resource->Gpio.IntFlags & 3]);
+
+    /* Dump the GpioInt/GpioIo common portion of the descriptor */
+
+    AcpiDmGpioCommon (Resource, Level);
+}
+
+
+/*******************************************************************************
+ *
+ * FUNCTION:    AcpiDmGpioDescriptor
+ *
+ * PARAMETERS:  Resource            - Pointer to the resource descriptor
+ *              Length              - Length of the descriptor in bytes
+ *              Level               - Current source code indentation level
+ *
+ * RETURN:      None
+ *
+ * DESCRIPTION: Decode a GpioInt/GpioIo GPIO Interrupt/IO descriptor
+ *
+ ******************************************************************************/
+
+void
+AcpiDmGpioDescriptor (
+    AML_RESOURCE            *Resource,
+    UINT32                  Length,
+    UINT32                  Level)
+{
+    UINT8                   ConnectionType;
+
+
+    ConnectionType = Resource->Gpio.ConnectionType;
+
+    switch (ConnectionType)
+    {
+    case AML_RESOURCE_GPIO_TYPE_INT:
+        AcpiDmGpioIntDescriptor (Resource, Length, Level);
+        break;
+
+    case AML_RESOURCE_GPIO_TYPE_IO:
+        AcpiDmGpioIoDescriptor (Resource, Length, Level);
+        break;
+
+    default:
+        AcpiOsPrintf ("Unknown GPIO type\n");
+        break;
+    }
+}
+
+
+/*******************************************************************************
+ *
+ * FUNCTION:    AcpiDmDumpSerialBusVendorData
+ *
+ * PARAMETERS:  Resource            - Pointer to the resource descriptor
+ *
+ * RETURN:      None
+ *
+ * DESCRIPTION: Dump optional serial bus vendor data
+ *
+ ******************************************************************************/
+
+static void
+AcpiDmDumpSerialBusVendorData (
+    AML_RESOURCE            *Resource,
+    UINT32                  Level)
+{
+    UINT8                   *VendorData;
+    UINT32                  VendorLength;
+
+
+    /* Get the (optional) vendor data and length */
+
+    switch (Resource->CommonSerialBus.Type)
+    {
+    case AML_RESOURCE_I2C_SERIALBUSTYPE:
+
+        VendorLength = Resource->CommonSerialBus.TypeDataLength -
+            AML_RESOURCE_I2C_MIN_DATA_LEN;
+
+        VendorData = ACPI_ADD_PTR (UINT8, Resource,
+            sizeof (AML_RESOURCE_I2C_SERIALBUS));
+        break;
+
+    case AML_RESOURCE_SPI_SERIALBUSTYPE:
+
+        VendorLength = Resource->CommonSerialBus.TypeDataLength -
+            AML_RESOURCE_SPI_MIN_DATA_LEN;
+
+        VendorData = ACPI_ADD_PTR (UINT8, Resource,
+            sizeof (AML_RESOURCE_SPI_SERIALBUS));
+        break;
+
+    case AML_RESOURCE_UART_SERIALBUSTYPE:
+
+        VendorLength = Resource->CommonSerialBus.TypeDataLength -
+            AML_RESOURCE_UART_MIN_DATA_LEN;
+
+        VendorData = ACPI_ADD_PTR (UINT8, Resource,
+            sizeof (AML_RESOURCE_UART_SERIALBUS));
+        break;
+
+    default:
+        return;
+    }
+
+    /* Dump the vendor bytes as a RawDataBuffer object */
+
+    AcpiDmDumpRawDataBuffer (VendorData, VendorLength, Level);
+}
+
+
+/*******************************************************************************
+ *
+ * FUNCTION:    AcpiDmI2cSerialBusDescriptor
+ *
+ * PARAMETERS:  Resource            - Pointer to the resource descriptor
+ *              Length              - Length of the descriptor in bytes
+ *              Level               - Current source code indentation level
+ *
+ * RETURN:      None
+ *
+ * DESCRIPTION: Decode a I2C serial bus descriptor
+ *
+ ******************************************************************************/
+
+static void
+AcpiDmI2cSerialBusDescriptor (
+    AML_RESOURCE            *Resource,
+    UINT32                  Length,
+    UINT32                  Level)
+{
+    UINT32                  ResourceSourceOffset;
+
+
+    /* SlaveAddress, SlaveMode, ConnectionSpeed, AddressingMode */
+
+    AcpiDmIndent (Level);
+    AcpiOsPrintf ("I2cSerialBus (0x%4.4X, %s, 0x%8.8X,\n",
+        Resource->I2cSerialBus.SlaveAddress,
+        AcpiGbl_SmDecode [(Resource->I2cSerialBus.Flags & 1)],
+        Resource->I2cSerialBus.ConnectionSpeed);
+
+    AcpiDmIndent (Level + 1);
+    AcpiOsPrintf ("%s, ",
+        AcpiGbl_AmDecode [(Resource->I2cSerialBus.TypeSpecificFlags & 1)]);
+
+    /* ResourceSource is a required field */
+
+    ResourceSourceOffset = sizeof (AML_RESOURCE_COMMON_SERIALBUS) +
+        Resource->CommonSerialBus.TypeDataLength;
+
+    AcpiUtPrintString (
+        ACPI_ADD_PTR (char, Resource, ResourceSourceOffset),
+        ACPI_UINT8_MAX);
+
+    /* ResourceSourceIndex, ResourceUsage */
+
+    AcpiOsPrintf (",\n");
+    AcpiDmIndent (Level + 1);
+    AcpiOsPrintf ("0x%2.2X, ", Resource->I2cSerialBus.ResSourceIndex);
+
+    AcpiOsPrintf ("%s, ",
+        AcpiGbl_ConsumeDecode [(Resource->I2cSerialBus.Flags & 1)]);
+
+    /* Insert a descriptor name */
+
+    AcpiDmDescriptorName ();
+    AcpiOsPrintf (",\n");
+
+    /* Dump the vendor data */
+
+    AcpiDmIndent (Level + 1);
+    AcpiDmDumpSerialBusVendorData (Resource, Level);
+    AcpiOsPrintf (")\n");
+}
+
+
+/*******************************************************************************
+ *
+ * FUNCTION:    AcpiDmSpiSerialBusDescriptor
+ *
+ * PARAMETERS:  Resource            - Pointer to the resource descriptor
+ *              Length              - Length of the descriptor in bytes
+ *              Level               - Current source code indentation level
+ *
+ * RETURN:      None
+ *
+ * DESCRIPTION: Decode a SPI serial bus descriptor
+ *
+ ******************************************************************************/
+
+static void
+AcpiDmSpiSerialBusDescriptor (
+    AML_RESOURCE            *Resource,
+    UINT32                  Length,
+    UINT32                  Level)
+{
+    UINT32                  ResourceSourceOffset;
+
+
+    /* DeviceSelection, DeviceSelectionPolarity, WireMode, DataBitLength */
+
+    AcpiDmIndent (Level);
+    AcpiOsPrintf ("SpiSerialBus (0x%4.4X, %s, %s, 0x%2.2X,\n",
+        Resource->SpiSerialBus.DeviceSelection,
+        AcpiGbl_DpDecode [(Resource->SpiSerialBus.TypeSpecificFlags >> 1) & 1],
+        AcpiGbl_WmDecode [(Resource->SpiSerialBus.TypeSpecificFlags & 1)],
+        Resource->SpiSerialBus.DataBitLength);
+
+    /* SlaveMode, ConnectionSpeed, ClockPolarity, ClockPhase */
+
+    AcpiDmIndent (Level + 1);
+    AcpiOsPrintf ("%s, 0x%8.8X, %s,\n",
+        AcpiGbl_SmDecode [(Resource->SpiSerialBus.Flags & 1)],
+        Resource->SpiSerialBus.ConnectionSpeed,
+        AcpiGbl_CpoDecode [(Resource->SpiSerialBus.ClockPolarity & 1)]);
+
+    AcpiDmIndent (Level + 1);
+    AcpiOsPrintf ("%s, ",
+        AcpiGbl_CphDecode [(Resource->SpiSerialBus.ClockPhase & 1)]);
+
+    /* ResourceSource is a required field */
+
+    ResourceSourceOffset = sizeof (AML_RESOURCE_COMMON_SERIALBUS) +
+        Resource->CommonSerialBus.TypeDataLength;
+
+    AcpiUtPrintString (
+        ACPI_ADD_PTR (char, Resource, ResourceSourceOffset),
+        ACPI_UINT8_MAX);
+
+    /* ResourceSourceIndex, ResourceUsage */
+
+    AcpiOsPrintf (",\n");
+    AcpiDmIndent (Level + 1);
+    AcpiOsPrintf ("0x%2.2X, ", Resource->SpiSerialBus.ResSourceIndex);
+
+    AcpiOsPrintf ("%s, ",
+        AcpiGbl_ConsumeDecode [(Resource->SpiSerialBus.Flags & 1)]);
+
+    /* Insert a descriptor name */
+
+    AcpiDmDescriptorName ();
+    AcpiOsPrintf (",\n");
+
+    /* Dump the vendor data */
+
+    AcpiDmIndent (Level + 1);
+    AcpiDmDumpSerialBusVendorData (Resource, Level);
+    AcpiOsPrintf (")\n");
+}
+
+
+/*******************************************************************************
+ *
+ * FUNCTION:    AcpiDmUartSerialBusDescriptor
+ *
+ * PARAMETERS:  Resource            - Pointer to the resource descriptor
+ *              Length              - Length of the descriptor in bytes
+ *              Level               - Current source code indentation level
+ *
+ * RETURN:      None
+ *
+ * DESCRIPTION: Decode a UART serial bus descriptor
+ *
+ ******************************************************************************/
+
+static void
+AcpiDmUartSerialBusDescriptor (
+    AML_RESOURCE            *Resource,
+    UINT32                  Length,
+    UINT32                  Level)
+{
+    UINT32                  ResourceSourceOffset;
+
+
+    /* ConnectionSpeed, BitsPerByte, StopBits */
+
+    AcpiDmIndent (Level);
+    AcpiOsPrintf ("UartSerialBus (0x%8.8X, %s, %s,\n",
+        Resource->UartSerialBus.DefaultBaudRate,
+        AcpiGbl_BpbDecode [(Resource->UartSerialBus.TypeSpecificFlags >> 4) & 3],
+        AcpiGbl_SbDecode [(Resource->UartSerialBus.TypeSpecificFlags >> 2) & 3]);
+
+    /* LinesInUse, IsBigEndian, Parity, FlowControl */
+
+    AcpiDmIndent (Level + 1);
+    AcpiOsPrintf ("0x%2.2X, %s, %s, %s,\n",
+        Resource->UartSerialBus.LinesEnabled,
+        AcpiGbl_EdDecode [(Resource->UartSerialBus.TypeSpecificFlags >> 7) & 1],
+        AcpiGbl_PtDecode [Resource->UartSerialBus.Parity & 7],
+        AcpiGbl_FcDecode [Resource->UartSerialBus.TypeSpecificFlags & 3]);
+
+    /* ReceiveBufferSize, TransmitBufferSize */
+
+    AcpiDmIndent (Level + 1);
+    AcpiOsPrintf ("0x%4.4X, 0x%4.4X, ",
+        Resource->UartSerialBus.RxFifoSize,
+        Resource->UartSerialBus.TxFifoSize);
+
+    /* ResourceSource is a required field */
+
+    ResourceSourceOffset = sizeof (AML_RESOURCE_COMMON_SERIALBUS) +
+        Resource->CommonSerialBus.TypeDataLength;
+
+    AcpiUtPrintString (
+        ACPI_ADD_PTR (char, Resource, ResourceSourceOffset),
+        ACPI_UINT8_MAX);
+
+    /* ResourceSourceIndex, ResourceUsage */
+
+    AcpiOsPrintf (",\n");
+    AcpiDmIndent (Level + 1);
+    AcpiOsPrintf ("0x%2.2X, ", Resource->UartSerialBus.ResSourceIndex);
+
+    AcpiOsPrintf ("%s, ",
+        AcpiGbl_ConsumeDecode [(Resource->UartSerialBus.Flags & 1)]);
+
+    /* Insert a descriptor name */
+
+    AcpiDmDescriptorName ();
+    AcpiOsPrintf (",\n");
+
+    /* Dump the vendor data */
+
+    AcpiDmIndent (Level + 1);
+    AcpiDmDumpSerialBusVendorData (Resource, Level);
+    AcpiOsPrintf (")\n");
+}
+
+
+/*******************************************************************************
+ *
+ * FUNCTION:    AcpiDmSerialBusDescriptor
+ *
+ * PARAMETERS:  Resource            - Pointer to the resource descriptor
+ *              Length              - Length of the descriptor in bytes
+ *              Level               - Current source code indentation level
+ *
+ * RETURN:      None
+ *
+ * DESCRIPTION: Decode a I2C/SPI/UART serial bus descriptor
+ *
+ ******************************************************************************/
+
+void
+AcpiDmSerialBusDescriptor (
+    AML_RESOURCE            *Resource,
+    UINT32                  Length,
+    UINT32                  Level)
+{
+
+    SerialBusResourceDispatch [Resource->CommonSerialBus.Type] (
+        Resource, Length, Level);
+}
+
+#endif
+
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/disassembler/dmresrcs.c
--- a/head/sys/contrib/dev/acpica/disassembler/dmresrcs.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/disassembler/dmresrcs.c	Tue Dec 06 20:26:16 2011 +0200
@@ -121,9 +121,9 @@
 
     AcpiDmIndent (Level);
     AcpiOsPrintf ("DMA (%s, %s, %s, ",
-            AcpiGbl_TypDecode [(Resource->Dma.Flags >> 5) & 3],
-            AcpiGbl_BmDecode  [(Resource->Dma.Flags >> 2) & 1],
-            AcpiGbl_SizDecode [(Resource->Dma.Flags >> 0) & 3]);
+        AcpiGbl_TypDecode [(Resource->Dma.Flags >> 5) & 3],
+        AcpiGbl_BmDecode  [(Resource->Dma.Flags >> 2) & 1],
+        AcpiGbl_SizDecode [(Resource->Dma.Flags >> 0) & 3]);
 
     /* Insert a descriptor name */
 
@@ -137,6 +137,49 @@
 
 /*******************************************************************************
  *
+ * FUNCTION:    AcpiDmFixedDmaDescriptor
+ *
+ * PARAMETERS:  Resource            - Pointer to the resource descriptor
+ *              Length              - Length of the descriptor in bytes
+ *              Level               - Current source code indentation level
+ *
+ * RETURN:      None
+ *
+ * DESCRIPTION: Decode a FixedDMA descriptor
+ *
+ ******************************************************************************/
+
+void
+AcpiDmFixedDmaDescriptor (
+    AML_RESOURCE            *Resource,
+    UINT32                  Length,
+    UINT32                  Level)
+{
+
+    AcpiDmIndent (Level);
+    AcpiOsPrintf ("FixedDMA (0x%4.4X, 0x%4.4X, ",
+        Resource->FixedDma.RequestLines,
+        Resource->FixedDma.Channels);
+
+    if (Resource->FixedDma.Width <= 5)
+    {
+        AcpiOsPrintf ("%s, ",
+            AcpiGbl_DtsDecode [Resource->FixedDma.Width]);
+    }
+    else
+    {
+        AcpiOsPrintf ("%X /* INVALID DMA WIDTH */, ", Resource->FixedDma.Width);
+    }
+
+    /* Insert a descriptor name */
+
+    AcpiDmDescriptorName ();
+    AcpiOsPrintf (")\n");
+}
+
+
+/*******************************************************************************
+ *
  * FUNCTION:    AcpiDmIoDescriptor
  *
  * PARAMETERS:  Resource            - Pointer to the resource descriptor
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/disassembler/dmutils.c
--- a/head/sys/contrib/dev/acpica/disassembler/dmutils.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/disassembler/dmutils.c	Tue Dec 06 20:26:16 2011 +0200
@@ -135,7 +135,8 @@
  *
  * RETURN:      None
  *
- * DESCRIPTION: Decode the AccessAs attribute byte.  (Mostly SMBus stuff)
+ * DESCRIPTION: Decode the AccessAs attribute byte. (Mostly SMBus and
+ *              GenericSerialBus stuff.)
  *
  ******************************************************************************/
 
@@ -146,44 +147,61 @@
 
     switch (Attribute)
     {
-    case AML_FIELD_ATTRIB_SMB_QUICK:
+    case AML_FIELD_ATTRIB_QUICK:
 
-        AcpiOsPrintf ("SMBQuick");
+        AcpiOsPrintf ("AttribQuick");
         break;
 
-    case AML_FIELD_ATTRIB_SMB_SEND_RCV:
+    case AML_FIELD_ATTRIB_SEND_RCV:
 
-        AcpiOsPrintf ("SMBSendReceive");
+        AcpiOsPrintf ("AttribSendReceive");
         break;
 
-    case AML_FIELD_ATTRIB_SMB_BYTE:
+    case AML_FIELD_ATTRIB_BYTE:
 
-        AcpiOsPrintf ("SMBByte");
+        AcpiOsPrintf ("AttribByte");
         break;
 
-    case AML_FIELD_ATTRIB_SMB_WORD:
+    case AML_FIELD_ATTRIB_WORD:
 
-        AcpiOsPrintf ("SMBWord");
+        AcpiOsPrintf ("AttribWord");
         break;
 
-    case AML_FIELD_ATTRIB_SMB_WORD_CALL:
+    case AML_FIELD_ATTRIB_BLOCK:
 
-        AcpiOsPrintf ("SMBProcessCall");
+        AcpiOsPrintf ("AttribBlock");
         break;
 
-    case AML_FIELD_ATTRIB_SMB_BLOCK:
+    case AML_FIELD_ATTRIB_MULTIBYTE:
 
-        AcpiOsPrintf ("SMBBlock");
+        AcpiOsPrintf ("AttribBytes");
         break;
 
-    case AML_FIELD_ATTRIB_SMB_BLOCK_CALL:
+    case AML_FIELD_ATTRIB_WORD_CALL:
 
-        AcpiOsPrintf ("SMBBlockProcessCall");
+        AcpiOsPrintf ("AttribProcessCall");
+        break;
+
+    case AML_FIELD_ATTRIB_BLOCK_CALL:
+
+        AcpiOsPrintf ("AttribBlockProcessCall");
+        break;
+
+    case AML_FIELD_ATTRIB_RAW_BYTES:
+
+        AcpiOsPrintf ("AttribRawBytes");
+        break;
+
+    case AML_FIELD_ATTRIB_RAW_PROCESS:
+
+        AcpiOsPrintf ("AttribRawProcessBytes");
         break;
 
     default:
 
-        AcpiOsPrintf ("0x%.2X", Attribute);
+        /* A ByteConst is allowed by the grammar */
+
+        AcpiOsPrintf ("0x%2.2X", Attribute);
         break;
     }
 }
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/disassembler/dmwalk.c
--- a/head/sys/contrib/dev/acpica/disassembler/dmwalk.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/disassembler/dmwalk.c	Tue Dec 06 20:26:16 2011 +0200
@@ -464,7 +464,8 @@
 
     AcpiDmDisassembleOneOp (NULL, Info, Op);
 
-    if (Op->Common.DisasmOpcode == ACPI_DASM_LNOT_PREFIX)
+    if ((Op->Common.DisasmOpcode == ACPI_DASM_LNOT_PREFIX) ||
+        (Op->Common.AmlOpcode == AML_INT_CONNECTION_OP))
     {
         return (AE_OK);
     }
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/dispatcher/dsargs.c
--- a/head/sys/contrib/dev/acpica/dispatcher/dsargs.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/dispatcher/dsargs.c	Tue Dec 06 20:26:16 2011 +0200
@@ -424,7 +424,7 @@
 
     /* Execute the argument AML */
 
-    Status = AcpiDsExecuteArguments (Node, Node->Parent,
+    Status = AcpiDsExecuteArguments (Node, ExtraDesc->Extra.ScopeNode,
                 ExtraDesc->Extra.AmlLength, ExtraDesc->Extra.AmlStart);
     return_ACPI_STATUS (Status);
 }
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/dispatcher/dsfield.c
--- a/head/sys/contrib/dev/acpica/dispatcher/dsfield.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/dispatcher/dsfield.c	Tue Dec 06 20:26:16 2011 +0200
@@ -243,6 +243,7 @@
 {
     ACPI_STATUS             Status;
     UINT64                  Position;
+    ACPI_PARSE_OBJECT       *Child;
 
 
     ACPI_FUNCTION_TRACE_PTR (DsGetFieldNames, Info);
@@ -257,10 +258,11 @@
     while (Arg)
     {
         /*
-         * Three types of field elements are handled:
-         * 1) Offset - specifies a bit offset
-         * 2) AccessAs - changes the access mode
-         * 3) Name - Enters a new named field into the namespace
+         * Four types of field elements are handled:
+         * 1) Name - Enters a new named field into the namespace
+         * 2) Offset - specifies a bit offset
+         * 3) AccessAs - changes the access mode/attributes
+         * 4) Connection - Associate a resource template with the field
          */
         switch (Arg->Common.AmlOpcode)
         {
@@ -279,25 +281,68 @@
             Info->FieldBitPosition = (UINT32) Position;
             break;
 
+        case AML_INT_ACCESSFIELD_OP:
+        case AML_INT_EXTACCESSFIELD_OP:
+            /*
+             * Get new AccessType, AccessAttribute, and AccessLength fields
+             * -- to be used for all field units that follow, until the
+             * end-of-field or another AccessAs keyword is encountered.
+             * NOTE. These three bytes are encoded in the integer value
+             * of the parseop for convenience.
+             *
+             * In FieldFlags, preserve the flag bits other than the
+             * ACCESS_TYPE bits.
+             */
 
-        case AML_INT_ACCESSFIELD_OP:
+            /* AccessType (ByteAcc, WordAcc, etc.) */
+
+            Info->FieldFlags = (UINT8)
+                ((Info->FieldFlags & ~(AML_FIELD_ACCESS_TYPE_MASK)) |
+                ((UINT8) ((UINT32) (Arg->Common.Value.Integer & 0x07))));
+
+            /* AccessAttribute (AttribQuick, AttribByte, etc.) */
+
+            Info->Attribute = (UINT8) ((Arg->Common.Value.Integer >> 8) & 0xFF);
+
+            /* AccessLength (for serial/buffer protocols) */
+
+            Info->AccessLength = (UINT8) ((Arg->Common.Value.Integer >> 16) & 0xFF);
+            break;
+
+        case AML_INT_CONNECTION_OP:
+            /*
+             * Clear any previous connection. New connection is used for all
+             * fields that follow, similar to AccessAs
+             */
+            Info->ResourceBuffer = NULL;
+            Info->ConnectionNode = NULL;
 
             /*
-             * Get a new AccessType and AccessAttribute -- to be used for all
-             * field units that follow, until field end or another AccessAs
-             * keyword.
-             *
-             * In FieldFlags, preserve the flag bits other than the
-             * ACCESS_TYPE bits
+             * A Connection() is either an actual resource descriptor (buffer)
+             * or a named reference to a resource template
              */
-            Info->FieldFlags = (UINT8)
-                ((Info->FieldFlags & ~(AML_FIELD_ACCESS_TYPE_MASK)) |
-                ((UINT8) ((UINT32) Arg->Common.Value.Integer >> 8)));
+            Child = Arg->Common.Value.Arg;
+            if (Child->Common.AmlOpcode == AML_INT_BYTELIST_OP)
+            {
+                Info->ResourceBuffer = Child->Named.Data;
+                Info->ResourceLength = (UINT16) Child->Named.Value.Integer;
+            }
+            else
+            {
+                /* Lookup the Connection() namepath, it should already exist */
 
-            Info->Attribute = (UINT8) (Arg->Common.Value.Integer);
+                Status = AcpiNsLookup (WalkState->ScopeInfo,
+                            Child->Common.Value.Name, ACPI_TYPE_ANY,
+                            ACPI_IMODE_EXECUTE, ACPI_NS_DONT_OPEN_SCOPE,
+                            WalkState, &Info->ConnectionNode);
+                if (ACPI_FAILURE (Status))
+                {
+                    ACPI_ERROR_NAMESPACE (Child->Common.Value.Name, Status);
+                    return_ACPI_STATUS (Status);
+                }
+            }
             break;
 
-
         case AML_INT_NAMEDFIELD_OP:
 
             /* Lookup the name, it should already exist */
@@ -348,7 +393,6 @@
             Info->FieldBitPosition += Info->FieldBitLength;
             break;
 
-
         default:
 
             ACPI_ERROR ((AE_INFO,
@@ -406,6 +450,8 @@
         }
     }
 
+    ACPI_MEMSET (&Info, 0, sizeof (ACPI_CREATE_FIELD_INFO));
+
     /* Second arg is the field flags */
 
     Arg = Arg->Common.Next;
@@ -418,7 +464,6 @@
     Info.RegionNode = RegionNode;
 
     Status = AcpiDsGetFieldNames (&Info, WalkState, Arg->Common.Next);
-
     return_ACPI_STATUS (Status);
 }
 
@@ -514,8 +559,8 @@
     while (Arg)
     {
         /*
-         * Ignore OFFSET and ACCESSAS terms here; we are only interested in the
-         * field names in order to enter them into the namespace.
+         * Ignore OFFSET/ACCESSAS/CONNECTION terms here; we are only interested
+         * in the field names in order to enter them into the namespace.
          */
         if (Arg->Common.AmlOpcode == AML_INT_NAMEDFIELD_OP)
         {
@@ -697,7 +742,6 @@
     Info.RegionNode = RegionNode;
 
     Status = AcpiDsGetFieldNames (&Info, WalkState, Arg->Common.Next);
-
     return_ACPI_STATUS (Status);
 }
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/events/evevent.c
--- a/head/sys/contrib/dev/acpica/events/evevent.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/events/evevent.c	Tue Dec 06 20:26:16 2011 +0200
@@ -81,6 +81,13 @@
     ACPI_FUNCTION_TRACE (EvInitializeEvents);
 
 
+    /* If Hardware Reduced flag is set, there are no fixed events */
+
+    if (AcpiGbl_ReducedHardware)
+    {
+        return_ACPI_STATUS (AE_OK);
+    }
+
     /*
      * Initialize the Fixed and General Purpose Events. This is done prior to
      * enabling SCIs to prevent interrupts from occurring before the handlers
@@ -128,6 +135,13 @@
     ACPI_FUNCTION_TRACE (EvInstallXruptHandlers);
 
 
+    /* If Hardware Reduced flag is set, there is no ACPI h/w */
+
+    if (AcpiGbl_ReducedHardware)
+    {
+        return_ACPI_STATUS (AE_OK);
+    }
+
     /* Install the SCI handler */
 
     Status = AcpiEvInstallSciHandler ();
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/events/evglock.c
--- a/head/sys/contrib/dev/acpica/events/evglock.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/events/evglock.c	Tue Dec 06 20:26:16 2011 +0200
@@ -79,6 +79,13 @@
     ACPI_FUNCTION_TRACE (EvInitGlobalLockHandler);
 
 
+    /* If Hardware Reduced flag is set, there is no global lock */
+
+    if (AcpiGbl_ReducedHardware)
+    {
+        return_ACPI_STATUS (AE_OK);
+    }
+
     /* Attempt installation of the global lock handler */
 
     Status = AcpiInstallFixedEventHandler (ACPI_EVENT_GLOBAL,
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/events/evregion.c
--- a/head/sys/contrib/dev/acpica/events/evregion.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/events/evregion.c	Tue Dec 06 20:26:16 2011 +0200
@@ -372,6 +372,7 @@
  * FUNCTION:    AcpiEvAddressSpaceDispatch
  *
  * PARAMETERS:  RegionObj           - Internal region object
+ *              FieldObj            - Corresponding field. Can be NULL.
  *              Function            - Read or Write operation
  *              RegionOffset        - Where in the region to read or write
  *              BitWidth            - Field width in bits (8, 16, 32, or 64)
@@ -388,6 +389,7 @@
 ACPI_STATUS
 AcpiEvAddressSpaceDispatch (
     ACPI_OPERAND_OBJECT     *RegionObj,
+    ACPI_OPERAND_OBJECT     *FieldObj,
     UINT32                  Function,
     UINT32                  RegionOffset,
     UINT32                  BitWidth,
@@ -399,6 +401,7 @@
     ACPI_OPERAND_OBJECT     *HandlerDesc;
     ACPI_OPERAND_OBJECT     *RegionObj2;
     void                    *RegionContext = NULL;
+    ACPI_CONNECTION_INFO    *Context;
 
 
     ACPI_FUNCTION_TRACE (EvAddressSpaceDispatch);
@@ -423,6 +426,8 @@
         return_ACPI_STATUS (AE_NOT_EXIST);
     }
 
+    Context = HandlerDesc->AddressSpace.Context;
+
     /*
      * It may be the case that the region has never been initialized.
      * Some types of regions require special init code
@@ -450,7 +455,7 @@
         AcpiExExitInterpreter ();
 
         Status = RegionSetup (RegionObj, ACPI_REGION_ACTIVATE,
-                    HandlerDesc->AddressSpace.Context, &RegionContext);
+                    Context, &RegionContext);
 
         /* Re-enter the interpreter */
 
@@ -499,6 +504,27 @@
         ACPI_FORMAT_NATIVE_UINT (RegionObj->Region.Address + RegionOffset),
         AcpiUtGetRegionName (RegionObj->Region.SpaceId)));
 
+
+    /*
+     * Special handling for GenericSerialBus and GeneralPurposeIo:
+     * There are three extra parameters that must be passed to the
+     * handler via the context:
+     *   1) Connection buffer, a resource template from Connection() op.
+     *   2) Length of the above buffer.
+     *   3) Actual access length from the AccessAs() op.
+     */
+    if (((RegionObj->Region.SpaceId == ACPI_ADR_SPACE_GSBUS) ||
+            (RegionObj->Region.SpaceId == ACPI_ADR_SPACE_GPIO)) &&
+        Context &&
+        FieldObj)
+    {
+        /* Get the Connection (ResourceTemplate) buffer */
+
+        Context->Connection = FieldObj->Field.ResourceBuffer;
+        Context->Length = FieldObj->Field.ResourceLength;
+        Context->AccessLength = FieldObj->Field.AccessLength;
+    }
+
     if (!(HandlerDesc->AddressSpace.HandlerFlags &
             ACPI_ADDR_HANDLER_DEFAULT_INSTALLED))
     {
@@ -514,7 +540,7 @@
 
     Status = Handler (Function,
         (RegionObj->Region.Address + RegionOffset), BitWidth, Value,
-        HandlerDesc->AddressSpace.Context, RegionObj2->Extra.RegionContext);
+        Context, RegionObj2->Extra.RegionContext);
 
     if (ACPI_FAILURE (Status))
     {
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/executer/exconfig.c
--- a/head/sys/contrib/dev/acpica/executer/exconfig.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/executer/exconfig.c	Tue Dec 06 20:26:16 2011 +0200
@@ -334,7 +334,7 @@
 
     for (i = 0; i < Length; i++)
     {
-        Status = AcpiEvAddressSpaceDispatch (ObjDesc, ACPI_READ,
+        Status = AcpiEvAddressSpaceDispatch (ObjDesc, NULL, ACPI_READ,
                     RegionOffset, 8, &Value);
         if (ACPI_FAILURE (Status))
         {
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/executer/excreate.c
--- a/head/sys/contrib/dev/acpica/executer/excreate.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/executer/excreate.c	Tue Dec 06 20:26:16 2011 +0200
@@ -284,7 +284,7 @@
  *
  * PARAMETERS:  AmlStart            - Pointer to the region declaration AML
  *              AmlLength           - Max length of the declaration AML
- *              RegionSpace         - SpaceID for the region
+ *              SpaceId             - Address space ID for the region
  *              WalkState           - Current state
  *
  * RETURN:      Status
@@ -297,7 +297,7 @@
 AcpiExCreateRegion (
     UINT8                   *AmlStart,
     UINT32                  AmlLength,
-    UINT8                   RegionSpace,
+    UINT8                   SpaceId,
     ACPI_WALK_STATE         *WalkState)
 {
     ACPI_STATUS             Status;
@@ -326,16 +326,18 @@
      * Space ID must be one of the predefined IDs, or in the user-defined
      * range
      */
-    if ((RegionSpace >= ACPI_NUM_PREDEFINED_REGIONS) &&
-        (RegionSpace < ACPI_USER_REGION_BEGIN) &&
-        (RegionSpace != ACPI_ADR_SPACE_DATA_TABLE))
+    if (!AcpiIsValidSpaceId (SpaceId))
     {
-        ACPI_ERROR ((AE_INFO, "Invalid AddressSpace type 0x%X", RegionSpace));
-        return_ACPI_STATUS (AE_AML_INVALID_SPACE_ID);
+        /*
+         * Print an error message, but continue. We don't want to abort
+         * a table load for this exception. Instead, if the region is
+         * actually used at runtime, abort the executing method.
+         */
+        ACPI_ERROR ((AE_INFO, "Invalid/unknown Address Space ID: 0x%2.2X", SpaceId));
     }
 
     ACPI_DEBUG_PRINT ((ACPI_DB_LOAD, "Region Type - %s (0x%X)\n",
-        AcpiUtGetRegionName (RegionSpace), RegionSpace));
+        AcpiUtGetRegionName (SpaceId), SpaceId));
 
     /* Create the region descriptor */
 
@@ -353,10 +355,18 @@
     RegionObj2 = ObjDesc->Common.NextObject;
     RegionObj2->Extra.AmlStart = AmlStart;
     RegionObj2->Extra.AmlLength = AmlLength;
+    if (WalkState->ScopeInfo)
+    {
+        RegionObj2->Extra.ScopeNode = WalkState->ScopeInfo->Scope.Node;
+    }
+    else
+    {
+        RegionObj2->Extra.ScopeNode = Node;
+    }
 
     /* Init the region from the operands */
 
-    ObjDesc->Region.SpaceId = RegionSpace;
+    ObjDesc->Region.SpaceId = SpaceId;
     ObjDesc->Region.Address = 0;
     ObjDesc->Region.Length = 0;
     ObjDesc->Region.Node = Node;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/executer/exdump.c
--- a/head/sys/contrib/dev/acpica/executer/exdump.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/executer/exdump.c	Tue Dec 06 20:26:16 2011 +0200
@@ -209,11 +209,13 @@
     {ACPI_EXD_POINTER,  ACPI_EXD_OFFSET (BufferField.BufferObj),        "Buffer Object"}
 };
 
-static ACPI_EXDUMP_INFO     AcpiExDumpRegionField[3] =
+static ACPI_EXDUMP_INFO     AcpiExDumpRegionField[5] =
 {
     {ACPI_EXD_INIT,     ACPI_EXD_TABLE_SIZE (AcpiExDumpRegionField),    NULL},
     {ACPI_EXD_FIELD,    0,                                              NULL},
-    {ACPI_EXD_POINTER,  ACPI_EXD_OFFSET (Field.RegionObj),              "Region Object"}
+    {ACPI_EXD_UINT8,    ACPI_EXD_OFFSET (Field.AccessLength),           "AccessLength"},
+    {ACPI_EXD_POINTER,  ACPI_EXD_OFFSET (Field.RegionObj),              "Region Object"},
+    {ACPI_EXD_POINTER,  ACPI_EXD_OFFSET (Field.ResourceBuffer),         "ResourceBuffer"}
 };
 
 static ACPI_EXDUMP_INFO     AcpiExDumpBankField[5] =
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/executer/exfield.c
--- a/head/sys/contrib/dev/acpica/executer/exfield.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/executer/exfield.c	Tue Dec 06 20:26:16 2011 +0200
@@ -113,19 +113,25 @@
     }
     else if ((ObjDesc->Common.Type == ACPI_TYPE_LOCAL_REGION_FIELD) &&
              (ObjDesc->Field.RegionObj->Region.SpaceId == ACPI_ADR_SPACE_SMBUS ||
+              ObjDesc->Field.RegionObj->Region.SpaceId == ACPI_ADR_SPACE_GSBUS ||
               ObjDesc->Field.RegionObj->Region.SpaceId == ACPI_ADR_SPACE_IPMI))
     {
         /*
-         * This is an SMBus or IPMI read. We must create a buffer to hold
+         * This is an SMBus, GSBus or IPMI read. We must create a buffer to hold
          * the data and then directly access the region handler.
          *
-         * Note: Smbus protocol value is passed in upper 16-bits of Function
+         * Note: SMBus and GSBus protocol value is passed in upper 16-bits of Function
          */
         if (ObjDesc->Field.RegionObj->Region.SpaceId == ACPI_ADR_SPACE_SMBUS)
         {
             Length = ACPI_SMBUS_BUFFER_SIZE;
             Function = ACPI_READ | (ObjDesc->Field.Attribute << 16);
         }
+        else if (ObjDesc->Field.RegionObj->Region.SpaceId == ACPI_ADR_SPACE_GSBUS)
+        {
+            Length = ACPI_GSBUS_BUFFER_SIZE;
+            Function = ACPI_READ | (ObjDesc->Field.Attribute << 16);
+        }
         else /* IPMI */
         {
             Length = ACPI_IPMI_BUFFER_SIZE;
@@ -274,23 +280,24 @@
     }
     else if ((ObjDesc->Common.Type == ACPI_TYPE_LOCAL_REGION_FIELD) &&
              (ObjDesc->Field.RegionObj->Region.SpaceId == ACPI_ADR_SPACE_SMBUS ||
+              ObjDesc->Field.RegionObj->Region.SpaceId == ACPI_ADR_SPACE_GSBUS ||
               ObjDesc->Field.RegionObj->Region.SpaceId == ACPI_ADR_SPACE_IPMI))
     {
         /*
-         * This is an SMBus or IPMI write. We will bypass the entire field
+         * This is an SMBus, GSBus or IPMI write. We will bypass the entire field
          * mechanism and handoff the buffer directly to the handler. For
          * these address spaces, the buffer is bi-directional; on a write,
          * return data is returned in the same buffer.
          *
          * Source must be a buffer of sufficient size:
-         * ACPI_SMBUS_BUFFER_SIZE or ACPI_IPMI_BUFFER_SIZE.
+         * ACPI_SMBUS_BUFFER_SIZE, ACPI_GSBUS_BUFFER_SIZE, or ACPI_IPMI_BUFFER_SIZE.
          *
-         * Note: SMBus protocol type is passed in upper 16-bits of Function
+         * Note: SMBus and GSBus protocol type is passed in upper 16-bits of Function
          */
         if (SourceDesc->Common.Type != ACPI_TYPE_BUFFER)
         {
             ACPI_ERROR ((AE_INFO,
-                "SMBus or IPMI write requires Buffer, found type %s",
+                "SMBus/IPMI/GenericSerialBus write requires Buffer, found type %s",
                 AcpiUtGetObjectTypeName (SourceDesc)));
 
             return_ACPI_STATUS (AE_AML_OPERAND_TYPE);
@@ -301,6 +308,11 @@
             Length = ACPI_SMBUS_BUFFER_SIZE;
             Function = ACPI_WRITE | (ObjDesc->Field.Attribute << 16);
         }
+        else if (ObjDesc->Field.RegionObj->Region.SpaceId == ACPI_ADR_SPACE_GSBUS)
+        {
+            Length = ACPI_GSBUS_BUFFER_SIZE;
+            Function = ACPI_WRITE | (ObjDesc->Field.Attribute << 16);
+        }
         else /* IPMI */
         {
             Length = ACPI_IPMI_BUFFER_SIZE;
@@ -310,7 +322,7 @@
         if (SourceDesc->Buffer.Length < Length)
         {
             ACPI_ERROR ((AE_INFO,
-                "SMBus or IPMI write requires Buffer of length %u, found length %u",
+                "SMBus/IPMI/GenericSerialBus write requires Buffer of length %u, found length %u",
                 Length, SourceDesc->Buffer.Length));
 
             return_ACPI_STATUS (AE_AML_BUFFER_LIMIT);
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/executer/exfldio.c
--- a/head/sys/contrib/dev/acpica/executer/exfldio.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/executer/exfldio.c	Tue Dec 06 20:26:16 2011 +0200
@@ -98,6 +98,7 @@
 {
     ACPI_STATUS             Status = AE_OK;
     ACPI_OPERAND_OBJECT     *RgnDesc;
+    UINT8                   SpaceId;
 
 
     ACPI_FUNCTION_TRACE_U32 (ExSetupRegion, FieldDatumByteOffset);
@@ -116,6 +117,16 @@
         return_ACPI_STATUS (AE_AML_OPERAND_TYPE);
     }
 
+    SpaceId = RgnDesc->Region.SpaceId;
+
+    /* Validate the Space ID */
+
+    if (!AcpiIsValidSpaceId (SpaceId))
+    {
+        ACPI_ERROR ((AE_INFO, "Invalid/unknown Address Space ID: 0x%2.2X", SpaceId));
+        return_ACPI_STATUS (AE_AML_INVALID_SPACE_ID);
+    }
+
     /*
      * If the Region Address and Length have not been previously evaluated,
      * evaluate them now and save the results.
@@ -130,11 +141,12 @@
     }
 
     /*
-     * Exit now for SMBus or IPMI address space, it has a non-linear
+     * Exit now for SMBus, GSBus or IPMI address space, it has a non-linear
      * address space and the request cannot be directly validated
      */
-    if (RgnDesc->Region.SpaceId == ACPI_ADR_SPACE_SMBUS ||
-        RgnDesc->Region.SpaceId == ACPI_ADR_SPACE_IPMI)
+    if (SpaceId == ACPI_ADR_SPACE_SMBUS ||
+        SpaceId == ACPI_ADR_SPACE_GSBUS ||
+        SpaceId == ACPI_ADR_SPACE_IPMI)
     {
         /* SMBus or IPMI has a non-linear address space */
 
@@ -290,7 +302,8 @@
 
     /* Invoke the appropriate AddressSpace/OpRegion handler */
 
-    Status = AcpiEvAddressSpaceDispatch (RgnDesc, Function, RegionOffset,
+    Status = AcpiEvAddressSpaceDispatch (RgnDesc, ObjDesc,
+                Function, RegionOffset,
                 ACPI_MUL_8 (ObjDesc->CommonField.AccessByteWidth), Value);
 
     if (ACPI_FAILURE (Status))
@@ -337,6 +350,8 @@
     ACPI_OPERAND_OBJECT     *ObjDesc,
     UINT64                  Value)
 {
+    ACPI_FUNCTION_NAME (ExRegisterOverflow);
+
 
     if (ObjDesc->CommonField.BitLength >= ACPI_INTEGER_BIT_SIZE)
     {
@@ -353,6 +368,11 @@
          * The Value is larger than the maximum value that can fit into
          * the register.
          */
+        ACPI_ERROR ((AE_INFO,
+            "Index value 0x%8.8X%8.8X overflows field width 0x%X",
+            ACPI_FORMAT_UINT64 (Value),
+            ObjDesc->CommonField.BitLength));
+
         return (TRUE);
     }
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/executer/exprep.c
--- a/head/sys/contrib/dev/acpica/executer/exprep.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/executer/exprep.c	Tue Dec 06 20:26:16 2011 +0200
@@ -49,6 +49,7 @@
 #include <contrib/dev/acpica/include/acinterp.h>
 #include <contrib/dev/acpica/include/amlcode.h>
 #include <contrib/dev/acpica/include/acnamesp.h>
+#include <contrib/dev/acpica/include/acdispat.h>
 
 
 #define _COMPONENT          ACPI_EXECUTER
@@ -484,6 +485,32 @@
 
         ObjDesc->Field.RegionObj = AcpiNsGetAttachedObject (Info->RegionNode);
 
+        /* Fields specific to GenericSerialBus fields */
+
+        ObjDesc->Field.AccessLength = Info->AccessLength;
+
+        if (Info->ConnectionNode)
+        {
+            SecondDesc = Info->ConnectionNode->Object;
+            if (!(SecondDesc->Common.Flags & AOPOBJ_DATA_VALID))
+            {
+                Status = AcpiDsGetBufferArguments (SecondDesc);
+                if (ACPI_FAILURE (Status))
+                {
+                    AcpiUtDeleteObjectDesc (ObjDesc);
+                    return_ACPI_STATUS (Status);
+                }
+            }
+
+            ObjDesc->Field.ResourceBuffer = SecondDesc->Buffer.Pointer;
+            ObjDesc->Field.ResourceLength = (UINT16) SecondDesc->Buffer.Length;
+        }
+        else if (Info->ResourceBuffer)
+        {
+            ObjDesc->Field.ResourceBuffer = Info->ResourceBuffer;
+            ObjDesc->Field.ResourceLength = Info->ResourceLength;
+        }
+
         /* Allow full data read from EC address space */
 
         if ((ObjDesc->Field.RegionObj->Region.SpaceId == ACPI_ADR_SPACE_EC) &&
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/executer/exutils.c
--- a/head/sys/contrib/dev/acpica/executer/exutils.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/executer/exutils.c	Tue Dec 06 20:26:16 2011 +0200
@@ -499,4 +499,34 @@
     }
 }
 
+
+/*******************************************************************************
+ *
+ * FUNCTION:    AcpiIsValidSpaceId
+ *
+ * PARAMETERS:  SpaceId             - ID to be validated
+ *
+ * RETURN:      TRUE if valid/supported ID.
+ *
+ * DESCRIPTION: Validate an operation region SpaceID.
+ *
+ ******************************************************************************/
+
+BOOLEAN
+AcpiIsValidSpaceId (
+    UINT8                   SpaceId)
+{
+
+    if ((SpaceId >= ACPI_NUM_PREDEFINED_REGIONS) &&
+        (SpaceId < ACPI_USER_REGION_BEGIN) &&
+        (SpaceId != ACPI_ADR_SPACE_DATA_TABLE) &&
+        (SpaceId != ACPI_ADR_SPACE_FIXED_HARDWARE))
+    {
+        return (FALSE);
+    }
+
+    return (TRUE);
+}
+
+
 #endif
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/hardware/hwvalid.c
--- a/head/sys/contrib/dev/acpica/hardware/hwvalid.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/hardware/hwvalid.c	Tue Dec 06 20:26:16 2011 +0200
@@ -149,6 +149,8 @@
         (BitWidth != 16) &&
         (BitWidth != 32))
     {
+        ACPI_ERROR ((AE_INFO,
+            "Bad BitWidth parameter: %8.8X", BitWidth));
         return (AE_BAD_PARAMETER);
     }
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/include/acapps.h
--- a/head/sys/contrib/dev/acpica/include/acapps.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/include/acapps.h	Tue Dec 06 20:26:16 2011 +0200
@@ -81,6 +81,15 @@
     Prefix, ACPICA_COPYRIGHT, \
     Prefix
 
+/* Macros for usage messages */
+
+#define ACPI_USAGE_HEADER(Usage) \
+    printf ("Usage: %s\nOptions:\n", Usage);
+
+#define ACPI_OPTION(Name, Description) \
+    printf ("  %-18s%s\n", Name, Description);
+
+
 #define FILE_SUFFIX_DISASSEMBLY     "dsl"
 #define ACPI_TABLE_FILE_SUFFIX      ".dat"
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/include/acconfig.h
--- a/head/sys/contrib/dev/acpica/include/acconfig.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/include/acconfig.h	Tue Dec 06 20:26:16 2011 +0200
@@ -123,7 +123,7 @@
 
 /* Maximum sleep allowed via Sleep() operator */
 
-#define ACPI_MAX_SLEEP                  20000   /* Two seconds */
+#define ACPI_MAX_SLEEP                  2000    /* 2000 millisec == two seconds */
 
 
 /******************************************************************************
@@ -183,9 +183,10 @@
 #define ACPI_RSDP_CHECKSUM_LENGTH       20
 #define ACPI_RSDP_XCHECKSUM_LENGTH      36
 
-/* SMBus and IPMI bidirectional buffer size */
+/* SMBus, GSBus and IPMI bidirectional buffer size */
 
 #define ACPI_SMBUS_BUFFER_SIZE          34
+#define ACPI_GSBUS_BUFFER_SIZE          34
 #define ACPI_IPMI_BUFFER_SIZE           66
 
 /* _SxD and _SxW control methods */
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/include/acdebug.h
--- a/head/sys/contrib/dev/acpica/include/acdebug.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/include/acdebug.h	Tue Dec 06 20:26:16 2011 +0200
@@ -107,6 +107,10 @@
     char                    *TableArg);
 
 void
+AcpiDbDisplayTemplate (
+    char                    *BufferArg);
+
+void
 AcpiDbUnloadAcpiTable (
     char                    *TableArg,
     char                    *InstanceArg);
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/include/acdisasm.h
--- a/head/sys/contrib/dev/acpica/include/acdisasm.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/include/acdisasm.h	Tue Dec 06 20:26:16 2011 +0200
@@ -80,57 +80,82 @@
 
 /*
  * Values for Opcode above.
- * Note: 0-7 must not change, used as a flag shift value
+ * Note: 0-7 must not change, they are used as a flag shift value. Other
+ * than those, new values can be added wherever appropriate.
  */
-#define ACPI_DMT_FLAG0                  0
-#define ACPI_DMT_FLAG1                  1
-#define ACPI_DMT_FLAG2                  2
-#define ACPI_DMT_FLAG3                  3
-#define ACPI_DMT_FLAG4                  4
-#define ACPI_DMT_FLAG5                  5
-#define ACPI_DMT_FLAG6                  6
-#define ACPI_DMT_FLAG7                  7
-#define ACPI_DMT_FLAGS0                 8
-#define ACPI_DMT_FLAGS2                 9
-#define ACPI_DMT_UINT8                  10
-#define ACPI_DMT_UINT16                 11
-#define ACPI_DMT_UINT24                 12
-#define ACPI_DMT_UINT32                 13
-#define ACPI_DMT_UINT56                 14
-#define ACPI_DMT_UINT64                 15
-#define ACPI_DMT_STRING                 16
-#define ACPI_DMT_NAME4                  17
-#define ACPI_DMT_NAME6                  18
-#define ACPI_DMT_NAME8                  19
-#define ACPI_DMT_CHKSUM                 20
-#define ACPI_DMT_SPACEID                21
-#define ACPI_DMT_GAS                    22
-#define ACPI_DMT_ASF                    23
-#define ACPI_DMT_DMAR                   24
-#define ACPI_DMT_HEST                   25
-#define ACPI_DMT_HESTNTFY               26
-#define ACPI_DMT_HESTNTYP               27
-#define ACPI_DMT_MADT                   28
-#define ACPI_DMT_SRAT                   29
-#define ACPI_DMT_EXIT                   30
-#define ACPI_DMT_SIG                    31
-#define ACPI_DMT_FADTPM                 32
-#define ACPI_DMT_BUF16                  33
-#define ACPI_DMT_IVRS                   34
-#define ACPI_DMT_BUFFER                 35
-#define ACPI_DMT_PCI_PATH               36
-#define ACPI_DMT_EINJACT                37
-#define ACPI_DMT_EINJINST               38
-#define ACPI_DMT_ERSTACT                39
-#define ACPI_DMT_ERSTINST               40
-#define ACPI_DMT_ACCWIDTH               41
-#define ACPI_DMT_UNICODE                42
-#define ACPI_DMT_UUID                   43
-#define ACPI_DMT_DEVICE_PATH            44
-#define ACPI_DMT_LABEL                  45
-#define ACPI_DMT_BUF7                   46
-#define ACPI_DMT_BUF128                 47
-#define ACPI_DMT_SLIC                   48
+typedef enum
+{
+    /* Simple Data Types */
+
+    ACPI_DMT_FLAG0          = 0,
+    ACPI_DMT_FLAG1          = 1,
+    ACPI_DMT_FLAG2          = 2,
+    ACPI_DMT_FLAG3          = 3,
+    ACPI_DMT_FLAG4          = 4,
+    ACPI_DMT_FLAG5          = 5,
+    ACPI_DMT_FLAG6          = 6,
+    ACPI_DMT_FLAG7          = 7,
+    ACPI_DMT_FLAGS0,
+    ACPI_DMT_FLAGS1,
+    ACPI_DMT_FLAGS2,
+    ACPI_DMT_FLAGS4,
+    ACPI_DMT_UINT8,
+    ACPI_DMT_UINT16,
+    ACPI_DMT_UINT24,
+    ACPI_DMT_UINT32,
+    ACPI_DMT_UINT40,
+    ACPI_DMT_UINT48,
+    ACPI_DMT_UINT56,
+    ACPI_DMT_UINT64,
+    ACPI_DMT_BUF7,
+    ACPI_DMT_BUF16,
+    ACPI_DMT_BUF128,
+    ACPI_DMT_SIG,
+    ACPI_DMT_STRING,
+    ACPI_DMT_NAME4,
+    ACPI_DMT_NAME6,
+    ACPI_DMT_NAME8,
+
+    /* Types that are decoded to strings and miscellaneous */
+
+    ACPI_DMT_ACCWIDTH,
+    ACPI_DMT_CHKSUM,
+    ACPI_DMT_GAS,
+    ACPI_DMT_SPACEID,
+    ACPI_DMT_UNICODE,
+    ACPI_DMT_UUID,
+
+    /* Types used only for the Data Table Compiler */
+
+    ACPI_DMT_BUFFER,
+    ACPI_DMT_DEVICE_PATH,
+    ACPI_DMT_LABEL,
+    ACPI_DMT_PCI_PATH,
+
+    /* Types that are specific to particular ACPI tables */
+
+    ACPI_DMT_ASF,
+    ACPI_DMT_DMAR,
+    ACPI_DMT_EINJACT,
+    ACPI_DMT_EINJINST,
+    ACPI_DMT_ERSTACT,
+    ACPI_DMT_ERSTINST,
+    ACPI_DMT_FADTPM,
+    ACPI_DMT_HEST,
+    ACPI_DMT_HESTNTFY,
+    ACPI_DMT_HESTNTYP,
+    ACPI_DMT_IVRS,
+    ACPI_DMT_MADT,
+    ACPI_DMT_PMTT,
+    ACPI_DMT_SLIC,
+    ACPI_DMT_SRAT,
+
+    /* Special opcodes */
+
+    ACPI_DMT_EXTRA_TEXT,
+    ACPI_DMT_EXIT
+
+} ACPI_ENTRY_TYPES;
 
 typedef
 void (*ACPI_DMTABLE_HANDLER) (
@@ -175,6 +200,11 @@
 #define ASL_WALK_CALLBACK_DEFINED
 #endif
 
+typedef
+void (*ACPI_RESOURCE_HANDLER) (
+    AML_RESOURCE            *Resource,
+    UINT32                  Length,
+    UINT32                  Level);
 
 typedef struct acpi_resource_tag
 {
@@ -202,6 +232,7 @@
 extern ACPI_DMTABLE_INFO        AcpiDmTableInfoAsfHdr[];
 extern ACPI_DMTABLE_INFO        AcpiDmTableInfoBoot[];
 extern ACPI_DMTABLE_INFO        AcpiDmTableInfoBert[];
+extern ACPI_DMTABLE_INFO        AcpiDmTableInfoBgrt[];
 extern ACPI_DMTABLE_INFO        AcpiDmTableInfoCpep[];
 extern ACPI_DMTABLE_INFO        AcpiDmTableInfoCpep0[];
 extern ACPI_DMTABLE_INFO        AcpiDmTableInfoDbgp[];
@@ -212,6 +243,7 @@
 extern ACPI_DMTABLE_INFO        AcpiDmTableInfoDmar1[];
 extern ACPI_DMTABLE_INFO        AcpiDmTableInfoDmar2[];
 extern ACPI_DMTABLE_INFO        AcpiDmTableInfoDmar3[];
+extern ACPI_DMTABLE_INFO        AcpiDmTableInfoDrtm[];
 extern ACPI_DMTABLE_INFO        AcpiDmTableInfoEcdt[];
 extern ACPI_DMTABLE_INFO        AcpiDmTableInfoEinj[];
 extern ACPI_DMTABLE_INFO        AcpiDmTableInfoEinj0[];
@@ -221,7 +253,13 @@
 extern ACPI_DMTABLE_INFO        AcpiDmTableInfoFadt1[];
 extern ACPI_DMTABLE_INFO        AcpiDmTableInfoFadt2[];
 extern ACPI_DMTABLE_INFO        AcpiDmTableInfoFadt3[];
+extern ACPI_DMTABLE_INFO        AcpiDmTableInfoFadt5[];
+extern ACPI_DMTABLE_INFO        AcpiDmTableInfoFpdt[];
+extern ACPI_DMTABLE_INFO        AcpiDmTableInfoFpdtHdr[];
+extern ACPI_DMTABLE_INFO        AcpiDmTableInfoFpdt0[];
+extern ACPI_DMTABLE_INFO        AcpiDmTableInfoFpdt1[];
 extern ACPI_DMTABLE_INFO        AcpiDmTableInfoGas[];
+extern ACPI_DMTABLE_INFO        AcpiDmTableInfoGtdt[];
 extern ACPI_DMTABLE_INFO        AcpiDmTableInfoHeader[];
 extern ACPI_DMTABLE_INFO        AcpiDmTableInfoHest[];
 extern ACPI_DMTABLE_INFO        AcpiDmTableInfoHest0[];
@@ -254,14 +292,34 @@
 extern ACPI_DMTABLE_INFO        AcpiDmTableInfoMadt8[];
 extern ACPI_DMTABLE_INFO        AcpiDmTableInfoMadt9[];
 extern ACPI_DMTABLE_INFO        AcpiDmTableInfoMadt10[];
+extern ACPI_DMTABLE_INFO        AcpiDmTableInfoMadt11[];
+extern ACPI_DMTABLE_INFO        AcpiDmTableInfoMadt12[];
 extern ACPI_DMTABLE_INFO        AcpiDmTableInfoMadtHdr[];
 extern ACPI_DMTABLE_INFO        AcpiDmTableInfoMcfg[];
 extern ACPI_DMTABLE_INFO        AcpiDmTableInfoMcfg0[];
 extern ACPI_DMTABLE_INFO        AcpiDmTableInfoMchi[];
+extern ACPI_DMTABLE_INFO        AcpiDmTableInfoMpst[];
+extern ACPI_DMTABLE_INFO        AcpiDmTableInfoMpst0[];
+extern ACPI_DMTABLE_INFO        AcpiDmTableInfoMpst0A[];
+extern ACPI_DMTABLE_INFO        AcpiDmTableInfoMpst0B[];
+extern ACPI_DMTABLE_INFO        AcpiDmTableInfoMpst1[];
+extern ACPI_DMTABLE_INFO        AcpiDmTableInfoMpst2[];
 extern ACPI_DMTABLE_INFO        AcpiDmTableInfoMsct[];
 extern ACPI_DMTABLE_INFO        AcpiDmTableInfoMsct0[];
+extern ACPI_DMTABLE_INFO        AcpiDmTableInfoPmtt[];
+extern ACPI_DMTABLE_INFO        AcpiDmTableInfoPmtt0[];
+extern ACPI_DMTABLE_INFO        AcpiDmTableInfoPmtt1[];
+extern ACPI_DMTABLE_INFO        AcpiDmTableInfoPmtt1a[];
+extern ACPI_DMTABLE_INFO        AcpiDmTableInfoPmtt2[];
+extern ACPI_DMTABLE_INFO        AcpiDmTableInfoPmttHdr[];
+extern ACPI_DMTABLE_INFO        AcpiDmTableInfoPcct[];
+extern ACPI_DMTABLE_INFO        AcpiDmTableInfoPcct0[];
 extern ACPI_DMTABLE_INFO        AcpiDmTableInfoRsdp1[];
 extern ACPI_DMTABLE_INFO        AcpiDmTableInfoRsdp2[];
+extern ACPI_DMTABLE_INFO        AcpiDmTableInfoS3pt[];
+extern ACPI_DMTABLE_INFO        AcpiDmTableInfoS3ptHdr[];
+extern ACPI_DMTABLE_INFO        AcpiDmTableInfoS3pt0[];
+extern ACPI_DMTABLE_INFO        AcpiDmTableInfoS3pt1[];
 extern ACPI_DMTABLE_INFO        AcpiDmTableInfoSbst[];
 extern ACPI_DMTABLE_INFO        AcpiDmTableInfoSlicHdr[];
 extern ACPI_DMTABLE_INFO        AcpiDmTableInfoSlic0[];
@@ -354,6 +412,10 @@
     ACPI_TABLE_HEADER       *Table);
 
 void
+AcpiDmDumpFpdt (
+    ACPI_TABLE_HEADER       *Table);
+
+void
 AcpiDmDumpHest (
     ACPI_TABLE_HEADER       *Table);
 
@@ -362,17 +424,29 @@
     ACPI_TABLE_HEADER       *Table);
 
 void
+AcpiDmDumpMadt (
+    ACPI_TABLE_HEADER       *Table);
+
+void
 AcpiDmDumpMcfg (
     ACPI_TABLE_HEADER       *Table);
 
 void
-AcpiDmDumpMadt (
+AcpiDmDumpMpst (
     ACPI_TABLE_HEADER       *Table);
 
 void
 AcpiDmDumpMsct (
     ACPI_TABLE_HEADER       *Table);
 
+void
+AcpiDmDumpPcct (
+    ACPI_TABLE_HEADER       *Table);
+
+void
+AcpiDmDumpPmtt (
+    ACPI_TABLE_HEADER       *Table);
+
 UINT32
 AcpiDmDumpRsdp (
     ACPI_TABLE_HEADER       *Table);
@@ -381,6 +455,10 @@
 AcpiDmDumpRsdt (
     ACPI_TABLE_HEADER       *Table);
 
+UINT32
+AcpiDmDumpS3pt (
+    ACPI_TABLE_HEADER       *Table);
+
 void
 AcpiDmDumpSlic (
     ACPI_TABLE_HEADER       *Table);
@@ -671,6 +749,18 @@
     UINT32                  Level);
 
 void
+AcpiDmGpioDescriptor (
+    AML_RESOURCE            *Resource,
+    UINT32                  Length,
+    UINT32                  Level);
+
+void
+AcpiDmSerialBusDescriptor (
+    AML_RESOURCE            *Resource,
+    UINT32                  Length,
+    UINT32                  Level);
+
+void
 AcpiDmVendorCommon (
     char                    *Name,
     UINT8                   *ByteData,
@@ -694,6 +784,12 @@
     UINT32                  Level);
 
 void
+AcpiDmFixedDmaDescriptor (
+    AML_RESOURCE            *Resource,
+    UINT32                  Length,
+    UINT32                  Level);
+
+void
 AcpiDmIoDescriptor (
     AML_RESOURCE            *Resource,
     UINT32                  Length,
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/include/acevents.h
--- a/head/sys/contrib/dev/acpica/include/acevents.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/include/acevents.h	Tue Dec 06 20:26:16 2011 +0200
@@ -228,7 +228,8 @@
 
 ACPI_STATUS
 AcpiEvAddressSpaceDispatch (
-    ACPI_OPERAND_OBJECT    *RegionObj,
+    ACPI_OPERAND_OBJECT     *RegionObj,
+    ACPI_OPERAND_OBJECT     *FieldObj,
     UINT32                  Function,
     UINT32                  RegionOffset,
     UINT32                  BitWidth,
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/include/acglobal.h
--- a/head/sys/contrib/dev/acpica/include/acglobal.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/include/acglobal.h	Tue Dec 06 20:26:16 2011 +0200
@@ -128,6 +128,12 @@
  */
 UINT8       ACPI_INIT_GLOBAL (AcpiGbl_TruncateIoAddresses, FALSE);
 
+/*
+ * Disable runtime checking and repair of values returned by control methods.
+ * Use only if the repair is causing a problem on a particular machine.
+ */
+UINT8       ACPI_INIT_GLOBAL (AcpiGbl_DisableAutoRepair, FALSE);
+
 
 /* AcpiGbl_FADT is a local copy of the FADT, converted to a common format. */
 
@@ -137,8 +143,20 @@
 ACPI_NAME                   AcpiGbl_TraceMethodName;
 BOOLEAN                     AcpiGbl_SystemAwakeAndRunning;
 
+/*
+ * ACPI 5.0 introduces the concept of a "reduced hardware platform", meaning
+ * that the ACPI hardware is no longer required. A flag in the FADT indicates
+ * a reduced HW machine, and that flag is duplicated here for convenience.
+ */
+BOOLEAN                     AcpiGbl_ReducedHardware;
+
+
 #endif
 
+/* Do not disassemble buffers to resource descriptors */
+
+ACPI_EXTERN UINT8       ACPI_INIT_GLOBAL (AcpiGbl_NoResourceDisassembly, FALSE);
+
 /*****************************************************************************
  *
  * ACPI Table globals
@@ -177,7 +195,7 @@
 
 /*****************************************************************************
  *
- * Mutual exlusion within ACPICA subsystem
+ * Mutual exclusion within ACPICA subsystem
  *
  ****************************************************************************/
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/include/acinterp.h
--- a/head/sys/contrib/dev/acpica/include/acinterp.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/include/acinterp.h	Tue Dec 06 20:26:16 2011 +0200
@@ -642,6 +642,10 @@
     char                    *Dest,
     UINT64                  Value);
 
+BOOLEAN
+AcpiIsValidSpaceId (
+    UINT8                   SpaceId);
+
 
 /*
  * exregion - default OpRegion handlers
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/include/aclocal.h
--- a/head/sys/contrib/dev/acpica/include/aclocal.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/include/aclocal.h	Tue Dec 06 20:26:16 2011 +0200
@@ -54,7 +54,7 @@
 
 /* Total number of aml opcodes defined */
 
-#define AML_NUM_OPCODES                 0x7F
+#define AML_NUM_OPCODES                 0x81
 
 
 /* Forward declarations */
@@ -213,7 +213,6 @@
 #define ANOBJ_IS_EXTERNAL               0x08    /* iASL only: This object created via External() */
 #define ANOBJ_METHOD_NO_RETVAL          0x10    /* iASL only: Method has no return value */
 #define ANOBJ_METHOD_SOME_NO_RETVAL     0x20    /* iASL only: Method has at least one return value */
-#define ANOBJ_IS_BIT_OFFSET             0x40    /* iASL only: Reference is a bit offset */
 #define ANOBJ_IS_REFERENCED             0x80    /* iASL only: Object was referenced */
 
 
@@ -286,12 +285,16 @@
     ACPI_NAMESPACE_NODE             *FieldNode;
     ACPI_NAMESPACE_NODE             *RegisterNode;
     ACPI_NAMESPACE_NODE             *DataRegisterNode;
+    ACPI_NAMESPACE_NODE             *ConnectionNode;
+    UINT8                           *ResourceBuffer;
     UINT32                          BankValue;
     UINT32                          FieldBitPosition;
     UINT32                          FieldBitLength;
+    UINT16                          ResourceLength;
     UINT8                           FieldFlags;
     UINT8                           Attribute;
     UINT8                           FieldType;
+    UINT8                           AccessLength;
 
 } ACPI_CREATE_FIELD_INFO;
 
@@ -359,7 +362,8 @@
 
 /*
  * Used for ACPI_PTYPE1_FIXED, ACPI_PTYPE1_VAR, ACPI_PTYPE2,
- * ACPI_PTYPE2_MIN, ACPI_PTYPE2_PKG_COUNT, ACPI_PTYPE2_COUNT
+ * ACPI_PTYPE2_MIN, ACPI_PTYPE2_PKG_COUNT, ACPI_PTYPE2_COUNT,
+ * ACPI_PTYPE2_FIX_VAR
  */
 typedef struct acpi_package_info
 {
@@ -411,6 +415,7 @@
     char                        *Pathname;
     const ACPI_PREDEFINED_INFO  *Predefined;
     union acpi_operand_object   *ParentPackage;
+    ACPI_NAMESPACE_NODE         *Node;
     UINT32                      Flags;
     UINT8                       NodeFlags;
 
@@ -774,6 +779,17 @@
 
 } ACPI_OPCODE_INFO;
 
+/* Structure for Resource Tag information */
+
+typedef struct acpi_tag_info
+{
+    UINT32                          BitOffset;
+    UINT32                          BitLength;
+
+} ACPI_TAG_INFO;
+
+/* Value associated with the parse object */
+
 typedef union acpi_parse_value
 {
     UINT64                          Integer;        /* Integer constant (Up to 64 bits) */
@@ -782,6 +798,7 @@
     UINT8                           *Buffer;        /* buffer or string */
     char                            *Name;          /* NULL terminated string */
     union acpi_parse_object         *Arg;           /* arguments and contained ops */
+    ACPI_TAG_INFO                   Tag;            /* Resource descriptor tag info  */
 
 } ACPI_PARSE_VALUE;
 
@@ -1112,7 +1129,7 @@
 #define ACPI_RESOURCE_NAME_END_DEPENDENT        0x38
 #define ACPI_RESOURCE_NAME_IO                   0x40
 #define ACPI_RESOURCE_NAME_FIXED_IO             0x48
-#define ACPI_RESOURCE_NAME_RESERVED_S1          0x50
+#define ACPI_RESOURCE_NAME_FIXED_DMA            0x50
 #define ACPI_RESOURCE_NAME_RESERVED_S2          0x58
 #define ACPI_RESOURCE_NAME_RESERVED_S3          0x60
 #define ACPI_RESOURCE_NAME_RESERVED_S4          0x68
@@ -1134,7 +1151,9 @@
 #define ACPI_RESOURCE_NAME_EXTENDED_IRQ         0x89
 #define ACPI_RESOURCE_NAME_ADDRESS64            0x8A
 #define ACPI_RESOURCE_NAME_EXTENDED_ADDRESS64   0x8B
-#define ACPI_RESOURCE_NAME_LARGE_MAX            0x8B
+#define ACPI_RESOURCE_NAME_GPIO                 0x8C
+#define ACPI_RESOURCE_NAME_SERIAL_BUS           0x8E
+#define ACPI_RESOURCE_NAME_LARGE_MAX            0x8E
 
 
 /*****************************************************************************
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/include/acnames.h
--- a/head/sys/contrib/dev/acpica/include/acnames.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/include/acnames.h	Tue Dec 06 20:26:16 2011 +0200
@@ -58,6 +58,7 @@
 #define METHOD_NAME__PRT        "_PRT"
 #define METHOD_NAME__CRS        "_CRS"
 #define METHOD_NAME__PRS        "_PRS"
+#define METHOD_NAME__AEI        "_AEI"
 #define METHOD_NAME__PRW        "_PRW"
 #define METHOD_NAME__SRS        "_SRS"
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/include/acobject.h
--- a/head/sys/contrib/dev/acpica/include/acobject.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/include/acobject.h	Tue Dec 06 20:26:16 2011 +0200
@@ -320,6 +320,7 @@
     UINT32                          BaseByteOffset;     /* Byte offset within containing object */\
     UINT32                          Value;              /* Value to store into the Bank or Index register */\
     UINT8                           StartFieldBitOffset;/* Bit offset within first field datum (0-63) */\
+    UINT8                           AccessLength;       /* For serial regions/fields */
 
 
 typedef struct acpi_object_field_common                 /* COMMON FIELD (for BUFFER, REGION, BANK, and INDEX fields) */
@@ -335,7 +336,9 @@
 {
     ACPI_OBJECT_COMMON_HEADER
     ACPI_COMMON_FIELD_INFO
+    UINT16                          ResourceLength;
     union acpi_operand_object       *RegionObj;         /* Containing OpRegion object */
+    UINT8                           *ResourceBuffer;    /* ResourceTemplate for serial regions/fields */
 
 } ACPI_OBJECT_REGION_FIELD;
 
@@ -463,6 +466,7 @@
 {
     ACPI_OBJECT_COMMON_HEADER
     ACPI_NAMESPACE_NODE             *Method_REG;        /* _REG method for this region (if any) */
+    ACPI_NAMESPACE_NODE             *ScopeNode;
     void                            *RegionContext;     /* Region-specific data */
     UINT8                           *AmlStart;
     UINT32                          AmlLength;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/include/acopcode.h
--- a/head/sys/contrib/dev/acpica/include/acopcode.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/include/acopcode.h	Tue Dec 06 20:26:16 2011 +0200
@@ -94,6 +94,7 @@
 #define ARGP_CONCAT_OP                  ARGP_LIST3 (ARGP_TERMARG,    ARGP_TERMARG,       ARGP_TARGET)
 #define ARGP_CONCAT_RES_OP              ARGP_LIST3 (ARGP_TERMARG,    ARGP_TERMARG,       ARGP_TARGET)
 #define ARGP_COND_REF_OF_OP             ARGP_LIST2 (ARGP_SUPERNAME,  ARGP_SUPERNAME)
+#define ARGP_CONNECTFIELD_OP            ARGP_LIST1 (ARGP_NAMESTRING)
 #define ARGP_CONTINUE_OP                ARG_NONE
 #define ARGP_COPY_OP                    ARGP_LIST2 (ARGP_TERMARG,    ARGP_SIMPLENAME)
 #define ARGP_CREATE_BIT_FIELD_OP        ARGP_LIST3 (ARGP_TERMARG,    ARGP_TERMARG,       ARGP_NAME)
@@ -165,6 +166,7 @@
 #define ARGP_RETURN_OP                  ARGP_LIST1 (ARGP_TERMARG)
 #define ARGP_REVISION_OP                ARG_NONE
 #define ARGP_SCOPE_OP                   ARGP_LIST3 (ARGP_PKGLENGTH,  ARGP_NAME,          ARGP_TERMLIST)
+#define ARGP_SERIALFIELD_OP             ARGP_LIST1 (ARGP_NAMESTRING)
 #define ARGP_SHIFT_LEFT_OP              ARGP_LIST3 (ARGP_TERMARG,    ARGP_TERMARG,       ARGP_TARGET)
 #define ARGP_SHIFT_RIGHT_OP             ARGP_LIST3 (ARGP_TERMARG,    ARGP_TERMARG,       ARGP_TARGET)
 #define ARGP_SIGNAL_OP                  ARGP_LIST1 (ARGP_SUPERNAME)
@@ -225,6 +227,7 @@
 #define ARGI_CONCAT_OP                  ARGI_LIST3 (ARGI_COMPUTEDATA,ARGI_COMPUTEDATA,   ARGI_TARGETREF)
 #define ARGI_CONCAT_RES_OP              ARGI_LIST3 (ARGI_BUFFER,     ARGI_BUFFER,        ARGI_TARGETREF)
 #define ARGI_COND_REF_OF_OP             ARGI_LIST2 (ARGI_OBJECT_REF, ARGI_TARGETREF)
+#define ARGI_CONNECTFIELD_OP            ARGI_INVALID_OPCODE
 #define ARGI_CONTINUE_OP                ARGI_INVALID_OPCODE
 #define ARGI_COPY_OP                    ARGI_LIST2 (ARGI_ANYTYPE,    ARGI_SIMPLE_TARGET)
 #define ARGI_CREATE_BIT_FIELD_OP        ARGI_LIST3 (ARGI_BUFFER,     ARGI_INTEGER,       ARGI_REFERENCE)
@@ -296,6 +299,7 @@
 #define ARGI_RETURN_OP                  ARGI_INVALID_OPCODE
 #define ARGI_REVISION_OP                ARG_NONE
 #define ARGI_SCOPE_OP                   ARGI_INVALID_OPCODE
+#define ARGI_SERIALFIELD_OP             ARGI_INVALID_OPCODE
 #define ARGI_SHIFT_LEFT_OP              ARGI_LIST3 (ARGI_INTEGER,    ARGI_INTEGER,       ARGI_TARGETREF)
 #define ARGI_SHIFT_RIGHT_OP             ARGI_LIST3 (ARGI_INTEGER,    ARGI_INTEGER,       ARGI_TARGETREF)
 #define ARGI_SIGNAL_OP                  ARGI_LIST1 (ARGI_EVENT)
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/include/acpixf.h
--- a/head/sys/contrib/dev/acpica/include/acpixf.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/include/acpixf.h	Tue Dec 06 20:26:16 2011 +0200
@@ -48,7 +48,7 @@
 
 /* Current ACPICA subsystem version in YYYYMMDD format */
 
-#define ACPI_CA_VERSION                 0x20110527
+#define ACPI_CA_VERSION                 0x20111123
 
 #include <contrib/dev/acpica/include/actypes.h>
 #include <contrib/dev/acpica/include/actbl.h>
@@ -59,6 +59,7 @@
 extern UINT32               AcpiCurrentGpeCount;
 extern ACPI_TABLE_FADT      AcpiGbl_FADT;
 extern BOOLEAN              AcpiGbl_SystemAwakeAndRunning;
+extern BOOLEAN              AcpiGbl_ReducedHardware;        /* ACPI 5.0 */
 
 /* Runtime configuration of debug print levels */
 
@@ -76,6 +77,7 @@
 extern UINT8                AcpiGbl_EnableAmlDebugObject;
 extern UINT8                AcpiGbl_CopyDsdtLocally;
 extern UINT8                AcpiGbl_TruncateIoAddresses;
+extern UINT8                AcpiGbl_DisableAutoRepair;
 
 
 /*
@@ -392,6 +394,21 @@
 
 
 /*
+ * Interfaces to AML mutex objects
+ */
+ACPI_STATUS
+AcpiAcquireMutex (
+    ACPI_HANDLE             Handle,
+    ACPI_STRING             Pathname,
+    UINT16                  Timeout);
+
+ACPI_STATUS
+AcpiReleaseMutex (
+    ACPI_HANDLE             Handle,
+    ACPI_STRING             Pathname);
+
+
+/*
  * Fixed Event interfaces
  */
 ACPI_STATUS
@@ -516,6 +533,11 @@
     ACPI_BUFFER             *RetBuffer);
 
 ACPI_STATUS
+AcpiGetEventResources (
+    ACPI_HANDLE             DeviceHandle,
+    ACPI_BUFFER             *RetBuffer);
+
+ACPI_STATUS
 AcpiWalkResources (
     ACPI_HANDLE                 Device,
     char                        *Name,
@@ -537,6 +559,12 @@
     ACPI_RESOURCE           *Resource,
     ACPI_RESOURCE_ADDRESS64 *Out);
 
+ACPI_STATUS
+AcpiBufferToResource (
+    UINT8                   *AmlBuffer,
+    UINT16                  AmlBufferLength,
+    ACPI_RESOURCE           **ResourcePtr);
+
 
 /*
  * Hardware (ACPI device) interfaces
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/include/acpredef.h
--- a/head/sys/contrib/dev/acpica/include/acpredef.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/include/acpredef.h	Tue Dec 06 20:26:16 2011 +0200
@@ -94,6 +94,14 @@
  * ACPI_PTYPE2_REV_FIXED: Revision at start, each subpackage is Fixed-length
  *      (Used for _ART, _FPS)
  *
+ * ACPI_PTYPE2_FIX_VAR: Each subpackage consists of some fixed-length elements
+ *      followed by an optional element
+ *      object type
+ *      count
+ *      object type
+ *      count = 0 (optional)
+ *      (Used for _DLM)
+ *
  *****************************************************************************/
 
 enum AcpiReturnPackageTypes
@@ -106,7 +114,8 @@
     ACPI_PTYPE2_PKG_COUNT   = 6,
     ACPI_PTYPE2_FIXED       = 7,
     ACPI_PTYPE2_MIN         = 8,
-    ACPI_PTYPE2_REV_FIXED   = 9
+    ACPI_PTYPE2_REV_FIXED   = 9,
+    ACPI_PTYPE2_FIX_VAR     = 10
 };
 
 
@@ -159,6 +168,7 @@
     {{"_AC8", 0, ACPI_RTYPE_INTEGER}},
     {{"_AC9", 0, ACPI_RTYPE_INTEGER}},
     {{"_ADR", 0, ACPI_RTYPE_INTEGER}},
+    {{"_AEI", 0, ACPI_RTYPE_BUFFER}},
     {{"_AL0", 0, ACPI_RTYPE_PACKAGE}}, /* Variable-length (Refs) */
                     {{{ACPI_PTYPE1_VAR, ACPI_RTYPE_REFERENCE, 0,0}, 0,0}},
 
@@ -231,6 +241,12 @@
     {{"_CID", 0, ACPI_RTYPE_INTEGER | ACPI_RTYPE_STRING | ACPI_RTYPE_PACKAGE}}, /* Variable-length (Ints/Strs) */
                     {{{ACPI_PTYPE1_VAR, ACPI_RTYPE_INTEGER | ACPI_RTYPE_STRING, 0,0}, 0,0}},
 
+    {{"_CLS", 0, ACPI_RTYPE_PACKAGE}}, /* Fixed-length (3 Int) */
+                    {{{ACPI_PTYPE1_FIXED, ACPI_RTYPE_INTEGER, 3,0}, 0,0}},
+
+    {{"_CPC", 0, ACPI_RTYPE_PACKAGE}}, /* Variable-length (Ints/Bufs) */
+                    {{{ACPI_PTYPE1_VAR, ACPI_RTYPE_INTEGER | ACPI_RTYPE_BUFFER, 0,0}, 0,0}},
+
     {{"_CRS", 0, ACPI_RTYPE_BUFFER}},
     {{"_CRT", 0, ACPI_RTYPE_INTEGER}},
     {{"_CSD", 0, ACPI_RTYPE_PACKAGE}}, /* Variable-length (1 Int(n), n-1 Int) */
@@ -239,12 +255,20 @@
     {{"_CST", 0, ACPI_RTYPE_PACKAGE}}, /* Variable-length (1 Int(n), n Pkg (1 Buf/3 Int) */
                     {{{ACPI_PTYPE2_PKG_COUNT,ACPI_RTYPE_BUFFER, 1, ACPI_RTYPE_INTEGER}, 3,0}},
 
+    {{"_CWS", 1, ACPI_RTYPE_INTEGER}},
     {{"_DCK", 1, ACPI_RTYPE_INTEGER}},
     {{"_DCS", 0, ACPI_RTYPE_INTEGER}},
     {{"_DDC", 1, ACPI_RTYPE_INTEGER | ACPI_RTYPE_BUFFER}},
     {{"_DDN", 0, ACPI_RTYPE_STRING}},
+    {{"_DEP", 0, ACPI_RTYPE_PACKAGE}}, /* Variable-length (Refs) */
+                    {{{ACPI_PTYPE1_VAR, ACPI_RTYPE_REFERENCE, 0,0}, 0,0}},
+
     {{"_DGS", 0, ACPI_RTYPE_INTEGER}},
     {{"_DIS", 0, 0}},
+
+    {{"_DLM", 0, ACPI_RTYPE_PACKAGE}}, /* Variable-length (Pkgs) each (1 Ref, 0/1 Optional Buf/Ref) */
+                    {{{ACPI_PTYPE2_FIX_VAR, ACPI_RTYPE_REFERENCE, 1, ACPI_RTYPE_REFERENCE | ACPI_RTYPE_BUFFER}, 0,0}},
+
     {{"_DMA", 0, ACPI_RTYPE_BUFFER}},
     {{"_DOD", 0, ACPI_RTYPE_PACKAGE}}, /* Variable-length (Ints) */
                     {{{ACPI_PTYPE1_VAR, ACPI_RTYPE_INTEGER, 0,0}, 0,0}},
@@ -264,6 +288,8 @@
     {{"_EJ3", 1, 0}},
     {{"_EJ4", 1, 0}},
     {{"_EJD", 0, ACPI_RTYPE_STRING}},
+    {{"_ERR", 3, ACPI_RTYPE_INTEGER}}, /* Internal use only, used by ACPICA test suites */
+    {{"_EVT", 1, 0}},
     {{"_FDE", 0, ACPI_RTYPE_BUFFER}},
     {{"_FDI", 0, ACPI_RTYPE_PACKAGE}}, /* Fixed-length (16 Int) */
                     {{{ACPI_PTYPE1_FIXED, ACPI_RTYPE_INTEGER, 16,0}, 0,0}},
@@ -284,14 +310,17 @@
 
 
     {{"_GAI", 0, ACPI_RTYPE_INTEGER}},
+    {{"_GCP", 0, ACPI_RTYPE_INTEGER}},
     {{"_GHL", 0, ACPI_RTYPE_INTEGER}},
     {{"_GLK", 0, ACPI_RTYPE_INTEGER}},
     {{"_GPD", 0, ACPI_RTYPE_INTEGER}},
     {{"_GPE", 0, ACPI_RTYPE_INTEGER}}, /* _GPE method, not _GPE scope */
+    {{"_GRT", 0, ACPI_RTYPE_BUFFER}},
     {{"_GSB", 0, ACPI_RTYPE_INTEGER}},
     {{"_GTF", 0, ACPI_RTYPE_BUFFER}},
     {{"_GTM", 0, ACPI_RTYPE_BUFFER}},
     {{"_GTS", 1, 0}},
+    {{"_GWS", 1, ACPI_RTYPE_INTEGER}},
     {{"_HID", 0, ACPI_RTYPE_INTEGER | ACPI_RTYPE_STRING}},
     {{"_HOT", 0, ACPI_RTYPE_INTEGER}},
     {{"_HPP", 0, ACPI_RTYPE_PACKAGE}}, /* Fixed-length (4 Int) */
@@ -306,6 +335,7 @@
     {{"_HPX", 0, ACPI_RTYPE_PACKAGE}}, /* Variable-length (Pkgs) each (var Ints) */
                     {{{ACPI_PTYPE2_MIN, ACPI_RTYPE_INTEGER, 5,0}, 0,0}},
 
+    {{"_HRV", 0, ACPI_RTYPE_INTEGER}},
     {{"_IFT", 0, ACPI_RTYPE_INTEGER}}, /* See IPMI spec */
     {{"_INI", 0, 0}},
     {{"_IRC", 0, 0}},
@@ -363,6 +393,9 @@
     {{"_PR3", 0, ACPI_RTYPE_PACKAGE}}, /* Variable-length (Refs) */
                     {{{ACPI_PTYPE1_VAR, ACPI_RTYPE_REFERENCE, 0,0}, 0,0}},
 
+    {{"_PRE", 0, ACPI_RTYPE_PACKAGE}}, /* Variable-length (Refs) */
+                    {{{ACPI_PTYPE1_VAR, ACPI_RTYPE_REFERENCE, 0,0}, 0,0}},
+
     {{"_PRL", 0, ACPI_RTYPE_PACKAGE}}, /* Variable-length (Refs) */
                     {{{ACPI_PTYPE1_VAR, ACPI_RTYPE_REFERENCE, 0,0}, 0,0}},
 
@@ -393,6 +426,7 @@
     {{"_PSD", 0, ACPI_RTYPE_PACKAGE}}, /* Variable-length (Pkgs) each (5 Int) with count */
                     {{{ACPI_PTYPE2_COUNT, ACPI_RTYPE_INTEGER,0,0}, 0,0}},
 
+    {{"_PSE", 1, 0}},
     {{"_PSL", 0, ACPI_RTYPE_PACKAGE}}, /* Variable-length (Refs) */
                     {{{ACPI_PTYPE1_VAR, ACPI_RTYPE_REFERENCE, 0,0}, 0,0}},
 
@@ -459,6 +493,7 @@
     {{"_SLI", 0, ACPI_RTYPE_BUFFER}},
     {{"_SPD", 1, ACPI_RTYPE_INTEGER}},
     {{"_SRS", 1, 0}},
+    {{"_SRT", 1, ACPI_RTYPE_INTEGER}},
     {{"_SRV", 0, ACPI_RTYPE_INTEGER}}, /* See IPMI spec */
     {{"_SST", 1, 0}},
     {{"_STA", 0, ACPI_RTYPE_INTEGER}},
@@ -466,6 +501,7 @@
     {{"_STP", 2, ACPI_RTYPE_INTEGER}},
     {{"_STR", 0, ACPI_RTYPE_BUFFER}},
     {{"_STV", 2, ACPI_RTYPE_INTEGER}},
+    {{"_SUB", 0, ACPI_RTYPE_STRING}},
     {{"_SUN", 0, ACPI_RTYPE_INTEGER}},
     {{"_SWS", 0, ACPI_RTYPE_INTEGER}},
     {{"_TC1", 0, ACPI_RTYPE_INTEGER}},
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/include/acresrc.h
--- a/head/sys/contrib/dev/acpica/include/acresrc.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/include/acresrc.h	Tue Dec 06 20:26:16 2011 +0200
@@ -75,28 +75,42 @@
 
 /* Resource conversion opcodes */
 
-#define ACPI_RSC_INITGET                0
-#define ACPI_RSC_INITSET                1
-#define ACPI_RSC_FLAGINIT               2
-#define ACPI_RSC_1BITFLAG               3
-#define ACPI_RSC_2BITFLAG               4
-#define ACPI_RSC_COUNT                  5
-#define ACPI_RSC_COUNT16                6
-#define ACPI_RSC_LENGTH                 7
-#define ACPI_RSC_MOVE8                  8
-#define ACPI_RSC_MOVE16                 9
-#define ACPI_RSC_MOVE32                 10
-#define ACPI_RSC_MOVE64                 11
-#define ACPI_RSC_SET8                   12
-#define ACPI_RSC_DATA8                  13
-#define ACPI_RSC_ADDRESS                14
-#define ACPI_RSC_SOURCE                 15
-#define ACPI_RSC_SOURCEX                16
-#define ACPI_RSC_BITMASK                17
-#define ACPI_RSC_BITMASK16              18
-#define ACPI_RSC_EXIT_NE                19
-#define ACPI_RSC_EXIT_LE                20
-#define ACPI_RSC_EXIT_EQ                21
+typedef enum
+{
+    ACPI_RSC_INITGET        = 0,
+    ACPI_RSC_INITSET,
+    ACPI_RSC_FLAGINIT,
+    ACPI_RSC_1BITFLAG,
+    ACPI_RSC_2BITFLAG,
+    ACPI_RSC_3BITFLAG,
+    ACPI_RSC_ADDRESS,
+    ACPI_RSC_BITMASK,
+    ACPI_RSC_BITMASK16,
+    ACPI_RSC_COUNT,
+    ACPI_RSC_COUNT16,
+    ACPI_RSC_COUNT_GPIO_PIN,
+    ACPI_RSC_COUNT_GPIO_RES,
+    ACPI_RSC_COUNT_GPIO_VEN,
+    ACPI_RSC_COUNT_SERIAL_RES,
+    ACPI_RSC_COUNT_SERIAL_VEN,
+    ACPI_RSC_DATA8,
+    ACPI_RSC_EXIT_EQ,
+    ACPI_RSC_EXIT_LE,
+    ACPI_RSC_EXIT_NE,
+    ACPI_RSC_LENGTH,
+    ACPI_RSC_MOVE_GPIO_PIN,
+    ACPI_RSC_MOVE_GPIO_RES,
+    ACPI_RSC_MOVE_SERIAL_RES,
+    ACPI_RSC_MOVE_SERIAL_VEN,
+    ACPI_RSC_MOVE8,
+    ACPI_RSC_MOVE16,
+    ACPI_RSC_MOVE32,
+    ACPI_RSC_MOVE64,
+    ACPI_RSC_SET8,
+    ACPI_RSC_SOURCE,
+    ACPI_RSC_SOURCEX
+
+} ACPI_RSCONVERT_OPCODES;
 
 /* Resource Conversion sub-opcodes */
 
@@ -109,6 +123,9 @@
 #define AML_OFFSET(f)                   (UINT8) ACPI_OFFSET (AML_RESOURCE,f)
 
 
+/*
+ * Individual entry for the resource dump tables
+ */
 typedef const struct acpi_rsdump_info
 {
     UINT8                   Opcode;
@@ -120,20 +137,27 @@
 
 /* Values for the Opcode field above */
 
-#define ACPI_RSD_TITLE                  0
-#define ACPI_RSD_LITERAL                1
-#define ACPI_RSD_STRING                 2
-#define ACPI_RSD_UINT8                  3
-#define ACPI_RSD_UINT16                 4
-#define ACPI_RSD_UINT32                 5
-#define ACPI_RSD_UINT64                 6
-#define ACPI_RSD_1BITFLAG               7
-#define ACPI_RSD_2BITFLAG               8
-#define ACPI_RSD_SHORTLIST              9
-#define ACPI_RSD_LONGLIST               10
-#define ACPI_RSD_DWORDLIST              11
-#define ACPI_RSD_ADDRESS                12
-#define ACPI_RSD_SOURCE                 13
+typedef enum
+{
+    ACPI_RSD_TITLE          = 0,
+    ACPI_RSD_1BITFLAG,
+    ACPI_RSD_2BITFLAG,
+    ACPI_RSD_3BITFLAG,
+    ACPI_RSD_ADDRESS,
+    ACPI_RSD_DWORDLIST,
+    ACPI_RSD_LITERAL,
+    ACPI_RSD_LONGLIST,
+    ACPI_RSD_SHORTLIST,
+    ACPI_RSD_SHORTLISTX,
+    ACPI_RSD_SOURCE,
+    ACPI_RSD_STRING,
+    ACPI_RSD_UINT8,
+    ACPI_RSD_UINT16,
+    ACPI_RSD_UINT32,
+    ACPI_RSD_UINT64,
+    ACPI_RSD_WORDLIST
+
+} ACPI_RSDUMP_OPCODES;
 
 /* restore default alignment */
 
@@ -143,13 +167,16 @@
 /* Resource tables indexed by internal resource type */
 
 extern const UINT8              AcpiGbl_AmlResourceSizes[];
+extern const UINT8              AcpiGbl_AmlResourceSerialBusSizes[];
 extern ACPI_RSCONVERT_INFO      *AcpiGbl_SetResourceDispatch[];
 
 /* Resource tables indexed by raw AML resource descriptor type */
 
 extern const UINT8              AcpiGbl_ResourceStructSizes[];
+extern const UINT8              AcpiGbl_ResourceStructSerialBusSizes[];
 extern ACPI_RSCONVERT_INFO      *AcpiGbl_GetResourceDispatch[];
 
+extern ACPI_RSCONVERT_INFO      *AcpiGbl_ConvertResourceSerialBusDispatch[];
 
 typedef struct acpi_vendor_walk_info
 {
@@ -208,6 +235,10 @@
     ACPI_NAMESPACE_NODE     *Node,
     ACPI_BUFFER             *RetBuffer);
 
+ACPI_STATUS
+AcpiRsGetAeiMethodData (
+    ACPI_NAMESPACE_NODE     *Node,
+    ACPI_BUFFER             *RetBuffer);
 
 /*
  * rscalc
@@ -348,6 +379,11 @@
 extern ACPI_RSCONVERT_INFO      AcpiRsConvertExtIrq[];
 extern ACPI_RSCONVERT_INFO      AcpiRsConvertAddress64[];
 extern ACPI_RSCONVERT_INFO      AcpiRsConvertExtAddress64[];
+extern ACPI_RSCONVERT_INFO      AcpiRsConvertGpio[];
+extern ACPI_RSCONVERT_INFO      AcpiRsConvertFixedDma[];
+extern ACPI_RSCONVERT_INFO      AcpiRsConvertI2cSerialBus[];
+extern ACPI_RSCONVERT_INFO      AcpiRsConvertSpiSerialBus[];
+extern ACPI_RSCONVERT_INFO      AcpiRsConvertUartSerialBus[];
 
 /* These resources require separate get/set tables */
 
@@ -366,6 +402,7 @@
  * rsinfo
  */
 extern ACPI_RSDUMP_INFO         *AcpiGbl_DumpResourceDispatch[];
+extern ACPI_RSDUMP_INFO         *AcpiGbl_DumpSerialBusDispatch[];
 
 /*
  * rsdump
@@ -387,6 +424,12 @@
 extern ACPI_RSDUMP_INFO         AcpiRsDumpExtAddress64[];
 extern ACPI_RSDUMP_INFO         AcpiRsDumpExtIrq[];
 extern ACPI_RSDUMP_INFO         AcpiRsDumpGenericReg[];
+extern ACPI_RSDUMP_INFO         AcpiRsDumpGpio[];
+extern ACPI_RSDUMP_INFO         AcpiRsDumpFixedDma[];
+extern ACPI_RSDUMP_INFO         AcpiRsDumpCommonSerialBus[];
+extern ACPI_RSDUMP_INFO         AcpiRsDumpI2cSerialBus[];
+extern ACPI_RSDUMP_INFO         AcpiRsDumpSpiSerialBus[];
+extern ACPI_RSDUMP_INFO         AcpiRsDumpUartSerialBus[];
 #endif
 
 #endif  /* __ACRESRC_H__ */
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/include/acrestyp.h
--- a/head/sys/contrib/dev/acpica/include/acrestyp.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/include/acrestyp.h	Tue Dec 06 20:26:16 2011 +0200
@@ -62,11 +62,14 @@
 #define ACPI_WRITE_COMBINING_MEMORY     (UINT8) 0x02
 #define ACPI_PREFETCHABLE_MEMORY        (UINT8) 0x03
 
+/*! [Begin] no source code translation */
 /*
  * IO Attributes
  * The ISA IO ranges are:     n000-n0FFh,  n400-n4FFh, n800-n8FFh, nC00-nCFFh.
  * The non-ISA IO ranges are: n100-n3FFh,  n500-n7FFh, n900-nBFFh, nCD0-nFFFh.
  */
+/*! [End] no source code translation !*/
+
 #define ACPI_NON_ISA_ONLY_RANGES        (UINT8) 0x01
 #define ACPI_ISA_ONLY_RANGES            (UINT8) 0x02
 #define ACPI_ENTIRE_RANGE               (ACPI_NON_ISA_ONLY_RANGES | ACPI_ISA_ONLY_RANGES)
@@ -82,16 +85,26 @@
 #define ACPI_DECODE_16                  (UINT8) 0x01    /* 16-bit IO address decode */
 
 /*
- * IRQ Attributes
+ * Interrupt attributes - used in multiple descriptors
  */
+
+/* Triggering */
+
 #define ACPI_LEVEL_SENSITIVE            (UINT8) 0x00
 #define ACPI_EDGE_SENSITIVE             (UINT8) 0x01
 
+/* Polarity */
+
 #define ACPI_ACTIVE_HIGH                (UINT8) 0x00
 #define ACPI_ACTIVE_LOW                 (UINT8) 0x01
+#define ACPI_ACTIVE_BOTH                (UINT8) 0x02
+
+/* Sharing */
 
 #define ACPI_EXCLUSIVE                  (UINT8) 0x00
 #define ACPI_SHARED                     (UINT8) 0x01
+#define ACPI_EXCLUSIVE_AND_WAKE         (UINT8) 0x02
+#define ACPI_SHARED_AND_WAKE            (UINT8) 0x03
 
 /*
  * DMA Attributes
@@ -128,6 +141,8 @@
 #define ACPI_POS_DECODE                 (UINT8) 0x00
 #define ACPI_SUB_DECODE                 (UINT8) 0x01
 
+/* Producer/Consumer */
+
 #define ACPI_PRODUCER                   (UINT8) 0x00
 #define ACPI_CONSUMER                   (UINT8) 0x01
 
@@ -167,7 +182,7 @@
 
 } ACPI_RESOURCE_IRQ;
 
-typedef struct ACPI_RESOURCE_DMA
+typedef struct acpi_resource_dma
 {
     UINT8                           Type;
     UINT8                           BusMaster;
@@ -209,6 +224,24 @@
 
 } ACPI_RESOURCE_FIXED_IO;
 
+typedef struct acpi_resource_fixed_dma
+{
+    UINT16                          RequestLines;
+    UINT16                          Channels;
+    UINT8                           Width;
+
+} ACPI_RESOURCE_FIXED_DMA;
+
+/* Values for Width field above */
+
+#define ACPI_DMA_WIDTH8                         0
+#define ACPI_DMA_WIDTH16                        1
+#define ACPI_DMA_WIDTH32                        2
+#define ACPI_DMA_WIDTH64                        3
+#define ACPI_DMA_WIDTH128                       4
+#define ACPI_DMA_WIDTH256                       5
+
+
 typedef struct acpi_resource_vendor
 {
     UINT16                          ByteLength;
@@ -385,6 +418,184 @@
 
 } ACPI_RESOURCE_GENERIC_REGISTER;
 
+typedef struct acpi_resource_gpio
+{
+    UINT8                           RevisionId;
+    UINT8                           ConnectionType;
+    UINT8                           ProducerConsumer;   /* For values, see Producer/Consumer above */
+    UINT8                           PinConfig;
+    UINT8                           Sharable;           /* For values, see Interrupt Attributes above */
+    UINT8                           IoRestriction;
+    UINT8                           Triggering;         /* For values, see Interrupt Attributes above */
+    UINT8                           Polarity;           /* For values, see Interrupt Attributes above */
+    UINT16                          DriveStrength;
+    UINT16                          DebounceTimeout;
+    UINT16                          PinTableLength;
+    UINT16                          VendorLength;
+    ACPI_RESOURCE_SOURCE            ResourceSource;
+    UINT16                          *PinTable;
+    UINT8                           *VendorData;
+
+} ACPI_RESOURCE_GPIO;
+
+/* Values for GPIO ConnectionType field above */
+
+#define ACPI_RESOURCE_GPIO_TYPE_INT             0
+#define ACPI_RESOURCE_GPIO_TYPE_IO              1
+
+/* Values for PinConfig field above */
+
+#define ACPI_PIN_CONFIG_DEFAULT                 0
+#define ACPI_PIN_CONFIG_PULLUP                  1
+#define ACPI_PIN_CONFIG_PULLDOWN                2
+#define ACPI_PIN_CONFIG_NOPULL                  3
+
+/* Values for IoRestriction field above */
+
+#define ACPI_IO_RESTRICT_NONE                   0
+#define ACPI_IO_RESTRICT_INPUT                  1
+#define ACPI_IO_RESTRICT_OUTPUT                 2
+#define ACPI_IO_RESTRICT_NONE_PRESERVE          3
+
+
+/* Common structure for I2C, SPI, and UART serial descriptors */
+
+#define ACPI_RESOURCE_SERIAL_COMMON \
+    UINT8                           RevisionId; \
+    UINT8                           Type; \
+    UINT8                           ProducerConsumer;    /* For values, see Producer/Consumer above */\
+    UINT8                           SlaveMode; \
+    UINT8                           TypeRevisionId; \
+    UINT16                          TypeDataLength; \
+    UINT16                          VendorLength; \
+    ACPI_RESOURCE_SOURCE            ResourceSource; \
+    UINT8                           *VendorData;
+
+typedef struct acpi_resource_common_serialbus
+{
+    ACPI_RESOURCE_SERIAL_COMMON
+
+} ACPI_RESOURCE_COMMON_SERIALBUS;
+
+/* Values for the Type field above */
+
+#define ACPI_RESOURCE_SERIAL_TYPE_I2C           1
+#define ACPI_RESOURCE_SERIAL_TYPE_SPI           2
+#define ACPI_RESOURCE_SERIAL_TYPE_UART          3
+
+/* Values for SlaveMode field above */
+
+#define ACPI_CONTROLLER_INITIATED               0
+#define ACPI_DEVICE_INITIATED                   1
+
+
+typedef struct acpi_resource_i2c_serialbus
+{
+    ACPI_RESOURCE_SERIAL_COMMON
+    UINT8                           AccessMode;
+    UINT16                          SlaveAddress;
+    UINT32                          ConnectionSpeed;
+
+} ACPI_RESOURCE_I2C_SERIALBUS;
+
+/* Values for AccessMode field above */
+
+#define ACPI_I2C_7BIT_MODE                      0
+#define ACPI_I2C_10BIT_MODE                     1
+
+
+typedef struct acpi_resource_spi_serialbus
+{
+    ACPI_RESOURCE_SERIAL_COMMON
+    UINT8                           WireMode;
+    UINT8                           DevicePolarity;
+    UINT8                           DataBitLength;
+    UINT8                           ClockPhase;
+    UINT8                           ClockPolarity;
+    UINT16                          DeviceSelection;
+    UINT32                          ConnectionSpeed;
+
+} ACPI_RESOURCE_SPI_SERIALBUS;
+
+/* Values for WireMode field above */
+
+#define ACPI_SPI_4WIRE_MODE                     0
+#define ACPI_SPI_3WIRE_MODE                     1
+
+/* Values for DevicePolarity field above */
+
+#define ACPI_SPI_ACTIVE_LOW                     0
+#define ACPI_SPI_ACTIVE_HIGH                    1
+
+/* Values for ClockPhase field above */
+
+#define ACPI_SPI_FIRST_PHASE                    0
+#define ACPI_SPI_SECOND_PHASE                   1
+
+/* Values for ClockPolarity field above */
+
+#define ACPI_SPI_START_LOW                      0
+#define ACPI_SPI_START_HIGH                     1
+
+
+typedef struct acpi_resource_uart_serialbus
+{
+    ACPI_RESOURCE_SERIAL_COMMON
+    UINT8                           Endian;
+    UINT8                           DataBits;
+    UINT8                           StopBits;
+    UINT8                           FlowControl;
+    UINT8                           Parity;
+    UINT8                           LinesEnabled;
+    UINT16                          RxFifoSize;
+    UINT16                          TxFifoSize;
+    UINT32                          DefaultBaudRate;
+
+} ACPI_RESOURCE_UART_SERIALBUS;
+
+/* Values for Endian field above */
+
+#define ACPI_UART_LITTLE_ENDIAN                 0
+#define ACPI_UART_BIG_ENDIAN                    1
+
+/* Values for DataBits field above */
+
+#define ACPI_UART_5_DATA_BITS                   0
+#define ACPI_UART_6_DATA_BITS                   1
+#define ACPI_UART_7_DATA_BITS                   2
+#define ACPI_UART_8_DATA_BITS                   3
+#define ACPI_UART_9_DATA_BITS                   4
+
+/* Values for StopBits field above */
+
+#define ACPI_UART_NO_STOP_BITS                  0
+#define ACPI_UART_1_STOP_BIT                    1
+#define ACPI_UART_1P5_STOP_BITS                 2
+#define ACPI_UART_2_STOP_BITS                   3
+
+/* Values for FlowControl field above */
+
+#define ACPI_UART_FLOW_CONTROL_NONE             0
+#define ACPI_UART_FLOW_CONTROL_HW               1
+#define ACPI_UART_FLOW_CONTROL_XON_XOFF         2
+
+/* Values for Parity field above */
+
+#define ACPI_UART_PARITY_NONE                   0
+#define ACPI_UART_PARITY_EVEN                   1
+#define ACPI_UART_PARITY_ODD                    2
+#define ACPI_UART_PARITY_MARK                   3
+#define ACPI_UART_PARITY_SPACE                  4
+
+/* Values for LinesEnabled bitfield above */
+
+#define ACPI_UART_CARRIER_DETECT                (1<<2)
+#define ACPI_UART_RING_INDICATOR                (1<<3)
+#define ACPI_UART_DATA_SET_READY                (1<<4)
+#define ACPI_UART_DATA_TERMINAL_READY           (1<<5)
+#define ACPI_UART_CLEAR_TO_SEND                 (1<<6)
+#define ACPI_UART_REQUEST_TO_SEND               (1<<7)
+
 
 /* ACPI_RESOURCE_TYPEs */
 
@@ -405,7 +616,10 @@
 #define ACPI_RESOURCE_TYPE_EXTENDED_ADDRESS64   14  /* ACPI 3.0 */
 #define ACPI_RESOURCE_TYPE_EXTENDED_IRQ         15
 #define ACPI_RESOURCE_TYPE_GENERIC_REGISTER     16
-#define ACPI_RESOURCE_TYPE_MAX                  16
+#define ACPI_RESOURCE_TYPE_GPIO                 17  /* ACPI 5.0 */
+#define ACPI_RESOURCE_TYPE_FIXED_DMA            18  /* ACPI 5.0 */
+#define ACPI_RESOURCE_TYPE_SERIAL_BUS           19  /* ACPI 5.0 */
+#define ACPI_RESOURCE_TYPE_MAX                  19
 
 /* Master union for resource descriptors */
 
@@ -416,6 +630,7 @@
     ACPI_RESOURCE_START_DEPENDENT           StartDpf;
     ACPI_RESOURCE_IO                        Io;
     ACPI_RESOURCE_FIXED_IO                  FixedIo;
+    ACPI_RESOURCE_FIXED_DMA                 FixedDma;
     ACPI_RESOURCE_VENDOR                    Vendor;
     ACPI_RESOURCE_VENDOR_TYPED              VendorTyped;
     ACPI_RESOURCE_END_TAG                   EndTag;
@@ -428,6 +643,11 @@
     ACPI_RESOURCE_EXTENDED_ADDRESS64        ExtAddress64;
     ACPI_RESOURCE_EXTENDED_IRQ              ExtendedIrq;
     ACPI_RESOURCE_GENERIC_REGISTER          GenericReg;
+    ACPI_RESOURCE_GPIO                      Gpio;
+    ACPI_RESOURCE_I2C_SERIALBUS             I2cSerialBus;
+    ACPI_RESOURCE_SPI_SERIALBUS             SpiSerialBus;
+    ACPI_RESOURCE_UART_SERIALBUS            UartSerialBus;
+    ACPI_RESOURCE_COMMON_SERIALBUS          CommonSerialBus;
 
     /* Common fields */
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/include/actbl.h
--- a/head/sys/contrib/dev/acpica/include/actbl.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/include/actbl.h	Tue Dec 06 20:26:16 2011 +0200
@@ -298,6 +298,7 @@
     ACPI_GENERIC_ADDRESS    XPmTimerBlock;      /* 64-bit Extended Power Mgt Timer Ctrl Reg Blk address */
     ACPI_GENERIC_ADDRESS    XGpe0Block;         /* 64-bit Extended General Purpose Event 0 Reg Blk address */
     ACPI_GENERIC_ADDRESS    XGpe1Block;         /* 64-bit Extended General Purpose Event 1 Reg Blk address */
+    ACPI_GENERIC_ADDRESS    SleepRegister;      /* 64-bit address of the Sleep register */
 
 } ACPI_TABLE_FADT;
 
@@ -309,6 +310,7 @@
 #define ACPI_FADT_NO_VGA            (1<<2)      /* 02: [V4] It is not safe to probe for VGA hardware */
 #define ACPI_FADT_NO_MSI            (1<<3)      /* 03: [V4] Message Signaled Interrupts (MSI) must not be enabled */
 #define ACPI_FADT_NO_ASPM           (1<<4)      /* 04: [V4] PCIe ASPM control must not be enabled */
+#define ACPI_FADT_NO_CMOS_RTC       (1<<5)      /* 05: [V5] No CMOS real-time clock present */
 
 /* Masks for FADT flags */
 
@@ -332,6 +334,9 @@
 #define ACPI_FADT_REMOTE_POWER_ON   (1<<17)     /* 17: [V4] System is compatible with remote power on (ACPI 3.0) */
 #define ACPI_FADT_APIC_CLUSTER      (1<<18)     /* 18: [V4] All local APICs must use cluster model (ACPI 3.0) */
 #define ACPI_FADT_APIC_PHYSICAL     (1<<19)     /* 19: [V4] All local xAPICs must use physical dest mode (ACPI 3.0) */
+#define ACPI_FADT_HW_REDUCED        (1<<20)     /* 20: [V5] ACPI hardware is not implemented (ACPI 5.0) */
+#define ACPI_FADT_PREFER_S0_IDLE    (1<<21)     /* 21: [V5] Use advanced idle capabilities (ACPI 5.0) */
+#define ACPI_FADT_USE_SLEEP_REG     (1<<22)     /* 22: [V5] Use the sleep register for sleep (ACPI 5.0) */
 
 
 /* Values for PreferredProfile (Prefered Power Management Profiles) */
@@ -344,7 +349,9 @@
     PM_WORKSTATION          = 3,
     PM_ENTERPRISE_SERVER    = 4,
     PM_SOHO_SERVER          = 5,
-    PM_APPLIANCE_PC         = 6
+    PM_APPLIANCE_PC         = 6,
+    PM_PERFORMANCE_SERVER   = 7,
+    PM_SLATE                = 8
 };
 
 
@@ -392,6 +399,7 @@
  */
 #include <contrib/dev/acpica/include/actbl1.h>
 #include <contrib/dev/acpica/include/actbl2.h>
+#include <contrib/dev/acpica/include/actbl3.h>
 
 /* Macros used to generate offsets to specific table fields */
 
@@ -405,12 +413,15 @@
  * FADT is the bottom line as to what the version really is.
  *
  * For reference, the values below are as follows:
- *     FADT V1  size: 0x74
- *     FADT V2  size: 0x84
- *     FADT V3+ size: 0xF4
+ *     FADT V1  size: 0x074
+ *     FADT V2  size: 0x084
+ *     FADT V3  size: 0x0F4
+ *     FADT V4  size: 0x0F4
+ *     FADT V5  size: 0x100
  */
 #define ACPI_FADT_V1_SIZE       (UINT32) (ACPI_FADT_OFFSET (Flags) + 4)
 #define ACPI_FADT_V2_SIZE       (UINT32) (ACPI_FADT_OFFSET (Reserved4[0]) + 3)
-#define ACPI_FADT_V3_SIZE       (UINT32) (sizeof (ACPI_TABLE_FADT))
+#define ACPI_FADT_V3_SIZE       (UINT32) (ACPI_FADT_OFFSET (SleepRegister))
+#define ACPI_FADT_V5_SIZE       (UINT32) (sizeof (ACPI_TABLE_FADT))
 
 #endif /* __ACTBL_H__ */
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/include/actbl1.h
--- a/head/sys/contrib/dev/acpica/include/actbl1.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/include/actbl1.h	Tue Dec 06 20:26:16 2011 +0200
@@ -252,16 +252,17 @@
 
 enum AcpiEinjActions
 {
-    ACPI_EINJ_BEGIN_OPERATION       = 0,
-    ACPI_EINJ_GET_TRIGGER_TABLE     = 1,
-    ACPI_EINJ_SET_ERROR_TYPE        = 2,
-    ACPI_EINJ_GET_ERROR_TYPE        = 3,
-    ACPI_EINJ_END_OPERATION         = 4,
-    ACPI_EINJ_EXECUTE_OPERATION     = 5,
-    ACPI_EINJ_CHECK_BUSY_STATUS     = 6,
-    ACPI_EINJ_GET_COMMAND_STATUS    = 7,
-    ACPI_EINJ_ACTION_RESERVED       = 8,     /* 8 and greater are reserved */
-    ACPI_EINJ_TRIGGER_ERROR         = 0xFF   /* Except for this value */
+    ACPI_EINJ_BEGIN_OPERATION               = 0,
+    ACPI_EINJ_GET_TRIGGER_TABLE             = 1,
+    ACPI_EINJ_SET_ERROR_TYPE                = 2,
+    ACPI_EINJ_GET_ERROR_TYPE                = 3,
+    ACPI_EINJ_END_OPERATION                 = 4,
+    ACPI_EINJ_EXECUTE_OPERATION             = 5,
+    ACPI_EINJ_CHECK_BUSY_STATUS             = 6,
+    ACPI_EINJ_GET_COMMAND_STATUS            = 7,
+    ACPI_EINJ_SET_ERROR_TYPE_WITH_ADDRESS   = 8,
+    ACPI_EINJ_ACTION_RESERVED               = 9,     /* 9 and greater are reserved */
+    ACPI_EINJ_TRIGGER_ERROR                 = 0xFF   /* Except for this value */
 };
 
 /* Values for Instruction field above */
@@ -273,9 +274,33 @@
     ACPI_EINJ_WRITE_REGISTER        = 2,
     ACPI_EINJ_WRITE_REGISTER_VALUE  = 3,
     ACPI_EINJ_NOOP                  = 4,
-    ACPI_EINJ_INSTRUCTION_RESERVED  = 5     /* 5 and greater are reserved */
+    ACPI_EINJ_FLUSH_CACHELINE       = 5,
+    ACPI_EINJ_INSTRUCTION_RESERVED  = 6     /* 6 and greater are reserved */
 };
 
+typedef struct acpi_einj_error_type_with_addr
+{
+    UINT32                  ErrorType;
+    UINT32                  VendorStructOffset;
+    UINT32                  Flags;
+    UINT32                  ApicId;
+    UINT64                  Address;
+    UINT64                  Range;
+    UINT32                  PcieId;
+
+} ACPI_EINJ_ERROR_TYPE_WITH_ADDR;
+
+typedef struct acpi_einj_vendor
+{
+    UINT32                  Length;
+    UINT32                  PcieId;
+    UINT16                  VendorId;
+    UINT16                  DeviceId;
+    UINT8                   RevisionId;
+    UINT8                   Reserved[3];
+
+} ACPI_EINJ_VENDOR;
+
 
 /* EINJ Trigger Error Action Table */
 
@@ -313,6 +338,7 @@
 #define ACPI_EINJ_PLATFORM_CORRECTABLE      (1<<9)
 #define ACPI_EINJ_PLATFORM_UNCORRECTABLE    (1<<10)
 #define ACPI_EINJ_PLATFORM_FATAL            (1<<11)
+#define ACPI_EINJ_VENDOR_DEFINED            (1<<31)
 
 
 /*******************************************************************************
@@ -731,7 +757,9 @@
     ACPI_MADT_TYPE_INTERRUPT_SOURCE     = 8,
     ACPI_MADT_TYPE_LOCAL_X2APIC         = 9,
     ACPI_MADT_TYPE_LOCAL_X2APIC_NMI     = 10,
-    ACPI_MADT_TYPE_RESERVED             = 11    /* 11 and greater are reserved */
+    ACPI_MADT_TYPE_GENERIC_INTERRUPT    = 11,
+    ACPI_MADT_TYPE_GENERIC_DISTRIBUTOR  = 12,
+    ACPI_MADT_TYPE_RESERVED             = 13    /* 13 and greater are reserved */
 };
 
 
@@ -886,11 +914,42 @@
 } ACPI_MADT_LOCAL_X2APIC_NMI;
 
 
+/* 11: Generic Interrupt (ACPI 5.0) */
+
+typedef struct acpi_madt_generic_interrupt
+{
+    ACPI_SUBTABLE_HEADER    Header;
+    UINT16                  Reserved;           /* Reserved - must be zero */
+    UINT32                  GicId;
+    UINT32                  Uid;
+    UINT32                  Flags;
+    UINT32                  ParkingVersion;
+    UINT32                  PerformanceInterrupt;
+    UINT64                  ParkedAddress;
+    UINT64                  BaseAddress;
+
+} ACPI_MADT_GENERIC_INTERRUPT;
+
+
+/* 12: Generic Distributor (ACPI 5.0) */
+
+typedef struct acpi_madt_generic_distributor
+{
+    ACPI_SUBTABLE_HEADER    Header;
+    UINT16                  Reserved;           /* Reserved - must be zero */
+    UINT32                  GicId;
+    UINT64                  BaseAddress;
+    UINT32                  GlobalIrqBase;
+    UINT32                  Reserved2;          /* Reserved - must be zero */
+
+} ACPI_MADT_GENERIC_DISTRIBUTOR;
+
+
 /*
  * Common flags fields for MADT subtables
  */
 
-/* MADT Local APIC flags (LapicFlags) */
+/* MADT Local APIC flags (LapicFlags) and GIC flags */
 
 #define ACPI_MADT_ENABLED           (1)         /* 00: Processor is usable if set */
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/include/actbl3.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/sys/contrib/dev/acpica/include/actbl3.h	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,650 @@
+/******************************************************************************
+ *
+ * Name: actbl3.h - ACPI Table Definitions
+ *
+ *****************************************************************************/
+
+/*
+ * Copyright (C) 2000 - 2011, Intel Corp.
+ * 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.
+ * 3. Neither the names of the above-listed copyright holders nor the names
+ *    of any contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ * Alternatively, this software may be distributed under the terms of the
+ * GNU General Public License ("GPL") version 2 as published by the Free
+ * Software Foundation.
+ *
+ * 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.
+ */
+
+#ifndef __ACTBL3_H__
+#define __ACTBL3_H__
+
+
+/*******************************************************************************
+ *
+ * Additional ACPI Tables (3)
+ *
+ * These tables are not consumed directly by the ACPICA subsystem, but are
+ * included here to support device drivers and the AML disassembler.
+ *
+ * The tables in this file are fully defined within the ACPI specification.
+ *
+ ******************************************************************************/
+
+
+/*
+ * Values for description table header signatures for tables defined in this
+ * file. Useful because they make it more difficult to inadvertently type in
+ * the wrong signature.
+ */
+#define ACPI_SIG_BGRT           "BGRT"      /* Boot Graphics Resource Table */
+#define ACPI_SIG_DRTM           "DRTM"      /* Dynamic Root of Trust for Measurement table */
+#define ACPI_SIG_FPDT           "FPDT"      /* Firmware Performance Data Table */
+#define ACPI_SIG_GTDT           "GTDT"      /* Generic Timer Description Table */
+#define ACPI_SIG_MPST           "MPST"      /* Memory Power State Table */
+#define ACPI_SIG_PCCT           "PCCT"      /* Platform Communications Channel Table */
+#define ACPI_SIG_PMTT           "PMTT"      /* Platform Memory Topology Table */
+#define ACPI_SIG_RASF           "RASF"      /* RAS Feature table */
+
+#define ACPI_SIG_S3PT           "S3PT"      /* S3 Performance (sub)Table */
+#define ACPI_SIG_PCCS           "PCC"       /* PCC Shared Memory Region */
+
+/* Reserved table signatures */
+
+#define ACPI_SIG_CSRT           "CSRT"      /* Core System Resources Table */
+#define ACPI_SIG_DBG2           "DBG2"      /* Debug Port table 2 */
+#define ACPI_SIG_MATR           "MATR"      /* Memory Address Translation Table */
+#define ACPI_SIG_MSDM           "MSDM"      /* Microsoft Data Management Table */
+#define ACPI_SIG_WPBT           "WPBT"      /* Windows Platform Binary Table */
+
+/*
+ * All tables must be byte-packed to match the ACPI specification, since
+ * the tables are provided by the system BIOS.
+ */
+#pragma pack(1)
+
+/*
+ * Note about bitfields: The UINT8 type is used for bitfields in ACPI tables.
+ * This is the only type that is even remotely portable. Anything else is not
+ * portable, so do not use any other bitfield types.
+ */
+
+
+/*******************************************************************************
+ *
+ * BGRT - Boot Graphics Resource Table (ACPI 5.0)
+ *        Version 1
+ *
+ ******************************************************************************/
+
+typedef struct acpi_table_bgrt
+{
+    ACPI_TABLE_HEADER       Header;             /* Common ACPI table header */
+    UINT16                  Version;
+    UINT8                   Status;
+    UINT8                   ImageType;
+    UINT64                  ImageAddress;
+    UINT32                  ImageOffsetX;
+    UINT32                  ImageOffsetY;
+
+} ACPI_TABLE_BGRT;
+
+
+/*******************************************************************************
+ *
+ * DRTM - Dynamic Root of Trust for Measurement table
+ *
+ ******************************************************************************/
+
+typedef struct acpi_table_drtm
+{
+    ACPI_TABLE_HEADER       Header;             /* Common ACPI table header */
+    UINT64                  EntryBaseAddress;
+    UINT64                  EntryLength;
+    UINT32                  EntryAddress32;
+    UINT64                  EntryAddress64;
+    UINT64                  ExitAddress;
+    UINT64                  LogAreaAddress;
+    UINT32                  LogAreaLength;
+    UINT64                  ArchDependentAddress;
+    UINT32                  Flags;
+
+} ACPI_TABLE_DRTM;
+
+/* 1) Validated Tables List */
+
+typedef struct acpi_drtm_vtl_list
+{
+    UINT32                  ValidatedTableListCount;
+
+} ACPI_DRTM_VTL_LIST;
+
+/* 2) Resources List */
+
+typedef struct acpi_drtm_resource_list
+{
+    UINT32                  ResourceListCount;
+
+} ACPI_DRTM_RESOURCE_LIST;
+
+/* 3) Platform-specific Identifiers List */
+
+typedef struct acpi_drtm_id_list
+{
+    UINT32                  IdListCount;
+
+} ACPI_DRTM_ID_LIST;
+
+
+/*******************************************************************************
+ *
+ * FPDT - Firmware Performance Data Table (ACPI 5.0)
+ *        Version 1
+ *
+ ******************************************************************************/
+
+typedef struct acpi_table_fpdt
+{
+    ACPI_TABLE_HEADER       Header;             /* Common ACPI table header */
+
+} ACPI_TABLE_FPDT;
+
+
+/* FPDT subtable header */
+
+typedef struct acpi_fpdt_header
+{
+    UINT16                  Type;
+    UINT8                   Length;
+    UINT8                   Revision;
+
+} ACPI_FPDT_HEADER;
+
+/* Values for Type field above */
+
+enum AcpiFpdtType
+{
+    ACPI_FPDT_TYPE_BOOT                 = 0,
+    ACPI_FPDT_TYPE_S3PERF               = 1,
+};
+
+
+/*
+ * FPDT subtables
+ */
+
+/* 0: Firmware Basic Boot Performance Record */
+
+typedef struct acpi_fpdt_boot
+{
+    ACPI_FPDT_HEADER        Header;
+    UINT8                   Reserved[4];
+    UINT64                  ResetEnd;
+    UINT64                  LoadStart;
+    UINT64                  StartupStart;
+    UINT64                  ExitServicesEntry;
+    UINT64                  ExitServicesExit;
+
+} ACPI_FPDT_BOOT;
+
+
+/* 1: S3 Performance Table Pointer Record */
+
+typedef struct acpi_fpdt_s3pt_ptr
+{
+    ACPI_FPDT_HEADER        Header;
+    UINT8                   Reserved[4];
+    UINT64                  Address;
+
+} ACPI_FPDT_S3PT_PTR;
+
+
+/*
+ * S3PT - S3 Performance Table. This table is pointed to by the
+ * FPDT S3 Pointer Record above.
+ */
+typedef struct acpi_table_s3pt
+{
+    UINT8                   Signature[4]; /* "S3PT" */
+    UINT32                  Length;
+
+} ACPI_TABLE_S3PT;
+
+
+/*
+ * S3PT Subtables
+ */
+typedef struct acpi_s3pt_header
+{
+    UINT16                  Type;
+    UINT8                   Length;
+    UINT8                   Revision;
+
+} ACPI_S3PT_HEADER;
+
+/* Values for Type field above */
+
+enum AcpiS3ptType
+{
+    ACPI_S3PT_TYPE_RESUME               = 0,
+    ACPI_S3PT_TYPE_SUSPEND              = 1,
+};
+
+typedef struct acpi_s3pt_resume
+{
+    ACPI_S3PT_HEADER        Header;
+    UINT32                  ResumeCount;
+    UINT64                  FullResume;
+    UINT64                  AverageResume;
+
+} ACPI_S3PT_RESUME;
+
+typedef struct acpi_s3pt_suspend
+{
+    ACPI_S3PT_HEADER        Header;
+    UINT64                  SuspendStart;
+    UINT64                  SuspendEnd;
+
+} ACPI_S3PT_SUSPEND;
+
+
+/*******************************************************************************
+ *
+ * GTDT - Generic Timer Description Table (ACPI 5.0)
+ *        Version 1
+ *
+ ******************************************************************************/
+
+typedef struct acpi_table_gtdt
+{
+    ACPI_TABLE_HEADER       Header;             /* Common ACPI table header */
+    UINT64                  Address;
+    UINT32                  Flags;
+    UINT32                  SecurePl1Interrupt;
+    UINT32                  SecurePl1Flags;
+    UINT32                  NonSecurePl1Interrupt;
+    UINT32                  NonSecurePl1Flags;
+    UINT32                  VirtualTimerInterrupt;
+    UINT32                  VirtualTimerFlags;
+    UINT32                  NonSecurePl2Interrupt;
+    UINT32                  NonSecurePl2Flags;
+
+} ACPI_TABLE_GTDT;
+
+/* Values for Flags field above */
+
+#define ACPI_GTDT_MAPPED_BLOCK_PRESENT      1
+
+/* Values for all "TimerFlags" fields above */
+
+#define ACPI_GTDT_INTERRUPT_MODE            1
+#define ACPI_GTDT_INTERRUPT_POLARITY        2
+
+
+/*******************************************************************************
+ *
+ * MPST - Memory Power State Table (ACPI 5.0)
+ *        Version 1
+ *
+ ******************************************************************************/
+
+#define ACPI_MPST_CHANNEL_INFO \
+    UINT16                  Reserved1; \
+    UINT8                   ChannelId; \
+    UINT8                   Reserved2; \
+    UINT16                  PowerNodeCount;
+
+/* Main table */
+
+typedef struct acpi_table_mpst
+{
+    ACPI_TABLE_HEADER       Header;             /* Common ACPI table header */
+    ACPI_MPST_CHANNEL_INFO                      /* Platform Communication Channel */
+
+} ACPI_TABLE_MPST;
+
+
+/* Memory Platform Communication Channel Info */
+
+typedef struct acpi_mpst_channel
+{
+    ACPI_MPST_CHANNEL_INFO                      /* Platform Communication Channel */
+
+} ACPI_MPST_CHANNEL;
+
+
+/* Memory Power Node Structure */
+
+typedef struct acpi_mpst_power_node
+{
+    UINT8                   Flags;
+    UINT8                   Reserved1;
+    UINT16                  NodeId;
+    UINT32                  Length;
+    UINT64                  RangeAddress;
+    UINT64                  RangeLength;
+    UINT8                   NumPowerStates;
+    UINT8                   NumPhysicalComponents;
+    UINT16                  Reserved2;
+
+} ACPI_MPST_POWER_NODE;
+
+/* Values for Flags field above */
+
+#define ACPI_MPST_ENABLED               1
+#define ACPI_MPST_POWER_MANAGED         2
+#define ACPI_MPST_HOT_PLUG_CAPABLE      4
+
+
+/* Memory Power State Structure (follows POWER_NODE above) */
+
+typedef struct acpi_mpst_power_state
+{
+    UINT8                   PowerState;
+    UINT8                   InfoIndex;
+
+} ACPI_MPST_POWER_STATE;
+
+
+/* Physical Component ID Structure (follows POWER_STATE above) */
+
+typedef struct acpi_mpst_component
+{
+    UINT16                  ComponentId;
+
+} ACPI_MPST_COMPONENT;
+
+
+/* Memory Power State Characteristics Structure (follows all POWER_NODEs) */
+
+typedef struct acpi_mpst_data_hdr
+{
+    UINT16                  CharacteristicsCount;
+
+} ACPI_MPST_DATA_HDR;
+
+typedef struct acpi_mpst_power_data
+{
+    UINT8                   Revision;
+    UINT8                   Flags;
+    UINT16                  Reserved1;
+    UINT32                  AveragePower;
+    UINT32                  PowerSaving;
+    UINT64                  ExitLatency;
+    UINT64                  Reserved2;
+
+} ACPI_MPST_POWER_DATA;
+
+/* Values for Flags field above */
+
+#define ACPI_MPST_PRESERVE              1
+#define ACPI_MPST_AUTOENTRY             2
+#define ACPI_MPST_AUTOEXIT              4
+
+
+/* Shared Memory Region (not part of an ACPI table) */
+
+typedef struct acpi_mpst_shared
+{
+    UINT32                  Signature;
+    UINT16                  PccCommand;
+    UINT16                  PccStatus;
+    UINT16                  CommandRegister;
+    UINT16                  StatusRegister;
+    UINT16                  PowerStateId;
+    UINT16                  PowerNodeId;
+    UINT64                  EnergyConsumed;
+    UINT64                  AveragePower;
+
+} ACPI_MPST_SHARED;
+
+
+/*******************************************************************************
+ *
+ * PCCT - Platform Communications Channel Table (ACPI 5.0)
+ *        Version 1
+ *
+ ******************************************************************************/
+
+typedef struct acpi_table_pcct
+{
+    ACPI_TABLE_HEADER       Header;             /* Common ACPI table header */
+    UINT32                  Flags;
+    UINT32                  Latency;
+    UINT32                  Reserved;
+
+} ACPI_TABLE_PCCT;
+
+/* Values for Flags field above */
+
+#define ACPI_PCCT_DOORBELL              1
+
+/*
+ * PCCT subtables
+ */
+
+/* 0: Generic Communications Subspace */
+
+typedef struct acpi_pcct_subspace
+{
+    ACPI_SUBTABLE_HEADER    Header;
+    UINT8                   Reserved[6];
+    UINT64                  BaseAddress;
+    UINT64                  Length;
+    ACPI_GENERIC_ADDRESS    DoorbellRegister;
+    UINT64                  PreserveMask;
+    UINT64                  WriteMask;
+
+} ACPI_PCCT_SUBSPACE;
+
+
+/*
+ * PCC memory structures (not part of the ACPI table)
+ */
+
+/* Shared Memory Region */
+
+typedef struct acpi_pcct_shared_memory
+{
+    UINT32                  Signature;
+    UINT16                  Command;
+    UINT16                  Status;
+
+} ACPI_PCCT_SHARED_MEMORY;
+
+
+/*******************************************************************************
+ *
+ * PMTT - Platform Memory Topology Table (ACPI 5.0)
+ *        Version 1
+ *
+ ******************************************************************************/
+
+typedef struct acpi_table_pmtt
+{
+    ACPI_TABLE_HEADER       Header;             /* Common ACPI table header */
+    UINT32                  Reserved;
+
+} ACPI_TABLE_PMTT;
+
+
+/* Common header for PMTT subtables that follow main table */
+
+typedef struct acpi_pmtt_header
+{
+    UINT8                   Type;
+    UINT8                   Reserved1;
+    UINT16                  Length;
+    UINT16                  Flags;
+    UINT16                  Reserved2;
+
+} ACPI_PMTT_HEADER;
+
+/* Values for Type field above */
+
+#define ACPI_PMTT_TYPE_SOCKET           0
+#define ACPI_PMTT_TYPE_CONTROLLER       1
+#define ACPI_PMTT_TYPE_DIMM             2
+#define ACPI_PMTT_TYPE_RESERVED         3 /* 0x03-0xFF are reserved */
+
+/* Values for Flags field above */
+
+#define ACPI_PMTT_TOP_LEVEL             0x0001
+#define ACPI_PMTT_PHYSICAL              0x0002
+#define ACPI_PMTT_MEMORY_TYPE           0x000C
+
+
+/*
+ * PMTT subtables, correspond to Type in acpi_pmtt_header
+ */
+
+
+/* 0: Socket Structure */
+
+typedef struct acpi_pmtt_socket
+{
+    ACPI_PMTT_HEADER        Header;
+    UINT16                  SocketId;
+    UINT16                  Reserved;
+
+} ACPI_PMTT_SOCKET;
+
+
+/* 1: Memory Controller subtable */
+
+typedef struct acpi_pmtt_controller
+{
+    ACPI_PMTT_HEADER        Header;
+    UINT32                  ReadLatency;
+    UINT32                  WriteLatency;
+    UINT32                  ReadBandwidth;
+    UINT32                  WriteBandwidth;
+    UINT16                  AccessWidth;
+    UINT16                  Alignment;
+    UINT16                  Reserved;
+    UINT16                  DomainCount;
+
+} ACPI_PMTT_CONTROLLER;
+
+/* 1a: Proximity Domain substructure */
+
+typedef struct acpi_pmtt_domain
+{
+    UINT32                  ProximityDomain;
+
+} ACPI_PMTT_DOMAIN;
+
+
+/* 2: Physical Component Identifier (DIMM) */
+
+typedef struct acpi_pmtt_physical_component
+{
+    ACPI_PMTT_HEADER        Header;
+    UINT16                  ComponentId;
+    UINT16                  Reserved;
+    UINT32                  MemorySize;
+    UINT32                  BiosHandle;
+
+} ACPI_PMTT_PHYSICAL_COMPONENT;
+
+
+/*******************************************************************************
+ *
+ * RASF - RAS Feature Table (ACPI 5.0)
+ *        Version 1
+ *
+ ******************************************************************************/
+
+typedef struct acpi_table_rasf
+{
+    ACPI_TABLE_HEADER       Header;             /* Common ACPI table header */
+    UINT8                   ChannelId[12];
+
+} ACPI_TABLE_RASF;
+
+/* RASF Platform Communication Channel Shared Memory Region */
+
+typedef struct acpi_rasf_shared_memory
+{
+    UINT32                  Signature;
+    UINT16                  Command;
+    UINT16                  Status;
+    UINT64                  RequestedAddress;
+    UINT64                  RequestedLength;
+    UINT64                  ActualAddress;
+    UINT64                  ActualLength;
+    UINT16                  Flags;
+    UINT8                   Speed;
+
+} ACPI_RASF_SHARED_MEMORY;
+
+/* Masks for Flags and Speed fields above */
+
+#define ACPI_RASF_SCRUBBER_RUNNING      1
+#define ACPI_RASF_SPEED                 (7<<1)
+
+/* Channel Commands */
+
+enum AcpiRasfCommands
+{
+    ACPI_RASF_GET_RAS_CAPABILITIES      = 1,
+    ACPI_RASF_GET_PATROL_PARAMETERS     = 2,
+    ACPI_RASF_START_PATROL_SCRUBBER     = 3,
+    ACPI_RASF_STOP_PATROL_SCRUBBER      = 4
+};
+
+/* Channel Command flags */
+
+#define ACPI_RASF_GENERATE_SCI          (1<<15)
+
+/* Status values */
+
+enum AcpiRasfStatus
+{
+    ACPI_RASF_SUCCESS                   = 0,
+    ACPI_RASF_NOT_VALID                 = 1,
+    ACPI_RASF_NOT_SUPPORTED             = 2,
+    ACPI_RASF_BUSY                      = 3,
+    ACPI_RASF_FAILED                    = 4,
+    ACPI_RASF_ABORTED                   = 5,
+    ACPI_RASF_INVALID_DATA              = 6
+};
+
+/* Status flags */
+
+#define ACPI_RASF_COMMAND_COMPLETE      (1)
+#define ACPI_RASF_SCI_DOORBELL          (1<<1)
+#define ACPI_RASF_ERROR                 (1<<2)
+#define ACPI_RASF_STATUS                (0x1F<<3)
+
+
+/* Reset to default packing */
+
+#pragma pack()
+
+#endif /* __ACTBL3_H__ */
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/include/actypes.h
--- a/head/sys/contrib/dev/acpica/include/actypes.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/include/actypes.h	Tue Dec 06 20:26:16 2011 +0200
@@ -716,8 +716,10 @@
 #define ACPI_ADR_SPACE_CMOS             (ACPI_ADR_SPACE_TYPE) 5
 #define ACPI_ADR_SPACE_PCI_BAR_TARGET   (ACPI_ADR_SPACE_TYPE) 6
 #define ACPI_ADR_SPACE_IPMI             (ACPI_ADR_SPACE_TYPE) 7
+#define ACPI_ADR_SPACE_GPIO             (ACPI_ADR_SPACE_TYPE) 8
+#define ACPI_ADR_SPACE_GSBUS            (ACPI_ADR_SPACE_TYPE) 9
 
-#define ACPI_NUM_PREDEFINED_REGIONS     8
+#define ACPI_NUM_PREDEFINED_REGIONS     10
 
 /*
  * Special Address Spaces
@@ -1030,6 +1032,17 @@
 
 #define ACPI_DEFAULT_HANDLER            NULL
 
+/* Special Context data for GenericSerialBus/GeneralPurposeIo (ACPI 5.0) */
+
+typedef struct acpi_connection_info
+{
+    UINT8                           *Connection;
+    UINT16                          Length;
+    UINT8                           AccessLength;
+
+} ACPI_CONNECTION_INFO;
+
+
 typedef
 ACPI_STATUS (*ACPI_ADR_SPACE_SETUP) (
     ACPI_HANDLE                     RegionHandle,
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/include/acutils.h
--- a/head/sys/contrib/dev/acpica/include/acutils.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/include/acutils.h	Tue Dec 06 20:26:16 2011 +0200
@@ -46,6 +46,7 @@
 
 
 extern const UINT8                      AcpiGbl_ResourceAmlSizes[];
+extern const UINT8                      AcpiGbl_ResourceAmlSerialBusSizes[];
 
 /* Strings used by the disassembler and debugger resource dump routines */
 
@@ -69,6 +70,22 @@
 extern const char                       *AcpiGbl_TrsDecode[];
 extern const char                       *AcpiGbl_TtpDecode[];
 extern const char                       *AcpiGbl_TypDecode[];
+extern const char                       *AcpiGbl_PpcDecode[];
+extern const char                       *AcpiGbl_IorDecode[];
+extern const char                       *AcpiGbl_DtsDecode[];
+extern const char                       *AcpiGbl_CtDecode[];
+extern const char                       *AcpiGbl_SbtDecode[];
+extern const char                       *AcpiGbl_AmDecode[];
+extern const char                       *AcpiGbl_SmDecode[];
+extern const char                       *AcpiGbl_WmDecode[];
+extern const char                       *AcpiGbl_CphDecode[];
+extern const char                       *AcpiGbl_CpoDecode[];
+extern const char                       *AcpiGbl_DpDecode[];
+extern const char                       *AcpiGbl_EdDecode[];
+extern const char                       *AcpiGbl_BpbDecode[];
+extern const char                       *AcpiGbl_SbDecode[];
+extern const char                       *AcpiGbl_FcDecode[];
+extern const char                       *AcpiGbl_PtDecode[];
 #endif
 
 /* Types for Resource descriptor entries */
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/include/amlcode.h
--- a/head/sys/contrib/dev/acpica/include/amlcode.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/include/amlcode.h	Tue Dec 06 20:26:16 2011 +0200
@@ -191,6 +191,15 @@
 
 
 /*
+ * Opcodes for "Field" operators
+ */
+#define AML_FIELD_OFFSET_OP         (UINT8) 0x00
+#define AML_FIELD_ACCESS_OP         (UINT8) 0x01
+#define AML_FIELD_CONNECTION_OP     (UINT8) 0x02        /* ACPI 5.0 */
+#define AML_FIELD_EXT_ACCESS_OP     (UINT8) 0x03        /* ACPI 5.0 */
+
+
+/*
  * Internal opcodes
  * Use only "Unknown" AML opcodes, don't attempt to use
  * any valid ACPI ASCII values (A-Z, 0-9, '-')
@@ -204,7 +213,8 @@
 #define AML_INT_METHODCALL_OP       (UINT16) 0x0035
 #define AML_INT_RETURN_VALUE_OP     (UINT16) 0x0036
 #define AML_INT_EVAL_SUBTREE_OP     (UINT16) 0x0037
-
+#define AML_INT_CONNECTION_OP       (UINT16) 0x0038
+#define AML_INT_EXTACCESSFIELD_OP   (UINT16) 0x0039
 
 #define ARG_NONE                    0x0
 
@@ -478,13 +488,16 @@
  */
 typedef enum
 {
-    AML_FIELD_ATTRIB_SMB_QUICK      = 0x02,
-    AML_FIELD_ATTRIB_SMB_SEND_RCV   = 0x04,
-    AML_FIELD_ATTRIB_SMB_BYTE       = 0x06,
-    AML_FIELD_ATTRIB_SMB_WORD       = 0x08,
-    AML_FIELD_ATTRIB_SMB_BLOCK      = 0x0A,
-    AML_FIELD_ATTRIB_SMB_WORD_CALL  = 0x0C,
-    AML_FIELD_ATTRIB_SMB_BLOCK_CALL = 0x0D
+    AML_FIELD_ATTRIB_QUICK          = 0x02,
+    AML_FIELD_ATTRIB_SEND_RCV       = 0x04,
+    AML_FIELD_ATTRIB_BYTE           = 0x06,
+    AML_FIELD_ATTRIB_WORD           = 0x08,
+    AML_FIELD_ATTRIB_BLOCK          = 0x0A,
+    AML_FIELD_ATTRIB_MULTIBYTE      = 0x0B,
+    AML_FIELD_ATTRIB_WORD_CALL      = 0x0C,
+    AML_FIELD_ATTRIB_BLOCK_CALL     = 0x0D,
+    AML_FIELD_ATTRIB_RAW_BYTES      = 0x0E,
+    AML_FIELD_ATTRIB_RAW_PROCESS    = 0x0F
 
 } AML_ACCESS_ATTRIBUTE;
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/include/amlresrc.h
--- a/head/sys/contrib/dev/acpica/include/amlresrc.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/include/amlresrc.h	Tue Dec 06 20:26:16 2011 +0200
@@ -59,29 +59,48 @@
 #define ACPI_RESTAG_TYPESPECIFICATTRIBUTES      "_ATT"
 #define ACPI_RESTAG_BASEADDRESS                 "_BAS"
 #define ACPI_RESTAG_BUSMASTER                   "_BM_"  /* Master(1), Slave(0) */
+#define ACPI_RESTAG_DEBOUNCETIME                "_DBT"
 #define ACPI_RESTAG_DECODE                      "_DEC"
+#define ACPI_RESTAG_DEVICEPOLARITY              "_DPL"
 #define ACPI_RESTAG_DMA                         "_DMA"
 #define ACPI_RESTAG_DMATYPE                     "_TYP"  /* Compatible(0), A(1), B(2), F(3) */
+#define ACPI_RESTAG_DRIVESTRENGTH               "_DRS"
+#define ACPI_RESTAG_ENDIANNESS                  "_END"
+#define ACPI_RESTAG_FLOWCONTROL                 "_FLC"
 #define ACPI_RESTAG_GRANULARITY                 "_GRA"
 #define ACPI_RESTAG_INTERRUPT                   "_INT"
 #define ACPI_RESTAG_INTERRUPTLEVEL              "_LL_"  /* ActiveLo(1), ActiveHi(0) */
 #define ACPI_RESTAG_INTERRUPTSHARE              "_SHR"  /* Shareable(1), NoShare(0) */
 #define ACPI_RESTAG_INTERRUPTTYPE               "_HE_"  /* Edge(1), Level(0) */
+#define ACPI_RESTAG_IORESTRICTION               "_IOR"
 #define ACPI_RESTAG_LENGTH                      "_LEN"
+#define ACPI_RESTAG_LINE                        "_LIN"
 #define ACPI_RESTAG_MEMATTRIBUTES               "_MTP"  /* Memory(0), Reserved(1), ACPI(2), NVS(3) */
 #define ACPI_RESTAG_MEMTYPE                     "_MEM"  /* NonCache(0), Cacheable(1) Cache+combine(2), Cache+prefetch(3) */
 #define ACPI_RESTAG_MAXADDR                     "_MAX"
 #define ACPI_RESTAG_MINADDR                     "_MIN"
 #define ACPI_RESTAG_MAXTYPE                     "_MAF"
 #define ACPI_RESTAG_MINTYPE                     "_MIF"
+#define ACPI_RESTAG_MODE                        "_MOD"
+#define ACPI_RESTAG_PARITY                      "_PAR"
+#define ACPI_RESTAG_PHASE                       "_PHA"
+#define ACPI_RESTAG_PIN                         "_PIN"
+#define ACPI_RESTAG_PINCONFIG                   "_PPI"
+#define ACPI_RESTAG_POLARITY                    "_POL"
 #define ACPI_RESTAG_REGISTERBITOFFSET           "_RBO"
 #define ACPI_RESTAG_REGISTERBITWIDTH            "_RBW"
 #define ACPI_RESTAG_RANGETYPE                   "_RNG"
 #define ACPI_RESTAG_READWRITETYPE               "_RW_"  /* ReadOnly(0), Writeable (1) */
+#define ACPI_RESTAG_LENGTH_RX                   "_RXL"
+#define ACPI_RESTAG_LENGTH_TX                   "_TXL"
+#define ACPI_RESTAG_SLAVEMODE                   "_SLV"
+#define ACPI_RESTAG_SPEED                       "_SPE"
+#define ACPI_RESTAG_STOPBITS                    "_STB"
 #define ACPI_RESTAG_TRANSLATION                 "_TRA"
 #define ACPI_RESTAG_TRANSTYPE                   "_TRS"  /* Sparse(1), Dense(0) */
 #define ACPI_RESTAG_TYPE                        "_TTP"  /* Translation(1), Static (0) */
 #define ACPI_RESTAG_XFERTYPE                    "_SIZ"  /* 8(0), 8And16(1), 16(2) */
+#define ACPI_RESTAG_VENDORDATA                  "_VEN"
 
 
 /* Default sizes for "small" resource descriptors */
@@ -92,6 +111,7 @@
 #define ASL_RDESC_END_DEPEND_SIZE               0x00
 #define ASL_RDESC_IO_SIZE                       0x07
 #define ASL_RDESC_FIXED_IO_SIZE                 0x03
+#define ASL_RDESC_FIXED_DMA_SIZE                0x05
 #define ASL_RDESC_END_TAG_SIZE                  0x01
 
 
@@ -214,6 +234,16 @@
 } AML_RESOURCE_END_TAG;
 
 
+typedef struct aml_resource_fixed_dma
+{
+    AML_RESOURCE_SMALL_HEADER_COMMON
+    UINT16                          RequestLines;
+    UINT16                          Channels;
+    UINT8                           Width;
+
+} AML_RESOURCE_FIXED_DMA;
+
+
 /*
  * LARGE descriptors
  */
@@ -368,6 +398,130 @@
 
 } AML_RESOURCE_GENERIC_REGISTER;
 
+
+/* Common descriptor for GpioInt and GpioIo (ACPI 5.0) */
+
+typedef struct aml_resource_gpio
+{
+    AML_RESOURCE_LARGE_HEADER_COMMON
+    UINT8                           RevisionId;
+    UINT8                           ConnectionType;
+    UINT16                          Flags;
+    UINT16                          IntFlags;
+    UINT8                           PinConfig;
+    UINT16                          DriveStrength;
+    UINT16                          DebounceTimeout;
+    UINT16                          PinTableOffset;
+    UINT8                           ResSourceIndex;
+    UINT16                          ResSourceOffset;
+    UINT16                          VendorOffset;
+    UINT16                          VendorLength;
+    /*
+     * Optional fields follow immediately:
+     * 1) PIN list (Words)
+     * 2) Resource Source String
+     * 3) Vendor Data bytes
+     */
+
+} AML_RESOURCE_GPIO;
+
+#define AML_RESOURCE_GPIO_REVISION              1       /* ACPI 5.0 */
+
+/* Values for ConnectionType above */
+
+#define AML_RESOURCE_GPIO_TYPE_INT              0
+#define AML_RESOURCE_GPIO_TYPE_IO               1
+#define AML_RESOURCE_MAX_GPIOTYPE               1
+
+
+/* Common preamble for all serial descriptors (ACPI 5.0) */
+
+#define AML_RESOURCE_SERIAL_COMMON \
+    UINT8                           RevisionId; \
+    UINT8                           ResSourceIndex; \
+    UINT8                           Type; \
+    UINT8                           Flags; \
+    UINT16                          TypeSpecificFlags; \
+    UINT8                           TypeRevisionId; \
+    UINT16                          TypeDataLength; \
+
+/* Values for the type field above */
+
+#define AML_RESOURCE_I2C_SERIALBUSTYPE          1
+#define AML_RESOURCE_SPI_SERIALBUSTYPE          2
+#define AML_RESOURCE_UART_SERIALBUSTYPE         3
+#define AML_RESOURCE_MAX_SERIALBUSTYPE          3
+#define AML_RESOURCE_VENDOR_SERIALBUSTYPE       192 /* Vendor defined is 0xC0-0xFF (NOT SUPPORTED) */
+
+typedef struct aml_resource_common_serialbus
+{
+    AML_RESOURCE_LARGE_HEADER_COMMON
+    AML_RESOURCE_SERIAL_COMMON
+
+} AML_RESOURCE_COMMON_SERIALBUS;
+
+typedef struct aml_resource_i2c_serialbus
+{
+    AML_RESOURCE_LARGE_HEADER_COMMON
+    AML_RESOURCE_SERIAL_COMMON
+    UINT32                          ConnectionSpeed;
+    UINT16                          SlaveAddress;
+    /*
+     * Optional fields follow immediately:
+     * 1) Vendor Data bytes
+     * 2) Resource Source String
+     */
+
+} AML_RESOURCE_I2C_SERIALBUS;
+
+#define AML_RESOURCE_I2C_REVISION               1       /* ACPI 5.0 */
+#define AML_RESOURCE_I2C_TYPE_REVISION          1       /* ACPI 5.0 */
+#define AML_RESOURCE_I2C_MIN_DATA_LEN           6
+
+typedef struct aml_resource_spi_serialbus
+{
+    AML_RESOURCE_LARGE_HEADER_COMMON
+    AML_RESOURCE_SERIAL_COMMON
+    UINT32                          ConnectionSpeed;
+    UINT8                           DataBitLength;
+    UINT8                           ClockPhase;
+    UINT8                           ClockPolarity;
+    UINT16                          DeviceSelection;
+    /*
+     * Optional fields follow immediately:
+     * 1) Vendor Data bytes
+     * 2) Resource Source String
+     */
+
+} AML_RESOURCE_SPI_SERIALBUS;
+
+#define AML_RESOURCE_SPI_REVISION               1       /* ACPI 5.0 */
+#define AML_RESOURCE_SPI_TYPE_REVISION          1       /* ACPI 5.0 */
+#define AML_RESOURCE_SPI_MIN_DATA_LEN           9
+
+
+typedef struct aml_resource_uart_serialbus
+{
+    AML_RESOURCE_LARGE_HEADER_COMMON
+    AML_RESOURCE_SERIAL_COMMON
+    UINT32                          DefaultBaudRate;
+    UINT16                          RxFifoSize;
+    UINT16                          TxFifoSize;
+    UINT8                           Parity;
+    UINT8                           LinesEnabled;
+    /*
+     * Optional fields follow immediately:
+     * 1) Vendor Data bytes
+     * 2) Resource Source String
+     */
+
+} AML_RESOURCE_UART_SERIALBUS;
+
+#define AML_RESOURCE_UART_REVISION              1       /* ACPI 5.0 */
+#define AML_RESOURCE_UART_TYPE_REVISION         1       /* ACPI 5.0 */
+#define AML_RESOURCE_UART_MIN_DATA_LEN          10
+
+
 /* restore default alignment */
 
 #pragma pack()
@@ -390,6 +544,7 @@
     AML_RESOURCE_END_DEPENDENT              EndDpf;
     AML_RESOURCE_IO                         Io;
     AML_RESOURCE_FIXED_IO                   FixedIo;
+    AML_RESOURCE_FIXED_DMA                  FixedDma;
     AML_RESOURCE_VENDOR_SMALL               VendorSmall;
     AML_RESOURCE_END_TAG                    EndTag;
 
@@ -405,6 +560,11 @@
     AML_RESOURCE_ADDRESS64                  Address64;
     AML_RESOURCE_EXTENDED_ADDRESS64         ExtAddress64;
     AML_RESOURCE_EXTENDED_IRQ               ExtendedIrq;
+    AML_RESOURCE_GPIO                       Gpio;
+    AML_RESOURCE_I2C_SERIALBUS              I2cSerialBus;
+    AML_RESOURCE_SPI_SERIALBUS              SpiSerialBus;
+    AML_RESOURCE_UART_SERIALBUS             UartSerialBus;
+    AML_RESOURCE_COMMON_SERIALBUS           CommonSerialBus;
 
     /* Utility overlays */
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/include/platform/acenv.h
--- a/head/sys/contrib/dev/acpica/include/platform/acenv.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/include/platform/acenv.h	Tue Dec 06 20:26:16 2011 +0200
@@ -79,7 +79,7 @@
 #define ACPI_SINGLE_THREADED
 #endif
 
-/* AcpiExec and AcpiBin configuration */
+/* AcpiExec configuration. Multithreaded with full AML debugger */
 
 #ifdef ACPI_EXEC_APP
 #define ACPI_APPLICATION
@@ -88,7 +88,27 @@
 #define ACPI_DBG_TRACK_ALLOCATIONS
 #endif
 
-#ifdef ACPI_BIN_APP
+/* AcpiNames configuration. Single threaded with debugger output enabled. */
+
+#ifdef ACPI_NAMES_APP
+#define ACPI_DEBUGGER
+#define ACPI_APPLICATION
+#define ACPI_SINGLE_THREADED
+#endif
+
+/*
+ * AcpiBin/AcpiHelp/AcpiSrc configuration. All single threaded, with
+ * no debug output.
+ */
+#if (defined ACPI_BIN_APP)   || \
+    (defined ACPI_SRC_APP)   || \
+    (defined ACPI_XTRACT_APP)
+#define ACPI_APPLICATION
+#define ACPI_SINGLE_THREADED
+#endif
+
+#ifdef ACPI_HELP_APP
+#define ACPI_DEBUG_OUTPUT
 #define ACPI_APPLICATION
 #define ACPI_SINGLE_THREADED
 #endif
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/namespace/nspredef.c
--- a/head/sys/contrib/dev/acpica/namespace/nspredef.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/namespace/nspredef.c	Tue Dec 06 20:26:16 2011 +0200
@@ -216,14 +216,20 @@
     }
 
     /*
-     * 1) We have a return value, but if one wasn't expected, just exit, this is
-     * not a problem. For example, if the "Implicit Return" feature is
-     * enabled, methods will always return a value.
+     * Return value validation and possible repair.
      *
-     * 2) If the return value can be of any type, then we cannot perform any
-     * validation, exit.
+     * 1) Don't perform return value validation/repair if this feature
+     * has been disabled via a global option.
+     *
+     * 2) We have a return value, but if one wasn't expected, just exit,
+     * this is not a problem. For example, if the "Implicit Return"
+     * feature is enabled, methods will always return a value.
+     *
+     * 3) If the return value can be of any type, then we cannot perform
+     * any validation, just exit.
      */
-    if ((!Predefined->Info.ExpectedBtypes) ||
+    if (AcpiGbl_DisableAutoRepair ||
+        (!Predefined->Info.ExpectedBtypes) ||
         (Predefined->Info.ExpectedBtypes == ACPI_RTYPE_ALL))
     {
         goto Cleanup;
@@ -237,6 +243,7 @@
         goto Cleanup;
     }
     Data->Predefined = Predefined;
+    Data->Node = Node;
     Data->NodeFlags = Node->Flags;
     Data->Pathname = Pathname;
 
@@ -658,6 +665,7 @@
     case ACPI_PTYPE2_FIXED:
     case ACPI_PTYPE2_MIN:
     case ACPI_PTYPE2_COUNT:
+    case ACPI_PTYPE2_FIX_VAR:
 
         /*
          * These types all return a single Package that consists of a
@@ -800,6 +808,29 @@
             break;
 
 
+        case ACPI_PTYPE2_FIX_VAR:
+            /*
+             * Each subpackage has a fixed number of elements and an
+             * optional element
+             */
+            ExpectedCount = Package->RetInfo.Count1 + Package->RetInfo.Count2;
+            if (SubPackage->Package.Count < ExpectedCount)
+            {
+                goto PackageTooSmall;
+            }
+
+            Status = AcpiNsCheckPackageElements (Data, SubElements,
+                        Package->RetInfo.ObjectType1,
+                        Package->RetInfo.Count1,
+                        Package->RetInfo.ObjectType2,
+                        SubPackage->Package.Count - Package->RetInfo.Count1, 0);
+            if (ACPI_FAILURE (Status))
+            {
+                return (Status);
+            }
+            break;
+
+
         case ACPI_PTYPE2_FIXED:
 
             /* Each sub-package has a fixed length */
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/namespace/nsrepair.c
--- a/head/sys/contrib/dev/acpica/namespace/nsrepair.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/namespace/nsrepair.c	Tue Dec 06 20:26:16 2011 +0200
@@ -696,6 +696,7 @@
     case ACPI_PTYPE2_FIXED:
     case ACPI_PTYPE2_MIN:
     case ACPI_PTYPE2_REV_FIXED:
+    case ACPI_PTYPE2_FIX_VAR:
         break;
 
     default:
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/namespace/nsrepair2.c
--- a/head/sys/contrib/dev/acpica/namespace/nsrepair2.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/namespace/nsrepair2.c	Tue Dec 06 20:26:16 2011 +0200
@@ -516,11 +516,12 @@
     }
 
     /*
-     * Copy and uppercase the string. From the ACPI specification:
+     * Copy and uppercase the string. From the ACPI 5.0 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.
+     * "NNNN####" where N is an uppercase letter or decimal digit, and
+     * # is a hex digit.
      */
     for (Dest = NewString->String.Pointer; *Source; Dest++, Source++)
     {
@@ -555,8 +556,23 @@
 {
     ACPI_OPERAND_OBJECT     *ReturnObject = *ReturnObjectPtr;
     ACPI_STATUS             Status;
+    ACPI_NAMESPACE_NODE     *Node;
 
 
+    /*
+     * We can only sort the _TSS return package if there is no _PSS in the
+     * same scope. This is because if _PSS is present, the ACPI specification
+     * dictates that the _TSS Power Dissipation field is to be ignored, and
+     * therefore some BIOSs leave garbage values in the _TSS Power field(s).
+     * In this case, it is best to just return the _TSS package as-is.
+     * (May, 2011)
+     */
+    Status = AcpiNsGetNode (Data->Node, "^_PSS", ACPI_NS_NO_UPSEARCH, &Node);
+    if (ACPI_SUCCESS (Status))
+    {
+        return (AE_OK);
+    }
+
     Status = AcpiNsCheckSortedList (Data, ReturnObject, 5, 1,
                 ACPI_SORT_DESCENDING, "PowerDissipation");
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/os_specific/service_layers/osunixxf.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/sys/contrib/dev/acpica/os_specific/service_layers/osunixxf.c	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,1214 @@
+/******************************************************************************
+ *
+ * Module Name: osunixxf - UNIX OSL interfaces
+ *
+ *****************************************************************************/
+
+/*
+ * Copyright (C) 2000 - 2011, Intel Corp.
+ * 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.
+ * 3. Neither the names of the above-listed copyright holders nor the names
+ *    of any contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ * Alternatively, this software may be distributed under the terms of the
+ * GNU General Public License ("GPL") version 2 as published by the Free
+ * Software Foundation.
+ *
+ * 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.
+ */
+
+
+/*
+ * These interfaces are required in order to compile the ASL compiler and the
+ * various ACPICA tools under Linux or other Unix-like system.
+ *
+ * Note: Use #define __APPLE__ for OS X generation.
+ */
+#include <contrib/dev/acpica/include/acpi.h>
+#include <contrib/dev/acpica/include/accommon.h>
+#include <contrib/dev/acpica/include/amlcode.h>
+#include <contrib/dev/acpica/include/acparser.h>
+#include <contrib/dev/acpica/include/acdebug.h>
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdarg.h>
+#include <unistd.h>
+#include <sys/time.h>
+#include <semaphore.h>
+#include <pthread.h>
+#include <errno.h>
+
+#define _COMPONENT          ACPI_OS_SERVICES
+        ACPI_MODULE_NAME    ("osunixxf")
+
+
+extern FILE                    *AcpiGbl_DebugFile;
+FILE                           *AcpiGbl_OutputFile;
+
+
+/* Upcalls to AcpiExec */
+
+ACPI_PHYSICAL_ADDRESS
+AeLocalGetRootPointer (
+    void);
+
+void
+AeTableOverride (
+    ACPI_TABLE_HEADER       *ExistingTable,
+    ACPI_TABLE_HEADER       **NewTable);
+
+typedef void* (*PTHREAD_CALLBACK) (void *);
+
+/* Apple-specific */
+
+#ifdef __APPLE__
+#define sem_destroy         sem_close
+#endif
+
+
+/******************************************************************************
+ *
+ * FUNCTION:    AcpiOsInitialize, AcpiOsTerminate
+ *
+ * PARAMETERS:  None
+ *
+ * RETURN:      Status
+ *
+ * DESCRIPTION: Init and terminate. Nothing to do.
+ *
+ *****************************************************************************/
+
+ACPI_STATUS
+AcpiOsInitialize (
+    void)
+{
+
+    AcpiGbl_OutputFile = stdout;
+    return (AE_OK);
+}
+
+
+ACPI_STATUS
+AcpiOsTerminate (
+    void)
+{
+
+    return (AE_OK);
+}
+
+
+/******************************************************************************
+ *
+ * FUNCTION:    AcpiOsGetRootPointer
+ *
+ * PARAMETERS:  None
+ *
+ * RETURN:      RSDP physical address
+ *
+ * DESCRIPTION: Gets the ACPI root pointer (RSDP)
+ *
+ *****************************************************************************/
+
+ACPI_PHYSICAL_ADDRESS
+AcpiOsGetRootPointer (
+    void)
+{
+
+    return (AeLocalGetRootPointer ());
+}
+
+
+/******************************************************************************
+ *
+ * FUNCTION:    AcpiOsPredefinedOverride
+ *
+ * PARAMETERS:  InitVal             - Initial value of the predefined object
+ *              NewVal              - The new value for the object
+ *
+ * RETURN:      Status, pointer to value. Null pointer returned if not
+ *              overriding.
+ *
+ * DESCRIPTION: Allow the OS to override predefined names
+ *
+ *****************************************************************************/
+
+ACPI_STATUS
+AcpiOsPredefinedOverride (
+    const ACPI_PREDEFINED_NAMES *InitVal,
+    ACPI_STRING                 *NewVal)
+{
+
+    if (!InitVal || !NewVal)
+    {
+        return (AE_BAD_PARAMETER);
+    }
+
+    *NewVal = NULL;
+    return (AE_OK);
+}
+
+
+/******************************************************************************
+ *
+ * FUNCTION:    AcpiOsTableOverride
+ *
+ * PARAMETERS:  ExistingTable       - Header of current table (probably
+ *                                    firmware)
+ *              NewTable            - Where an entire new table is returned.
+ *
+ * RETURN:      Status, pointer to new table. Null pointer returned if no
+ *              table is available to override
+ *
+ * DESCRIPTION: Return a different version of a table if one is available
+ *
+ *****************************************************************************/
+
+ACPI_STATUS
+AcpiOsTableOverride (
+    ACPI_TABLE_HEADER       *ExistingTable,
+    ACPI_TABLE_HEADER       **NewTable)
+{
+
+    if (!ExistingTable || !NewTable)
+    {
+        return (AE_BAD_PARAMETER);
+    }
+
+    *NewTable = NULL;
+
+#ifdef ACPI_EXEC_APP
+
+    AeTableOverride (ExistingTable, NewTable);
+    return (AE_OK);
+#else
+
+    return (AE_NO_ACPI_TABLES);
+#endif
+}
+
+
+/******************************************************************************
+ *
+ * FUNCTION:    AcpiOsRedirectOutput
+ *
+ * PARAMETERS:  Destination         - An open file handle/pointer
+ *
+ * RETURN:      None
+ *
+ * DESCRIPTION: Causes redirect of AcpiOsPrintf and AcpiOsVprintf
+ *
+ *****************************************************************************/
+
+void
+AcpiOsRedirectOutput (
+    void                    *Destination)
+{
+
+    AcpiGbl_OutputFile = Destination;
+}
+
+
+/******************************************************************************
+ *
+ * FUNCTION:    AcpiOsPrintf
+ *
+ * PARAMETERS:  fmt, ...            - Standard printf format
+ *
+ * RETURN:      None
+ *
+ * DESCRIPTION: Formatted output
+ *
+ *****************************************************************************/
+
+void ACPI_INTERNAL_VAR_XFACE
+AcpiOsPrintf (
+    const char              *Fmt,
+    ...)
+{
+    va_list                 Args;
+
+
+    va_start (Args, Fmt);
+    AcpiOsVprintf (Fmt, Args);
+    va_end (Args);
+}
+
+
+/******************************************************************************
+ *
+ * FUNCTION:    AcpiOsVprintf
+ *
+ * PARAMETERS:  fmt                 - Standard printf format
+ *              args                - Argument list
+ *
+ * RETURN:      None
+ *
+ * DESCRIPTION: Formatted output with argument list pointer
+ *
+ *****************************************************************************/
+
+void
+AcpiOsVprintf (
+    const char              *Fmt,
+    va_list                 Args)
+{
+    UINT8                   Flags;
+
+
+    Flags = AcpiGbl_DbOutputFlags;
+    if (Flags & ACPI_DB_REDIRECTABLE_OUTPUT)
+    {
+        /* Output is directable to either a file (if open) or the console */
+
+        if (AcpiGbl_DebugFile)
+        {
+            /* Output file is open, send the output there */
+
+            vfprintf (AcpiGbl_DebugFile, Fmt, Args);
+        }
+        else
+        {
+            /* No redirection, send output to console (once only!) */
+
+            Flags |= ACPI_DB_CONSOLE_OUTPUT;
+        }
+    }
+
+    if (Flags & ACPI_DB_CONSOLE_OUTPUT)
+    {
+        vfprintf (AcpiGbl_OutputFile, Fmt, Args);
+    }
+}
+
+
+/******************************************************************************
+ *
+ * FUNCTION:    AcpiOsGetLine
+ *
+ * PARAMETERS:  Buffer              - Where to return the command line
+ *              BufferLength        - Maximum length of Buffer
+ *              BytesRead           - Where the actual byte count is returned
+ *
+ * RETURN:      Status and actual bytes read
+ *
+ * DESCRIPTION: Formatted input with argument list pointer
+ *
+ *****************************************************************************/
+
+ACPI_STATUS
+AcpiOsGetLine (
+    char                    *Buffer,
+    UINT32                  BufferLength,
+    UINT32                  *BytesRead)
+{
+    UINT8                   Temp;
+    UINT32                  i;
+
+
+    for (i = 0; ; i++)
+    {
+        if (i >= BufferLength)
+        {
+            return (AE_BUFFER_OVERFLOW);
+        }
+
+        scanf ("%1c", &Temp);
+        if (!Temp || Temp == '\n')
+        {
+            break;
+        }
+
+        Buffer [i] = Temp;
+    }
+
+    /* Null terminate the buffer */
+
+    Buffer [i] = 0;
+
+    /* Return the number of bytes in the string */
+
+    if (BytesRead)
+    {
+        *BytesRead = i;
+    }
+    return (AE_OK);
+}
+
+
+/******************************************************************************
+ *
+ * FUNCTION:    AcpiOsMapMemory
+ *
+ * PARAMETERS:  where               - Physical address of memory to be mapped
+ *              length              - How much memory to map
+ *
+ * RETURN:      Pointer to mapped memory. Null on error.
+ *
+ * DESCRIPTION: Map physical memory into caller's address space
+ *
+ *****************************************************************************/
+
+void *
+AcpiOsMapMemory (
+    ACPI_PHYSICAL_ADDRESS   where,
+    ACPI_SIZE               length)
+{
+
+    return (ACPI_TO_POINTER ((ACPI_SIZE) where));
+}
+
+
+/******************************************************************************
+ *
+ * FUNCTION:    AcpiOsUnmapMemory
+ *
+ * PARAMETERS:  where               - Logical address of memory to be unmapped
+ *              length              - How much memory to unmap
+ *
+ * RETURN:      None.
+ *
+ * DESCRIPTION: Delete a previously created mapping. Where and Length must
+ *              correspond to a previous mapping exactly.
+ *
+ *****************************************************************************/
+
+void
+AcpiOsUnmapMemory (
+    void                    *where,
+    ACPI_SIZE               length)
+{
+
+    return;
+}
+
+
+/******************************************************************************
+ *
+ * FUNCTION:    AcpiOsAllocate
+ *
+ * PARAMETERS:  Size                - Amount to allocate, in bytes
+ *
+ * RETURN:      Pointer to the new allocation. Null on error.
+ *
+ * DESCRIPTION: Allocate memory. Algorithm is dependent on the OS.
+ *
+ *****************************************************************************/
+
+void *
+AcpiOsAllocate (
+    ACPI_SIZE               size)
+{
+    void                    *Mem;
+
+
+    Mem = (void *) malloc ((size_t) size);
+    return (Mem);
+}
+
+
+/******************************************************************************
+ *
+ * FUNCTION:    AcpiOsFree
+ *
+ * PARAMETERS:  mem                 - Pointer to previously allocated memory
+ *
+ * RETURN:      None.
+ *
+ * DESCRIPTION: Free memory allocated via AcpiOsAllocate
+ *
+ *****************************************************************************/
+
+void
+AcpiOsFree (
+    void                    *mem)
+{
+
+    free (mem);
+}
+
+
+#ifdef ACPI_SINGLE_THREADED
+/******************************************************************************
+ *
+ * FUNCTION:    Semaphore stub functions
+ *
+ * DESCRIPTION: Stub functions used for single-thread applications that do
+ *              not require semaphore synchronization. Full implementations
+ *              of these functions appear after the stubs.
+ *
+ *****************************************************************************/
+
+ACPI_STATUS
+AcpiOsCreateSemaphore (
+    UINT32              MaxUnits,
+    UINT32              InitialUnits,
+    ACPI_HANDLE         *OutHandle)
+{
+    *OutHandle = (ACPI_HANDLE) 1;
+    return (AE_OK);
+}
+
+ACPI_STATUS
+AcpiOsDeleteSemaphore (
+    ACPI_HANDLE         Handle)
+{
+    return (AE_OK);
+}
+
+ACPI_STATUS
+AcpiOsWaitSemaphore (
+    ACPI_HANDLE         Handle,
+    UINT32              Units,
+    UINT16              Timeout)
+{
+    return (AE_OK);
+}
+
+ACPI_STATUS
+AcpiOsSignalSemaphore (
+    ACPI_HANDLE         Handle,
+    UINT32              Units)
+{
+    return (AE_OK);
+}
+
+#else
+/******************************************************************************
+ *
+ * FUNCTION:    AcpiOsCreateSemaphore
+ *
+ * PARAMETERS:  InitialUnits        - Units to be assigned to the new semaphore
+ *              OutHandle           - Where a handle will be returned
+ *
+ * RETURN:      Status
+ *
+ * DESCRIPTION: Create an OS semaphore
+ *
+ *****************************************************************************/
+
+ACPI_STATUS
+AcpiOsCreateSemaphore (
+    UINT32              MaxUnits,
+    UINT32              InitialUnits,
+    ACPI_HANDLE         *OutHandle)
+{
+    sem_t               *Sem;
+
+
+    if (!OutHandle)
+    {
+        return (AE_BAD_PARAMETER);
+    }
+
+#ifdef __APPLE__
+    {
+        char            *SemaphoreName = tmpnam (NULL);
+
+        Sem = sem_open (SemaphoreName, O_EXCL|O_CREAT, 0755, InitialUnits);
+        if (!Sem)
+        {
+            return (AE_NO_MEMORY);
+        }
+        sem_unlink (SemaphoreName); /* This just deletes the name */
+    }
+
+#else
+    Sem = AcpiOsAllocate (sizeof (sem_t));
+    if (!Sem)
+    {
+        return (AE_NO_MEMORY);
+    }
+
+    if (sem_init (Sem, 0, InitialUnits) == -1)
+    {
+        AcpiOsFree (Sem);
+        return (AE_BAD_PARAMETER);
+    }
+#endif
+
+    *OutHandle = (ACPI_HANDLE) Sem;
+    return (AE_OK);
+}
+
+
+/******************************************************************************
+ *
+ * FUNCTION:    AcpiOsDeleteSemaphore
+ *
+ * PARAMETERS:  Handle              - Handle returned by AcpiOsCreateSemaphore
+ *
+ * RETURN:      Status
+ *
+ * DESCRIPTION: Delete an OS semaphore
+ *
+ *****************************************************************************/
+
+ACPI_STATUS
+AcpiOsDeleteSemaphore (
+    ACPI_HANDLE         Handle)
+{
+    sem_t               *Sem = (sem_t *) Handle;
+
+
+    if (!Sem)
+    {
+        return (AE_BAD_PARAMETER);
+    }
+
+    if (sem_destroy (Sem) == -1)
+    {
+        return (AE_BAD_PARAMETER);
+    }
+
+    return (AE_OK);
+}
+
+
+/******************************************************************************
+ *
+ * FUNCTION:    AcpiOsWaitSemaphore
+ *
+ * PARAMETERS:  Handle              - Handle returned by AcpiOsCreateSemaphore
+ *              Units               - How many units to wait for
+ *              Timeout             - How long to wait
+ *
+ * RETURN:      Status
+ *
+ * DESCRIPTION: Wait for units
+ *
+ *****************************************************************************/
+
+ACPI_STATUS
+AcpiOsWaitSemaphore (
+    ACPI_HANDLE         Handle,
+    UINT32              Units,
+    UINT16              Timeout)
+{
+    ACPI_STATUS         Status = AE_OK;
+    sem_t               *Sem = (sem_t *) Handle;
+    struct timespec     T;
+
+
+    if (!Sem)
+    {
+        return (AE_BAD_PARAMETER);
+    }
+
+    switch (Timeout)
+    {
+    /*
+     * No Wait:
+     * --------
+     * A zero timeout value indicates that we shouldn't wait - just
+     * acquire the semaphore if available otherwise return AE_TIME
+     * (a.k.a. 'would block').
+     */
+    case 0:
+
+        if (sem_trywait(Sem) == -1)
+        {
+            Status = (AE_TIME);
+        }
+        break;
+
+    /* Wait Indefinitely */
+
+    case ACPI_WAIT_FOREVER:
+
+        if (sem_wait (Sem))
+        {
+            Status = (AE_TIME);
+        }
+        break;
+
+    /* Wait with Timeout */
+
+    default:
+
+        T.tv_sec = Timeout / 1000;
+        T.tv_nsec = (Timeout - (T.tv_sec * 1000)) * 1000000;
+
+#ifdef ACPI_USE_ALTERNATE_TIMEOUT
+        /*
+         * Alternate timeout mechanism for environments where
+         * sem_timedwait is not available or does not work properly.
+         */
+        while (Timeout)
+        {
+            if (sem_trywait (Sem) == 0)
+            {
+                /* Got the semaphore */
+                return (AE_OK);
+            }
+            usleep (1000);  /* one millisecond */
+            Timeout--;
+        }
+        Status = (AE_TIME);
+#else
+
+        if (sem_timedwait (Sem, &T))
+        {
+            Status = (AE_TIME);
+        }
+#endif
+
+        break;
+    }
+
+    return (Status);
+}
+
+
+/******************************************************************************
+ *
+ * FUNCTION:    AcpiOsSignalSemaphore
+ *
+ * PARAMETERS:  Handle              - Handle returned by AcpiOsCreateSemaphore
+ *              Units               - Number of units to send
+ *
+ * RETURN:      Status
+ *
+ * DESCRIPTION: Send units
+ *
+ *****************************************************************************/
+
+ACPI_STATUS
+AcpiOsSignalSemaphore (
+    ACPI_HANDLE         Handle,
+    UINT32              Units)
+{
+    sem_t               *Sem = (sem_t *)Handle;
+
+
+    if (!Sem)
+    {
+        return (AE_BAD_PARAMETER);
+    }
+
+    if (sem_post (Sem) == -1)
+    {
+        return (AE_LIMIT);
+    }
+
+    return (AE_OK);
+}
+
+#endif /* ACPI_SINGLE_THREADED */
+
+
+/******************************************************************************
+ *
+ * FUNCTION:    Spinlock interfaces
+ *
+ * DESCRIPTION: Map these interfaces to semaphore interfaces
+ *
+ *****************************************************************************/
+
+ACPI_STATUS
+AcpiOsCreateLock (
+    ACPI_SPINLOCK           *OutHandle)
+{
+
+    return (AcpiOsCreateSemaphore (1, 1, OutHandle));
+}
+
+
+void
+AcpiOsDeleteLock (
+    ACPI_SPINLOCK           Handle)
+{
+    AcpiOsDeleteSemaphore (Handle);
+}
+
+
+ACPI_CPU_FLAGS
+AcpiOsAcquireLock (
+    ACPI_HANDLE             Handle)
+{
+    AcpiOsWaitSemaphore (Handle, 1, 0xFFFF);
+    return (0);
+}
+
+
+void
+AcpiOsReleaseLock (
+    ACPI_SPINLOCK           Handle,
+    ACPI_CPU_FLAGS          Flags)
+{
+    AcpiOsSignalSemaphore (Handle, 1);
+}
+
+
+/******************************************************************************
+ *
+ * FUNCTION:    AcpiOsInstallInterruptHandler
+ *
+ * PARAMETERS:  InterruptNumber     - Level handler should respond to.
+ *              Isr                 - Address of the ACPI interrupt handler
+ *              ExceptPtr           - Where status is returned
+ *
+ * RETURN:      Handle to the newly installed handler.
+ *
+ * DESCRIPTION: Install an interrupt handler. Used to install the ACPI
+ *              OS-independent handler.
+ *
+ *****************************************************************************/
+
+UINT32
+AcpiOsInstallInterruptHandler (
+    UINT32                  InterruptNumber,
+    ACPI_OSD_HANDLER        ServiceRoutine,
+    void                    *Context)
+{
+
+    return (AE_OK);
+}
+
+
+/******************************************************************************
+ *
+ * FUNCTION:    AcpiOsRemoveInterruptHandler
+ *
+ * PARAMETERS:  Handle              - Returned when handler was installed
+ *
+ * RETURN:      Status
+ *
+ * DESCRIPTION: Uninstalls an interrupt handler.
+ *
+ *****************************************************************************/
+
+ACPI_STATUS
+AcpiOsRemoveInterruptHandler (
+    UINT32                  InterruptNumber,
+    ACPI_OSD_HANDLER        ServiceRoutine)
+{
+
+    return (AE_OK);
+}
+
+
+/******************************************************************************
+ *
+ * FUNCTION:    AcpiOsStall
+ *
+ * PARAMETERS:  microseconds        - Time to sleep
+ *
+ * RETURN:      Blocks until sleep is completed.
+ *
+ * DESCRIPTION: Sleep at microsecond granularity
+ *
+ *****************************************************************************/
+
+void
+AcpiOsStall (
+    UINT32                  microseconds)
+{
+
+    if (microseconds)
+    {
+        usleep (microseconds);
+    }
+}
+
+
+/******************************************************************************
+ *
+ * FUNCTION:    AcpiOsSleep
+ *
+ * PARAMETERS:  milliseconds        - Time to sleep
+ *
+ * RETURN:      Blocks until sleep is completed.
+ *
+ * DESCRIPTION: Sleep at millisecond granularity
+ *
+ *****************************************************************************/
+
+void
+AcpiOsSleep (
+    UINT64                  milliseconds)
+{
+
+    sleep (milliseconds / 1000);    /* Sleep for whole seconds */
+
+    /*
+     * Arg to usleep() must be less than 1,000,000 (1 second)
+     */
+    usleep ((milliseconds % 1000) * 1000);      /* Sleep for remaining usecs */
+}
+
+
+/******************************************************************************
+ *
+ * FUNCTION:    AcpiOsGetTimer
+ *
+ * PARAMETERS:  None
+ *
+ * RETURN:      Current time in 100 nanosecond units
+ *
+ * DESCRIPTION: Get the current system time
+ *
+ *****************************************************************************/
+
+UINT64
+AcpiOsGetTimer (
+    void)
+{
+    struct timeval          time;
+
+
+    gettimeofday (&time, NULL);
+
+    /* Seconds * 10^7 = 100ns(10^-7), Microseconds(10^-6) * 10^1 = 100ns */
+
+    return (((UINT64) time.tv_sec * 10000000) + ((UINT64) time.tv_usec * 10));
+}
+
+
+/******************************************************************************
+ *
+ * FUNCTION:    AcpiOsReadPciConfiguration
+ *
+ * PARAMETERS:  PciId               - Seg/Bus/Dev
+ *              Register            - Device Register
+ *              Value               - Buffer where value is placed
+ *              Width               - Number of bits
+ *
+ * RETURN:      Status
+ *
+ * DESCRIPTION: Read data from PCI configuration space
+ *
+ *****************************************************************************/
+
+ACPI_STATUS
+AcpiOsReadPciConfiguration (
+    ACPI_PCI_ID             *PciId,
+    UINT32                  Register,
+    UINT64                  *Value,
+    UINT32                  Width)
+{
+
+    return (AE_OK);
+}
+
+
+/******************************************************************************
+ *
+ * FUNCTION:    AcpiOsWritePciConfiguration
+ *
+ * PARAMETERS:  PciId               - Seg/Bus/Dev
+ *              Register            - Device Register
+ *              Value               - Value to be written
+ *              Width               - Number of bits
+ *
+ * RETURN:      Status.
+ *
+ * DESCRIPTION: Write data to PCI configuration space
+ *
+ *****************************************************************************/
+
+ACPI_STATUS
+AcpiOsWritePciConfiguration (
+    ACPI_PCI_ID             *PciId,
+    UINT32                  Register,
+    UINT64                  Value,
+    UINT32                  Width)
+{
+
+    return (AE_OK);
+}
+
+
+/******************************************************************************
+ *
+ * FUNCTION:    AcpiOsReadPort
+ *
+ * PARAMETERS:  Address             - Address of I/O port/register to read
+ *              Value               - Where value is placed
+ *              Width               - Number of bits
+ *
+ * RETURN:      Value read from port
+ *
+ * DESCRIPTION: Read data from an I/O port or register
+ *
+ *****************************************************************************/
+
+ACPI_STATUS
+AcpiOsReadPort (
+    ACPI_IO_ADDRESS         Address,
+    UINT32                  *Value,
+    UINT32                  Width)
+{
+
+    switch (Width)
+    {
+    case 8:
+        *Value = 0xFF;
+        break;
+
+    case 16:
+        *Value = 0xFFFF;
+        break;
+
+    case 32:
+        *Value = 0xFFFFFFFF;
+        break;
+
+    default:
+        return (AE_BAD_PARAMETER);
+    }
+
+    return (AE_OK);
+}
+
+
+/******************************************************************************
+ *
+ * FUNCTION:    AcpiOsWritePort
+ *
+ * PARAMETERS:  Address             - Address of I/O port/register to write
+ *              Value               - Value to write
+ *              Width               - Number of bits
+ *
+ * RETURN:      None
+ *
+ * DESCRIPTION: Write data to an I/O port or register
+ *
+ *****************************************************************************/
+
+ACPI_STATUS
+AcpiOsWritePort (
+    ACPI_IO_ADDRESS         Address,
+    UINT32                  Value,
+    UINT32                  Width)
+{
+
+    return (AE_OK);
+}
+
+
+/******************************************************************************
+ *
+ * FUNCTION:    AcpiOsReadMemory
+ *
+ * PARAMETERS:  Address             - Physical Memory Address to read
+ *              Value               - Where value is placed
+ *              Width               - Number of bits
+ *
+ * RETURN:      Value read from physical memory address
+ *
+ * DESCRIPTION: Read data from a physical memory address
+ *
+ *****************************************************************************/
+
+ACPI_STATUS
+AcpiOsReadMemory (
+    ACPI_PHYSICAL_ADDRESS   Address,
+    UINT32                  *Value,
+    UINT32                  Width)
+{
+
+    switch (Width)
+    {
+    case 8:
+    case 16:
+    case 32:
+        *Value = 0;
+        break;
+
+    default:
+        return (AE_BAD_PARAMETER);
+    }
+    return (AE_OK);
+}
+
+
+/******************************************************************************
+ *
+ * FUNCTION:    AcpiOsWriteMemory
+ *
+ * PARAMETERS:  Address             - Physical Memory Address to write
+ *              Value               - Value to write
+ *              Width               - Number of bits
+ *
+ * RETURN:      None
+ *
+ * DESCRIPTION: Write data to a physical memory address
+ *
+ *****************************************************************************/
+
+ACPI_STATUS
+AcpiOsWriteMemory (
+    ACPI_PHYSICAL_ADDRESS   Address,
+    UINT32                  Value,
+    UINT32                  Width)
+{
+
+    return (AE_OK);
+}
+
+
+/******************************************************************************
+ *
+ * FUNCTION:    AcpiOsReadable
+ *
+ * PARAMETERS:  Pointer             - Area to be verified
+ *              Length              - Size of area
+ *
+ * RETURN:      TRUE if readable for entire length
+ *
+ * DESCRIPTION: Verify that a pointer is valid for reading
+ *
+ *****************************************************************************/
+
+BOOLEAN
+AcpiOsReadable (
+    void                    *Pointer,
+    ACPI_SIZE               Length)
+{
+
+    return (TRUE);
+}
+
+
+/******************************************************************************
+ *
+ * FUNCTION:    AcpiOsWritable
+ *
+ * PARAMETERS:  Pointer             - Area to be verified
+ *              Length              - Size of area
+ *
+ * RETURN:      TRUE if writable for entire length
+ *
+ * DESCRIPTION: Verify that a pointer is valid for writing
+ *
+ *****************************************************************************/
+
+BOOLEAN
+AcpiOsWritable (
+    void                    *Pointer,
+    ACPI_SIZE               Length)
+{
+
+    return (TRUE);
+}
+
+
+/******************************************************************************
+ *
+ * FUNCTION:    AcpiOsSignal
+ *
+ * PARAMETERS:  Function            - ACPI CA signal function code
+ *              Info                - Pointer to function-dependent structure
+ *
+ * RETURN:      Status
+ *
+ * DESCRIPTION: Miscellaneous functions. Example implementation only.
+ *
+ *****************************************************************************/
+
+ACPI_STATUS
+AcpiOsSignal (
+    UINT32                  Function,
+    void                    *Info)
+{
+
+    switch (Function)
+    {
+    case ACPI_SIGNAL_FATAL:
+        break;
+
+    case ACPI_SIGNAL_BREAKPOINT:
+        break;
+
+    default:
+        break;
+    }
+
+    return (AE_OK);
+}
+
+/* Optional multi-thread support */
+
+#ifndef ACPI_SINGLE_THREADED
+/******************************************************************************
+ *
+ * FUNCTION:    AcpiOsGetThreadId
+ *
+ * PARAMETERS:  None
+ *
+ * RETURN:      Id of the running thread
+ *
+ * DESCRIPTION: Get the ID of the current (running) thread
+ *
+ *****************************************************************************/
+
+ACPI_THREAD_ID
+AcpiOsGetThreadId (
+    void)
+{
+    pthread_t               thread;
+
+
+    thread = pthread_self();
+    return (ACPI_CAST_PTHREAD_T (thread));
+}
+
+
+/******************************************************************************
+ *
+ * FUNCTION:    AcpiOsExecute
+ *
+ * PARAMETERS:  Type                - Type of execution
+ *              Function            - Address of the function to execute
+ *              Context             - Passed as a parameter to the function
+ *
+ * RETURN:      Status.
+ *
+ * DESCRIPTION: Execute a new thread
+ *
+ *****************************************************************************/
+
+ACPI_STATUS
+AcpiOsExecute (
+    ACPI_EXECUTE_TYPE       Type,
+    ACPI_OSD_EXEC_CALLBACK  Function,
+    void                    *Context)
+{
+    pthread_t               thread;
+    int                     ret;
+
+
+    ret = pthread_create (&thread, NULL, (PTHREAD_CALLBACK) Function, Context);
+    if (ret)
+    {
+        AcpiOsPrintf("Create thread failed");
+    }
+    return (0);
+}
+
+#endif /* ACPI_SINGLE_THREADED */
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/osunixxf.c
--- a/head/sys/contrib/dev/acpica/osunixxf.c	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,1208 +0,0 @@
-/******************************************************************************
- *
- * Module Name: osunixxf - UNIX OSL interfaces
- *
- *****************************************************************************/
-
-/*
- * Copyright (C) 2000 - 2011, Intel Corp.
- * 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.
- * 3. Neither the names of the above-listed copyright holders nor the names
- *    of any contributors may be used to endorse or promote products derived
- *    from this software without specific prior written permission.
- *
- * Alternatively, this software may be distributed under the terms of the
- * GNU General Public License ("GPL") version 2 as published by the Free
- * Software Foundation.
- *
- * 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.
- */
-
-
-/*
- * These interfaces are required in order to compile the ASL compiler and the
- * various ACPICA tools under Linux or other Unix-like system.
- *
- * Note: Use #define __APPLE__ for OS X generation.
- */
-#include <stdio.h>
-#include <stdlib.h>
-#include <stdarg.h>
-#include <unistd.h>
-#include <sys/time.h>
-#include <semaphore.h>
-#include <pthread.h>
-#include <errno.h>
-
-#include <contrib/dev/acpica/include/acpi.h>
-#include <contrib/dev/acpica/include/accommon.h>
-#include <contrib/dev/acpica/include/amlcode.h>
-#include <contrib/dev/acpica/include/acparser.h>
-#include <contrib/dev/acpica/include/acdebug.h>
-
-#define _COMPONENT          ACPI_OS_SERVICES
-        ACPI_MODULE_NAME    ("osunixxf")
-
-
-extern FILE                    *AcpiGbl_DebugFile;
-FILE                           *AcpiGbl_OutputFile;
-
-
-/* Upcalls to AcpiExec */
-
-ACPI_PHYSICAL_ADDRESS
-AeLocalGetRootPointer (
-    void);
-
-void
-AeTableOverride (
-    ACPI_TABLE_HEADER       *ExistingTable,
-    ACPI_TABLE_HEADER       **NewTable);
-
-typedef void* (*PTHREAD_CALLBACK) (void *);
-
-/* Apple-specific */
-
-#ifdef __APPLE__
-#define sem_destroy         sem_close
-#endif
-
-
-/******************************************************************************
- *
- * FUNCTION:    AcpiOsInitialize, AcpiOsTerminate
- *
- * PARAMETERS:  None
- *
- * RETURN:      Status
- *
- * DESCRIPTION: Init and terminate. Nothing to do.
- *
- *****************************************************************************/
-
-ACPI_STATUS
-AcpiOsInitialize (
-    void)
-{
-
-    AcpiGbl_OutputFile = stdout;
-    return (AE_OK);
-}
-
-
-ACPI_STATUS
-AcpiOsTerminate (
-    void)
-{
-
-    return (AE_OK);
-}
-
-
-/******************************************************************************
- *
- * FUNCTION:    AcpiOsGetRootPointer
- *
- * PARAMETERS:  None
- *
- * RETURN:      RSDP physical address
- *
- * DESCRIPTION: Gets the ACPI root pointer (RSDP)
- *
- *****************************************************************************/
-
-ACPI_PHYSICAL_ADDRESS
-AcpiOsGetRootPointer (
-    void)
-{
-
-    return (AeLocalGetRootPointer ());
-}
-
-
-/******************************************************************************
- *
- * FUNCTION:    AcpiOsPredefinedOverride
- *
- * PARAMETERS:  InitVal             - Initial value of the predefined object
- *              NewVal              - The new value for the object
- *
- * RETURN:      Status, pointer to value. Null pointer returned if not
- *              overriding.
- *
- * DESCRIPTION: Allow the OS to override predefined names
- *
- *****************************************************************************/
-
-ACPI_STATUS
-AcpiOsPredefinedOverride (
-    const ACPI_PREDEFINED_NAMES *InitVal,
-    ACPI_STRING                 *NewVal)
-{
-
-    if (!InitVal || !NewVal)
-    {
-        return (AE_BAD_PARAMETER);
-    }
-
-    *NewVal = NULL;
-    return (AE_OK);
-}
-
-
-/******************************************************************************
- *
- * FUNCTION:    AcpiOsTableOverride
- *
- * PARAMETERS:  ExistingTable       - Header of current table (probably
- *                                    firmware)
- *              NewTable            - Where an entire new table is returned.
- *
- * RETURN:      Status, pointer to new table. Null pointer returned if no
- *              table is available to override
- *
- * DESCRIPTION: Return a different version of a table if one is available
- *
- *****************************************************************************/
-
-ACPI_STATUS
-AcpiOsTableOverride (
-    ACPI_TABLE_HEADER       *ExistingTable,
-    ACPI_TABLE_HEADER       **NewTable)
-{
-
-    if (!ExistingTable || !NewTable)
-    {
-        return (AE_BAD_PARAMETER);
-    }
-
-    *NewTable = NULL;
-
-#ifdef ACPI_EXEC_APP
-
-    AeTableOverride (ExistingTable, NewTable);
-    return (AE_OK);
-#else
-
-    return (AE_NO_ACPI_TABLES);
-#endif
-}
-
-
-/******************************************************************************
- *
- * FUNCTION:    AcpiOsRedirectOutput
- *
- * PARAMETERS:  Destination         - An open file handle/pointer
- *
- * RETURN:      None
- *
- * DESCRIPTION: Causes redirect of AcpiOsPrintf and AcpiOsVprintf
- *
- *****************************************************************************/
-
-void
-AcpiOsRedirectOutput (
-    void                    *Destination)
-{
-
-    AcpiGbl_OutputFile = Destination;
-}
-
-
-/******************************************************************************
- *
- * FUNCTION:    AcpiOsPrintf
- *
- * PARAMETERS:  fmt, ...            - Standard printf format
- *
- * RETURN:      None
- *
- * DESCRIPTION: Formatted output
- *
- *****************************************************************************/
-
-void ACPI_INTERNAL_VAR_XFACE
-AcpiOsPrintf (
-    const char              *Fmt,
-    ...)
-{
-    va_list                 Args;
-
-
-    va_start (Args, Fmt);
-    AcpiOsVprintf (Fmt, Args);
-    va_end (Args);
-}
-
-
-/******************************************************************************
- *
- * FUNCTION:    AcpiOsVprintf
- *
- * PARAMETERS:  fmt                 - Standard printf format
- *              args                - Argument list
- *
- * RETURN:      None
- *
- * DESCRIPTION: Formatted output with argument list pointer
- *
- *****************************************************************************/
-
-void
-AcpiOsVprintf (
-    const char              *Fmt,
-    va_list                 Args)
-{
-    INT32                   Count = 0;
-    UINT8                   Flags;
-
-
-    Flags = AcpiGbl_DbOutputFlags;
-    if (Flags & ACPI_DB_REDIRECTABLE_OUTPUT)
-    {
-        /* Output is directable to either a file (if open) or the console */
-
-        if (AcpiGbl_DebugFile)
-        {
-            /* Output file is open, send the output there */
-
-            Count = vfprintf (AcpiGbl_DebugFile, Fmt, Args);
-        }
-        else
-        {
-            /* No redirection, send output to console (once only!) */
-
-            Flags |= ACPI_DB_CONSOLE_OUTPUT;
-        }
-    }
-
-    if (Flags & ACPI_DB_CONSOLE_OUTPUT)
-    {
-        Count = vfprintf (AcpiGbl_OutputFile, Fmt, Args);
-    }
-}
-
-
-/******************************************************************************
- *
- * FUNCTION:    AcpiOsGetLine
- *
- * PARAMETERS:  Buffer              - Where to return the command line
- *              BufferLength        - Maximum length of Buffer
- *              BytesRead           - Where the actual byte count is returned
- *
- * RETURN:      Status and actual bytes read
- *
- * DESCRIPTION: Formatted input with argument list pointer
- *
- *****************************************************************************/
-
-ACPI_STATUS
-AcpiOsGetLine (
-    char                    *Buffer,
-    UINT32                  BufferLength,
-    UINT32                  *BytesRead)
-{
-    UINT8                   Temp;
-    UINT32                  i;
-
-
-    for (i = 0; ; i++)
-    {
-        if (i >= BufferLength)
-        {
-            return (AE_BUFFER_OVERFLOW);
-        }
-
-        scanf ("%1c", &Temp);
-        if (!Temp || Temp == '\n')
-        {
-            break;
-        }
-
-        Buffer [i] = Temp;
-    }
-
-    /* Null terminate the buffer */
-
-    Buffer [i] = 0;
-
-    /* Return the number of bytes in the string */
-
-    if (BytesRead)
-    {
-        *BytesRead = i;
-    }
-    return (AE_OK);
-}
-
-
-/******************************************************************************
- *
- * FUNCTION:    AcpiOsMapMemory
- *
- * PARAMETERS:  where               - Physical address of memory to be mapped
- *              length              - How much memory to map
- *
- * RETURN:      Pointer to mapped memory. Null on error.
- *
- * DESCRIPTION: Map physical memory into caller's address space
- *
- *****************************************************************************/
-
-void *
-AcpiOsMapMemory (
-    ACPI_PHYSICAL_ADDRESS   where,
-    ACPI_SIZE               length)
-{
-
-    return (ACPI_TO_POINTER ((ACPI_SIZE) where));
-}
-
-
-/******************************************************************************
- *
- * FUNCTION:    AcpiOsUnmapMemory
- *
- * PARAMETERS:  where               - Logical address of memory to be unmapped
- *              length              - How much memory to unmap
- *
- * RETURN:      None.
- *
- * DESCRIPTION: Delete a previously created mapping. Where and Length must
- *              correspond to a previous mapping exactly.
- *
- *****************************************************************************/
-
-void
-AcpiOsUnmapMemory (
-    void                    *where,
-    ACPI_SIZE               length)
-{
-
-    return;
-}
-
-
-/******************************************************************************
- *
- * FUNCTION:    AcpiOsAllocate
- *
- * PARAMETERS:  Size                - Amount to allocate, in bytes
- *
- * RETURN:      Pointer to the new allocation. Null on error.
- *
- * DESCRIPTION: Allocate memory. Algorithm is dependent on the OS.
- *
- *****************************************************************************/
-
-void *
-AcpiOsAllocate (
-    ACPI_SIZE               size)
-{
-    void                    *Mem;
-
-
-    Mem = (void *) malloc ((size_t) size);
-    return (Mem);
-}
-
-
-/******************************************************************************
- *
- * FUNCTION:    AcpiOsFree
- *
- * PARAMETERS:  mem                 - Pointer to previously allocated memory
- *
- * RETURN:      None.
- *
- * DESCRIPTION: Free memory allocated via AcpiOsAllocate
- *
- *****************************************************************************/
-
-void
-AcpiOsFree (
-    void                    *mem)
-{
-
-    free (mem);
-}
-
-
-#ifdef ACPI_SINGLE_THREADED
-/******************************************************************************
- *
- * FUNCTION:    Semaphore stub functions
- *
- * DESCRIPTION: Stub functions used for single-thread applications that do
- *              not require semaphore synchronization. Full implementations
- *              of these functions appear after the stubs.
- *
- *****************************************************************************/
-
-ACPI_STATUS
-AcpiOsCreateSemaphore (
-    UINT32              MaxUnits,
-    UINT32              InitialUnits,
-    ACPI_HANDLE         *OutHandle)
-{
-    *OutHandle = (ACPI_HANDLE) 1;
-    return (AE_OK);
-}
-
-ACPI_STATUS
-AcpiOsDeleteSemaphore (
-    ACPI_HANDLE         Handle)
-{
-    return (AE_OK);
-}
-
-ACPI_STATUS
-AcpiOsWaitSemaphore (
-    ACPI_HANDLE         Handle,
-    UINT32              Units,
-    UINT16              Timeout)
-{
-    return (AE_OK);
-}
-
-ACPI_STATUS
-AcpiOsSignalSemaphore (
-    ACPI_HANDLE         Handle,
-    UINT32              Units)
-{
-    return (AE_OK);
-}
-
-#else
-/******************************************************************************
- *
- * FUNCTION:    AcpiOsCreateSemaphore
- *
- * PARAMETERS:  InitialUnits        - Units to be assigned to the new semaphore
- *              OutHandle           - Where a handle will be returned
- *
- * RETURN:      Status
- *
- * DESCRIPTION: Create an OS semaphore
- *
- *****************************************************************************/
-
-ACPI_STATUS
-AcpiOsCreateSemaphore (
-    UINT32              MaxUnits,
-    UINT32              InitialUnits,
-    ACPI_HANDLE         *OutHandle)
-{
-    sem_t               *Sem;
-
-
-    if (!OutHandle)
-    {
-        return (AE_BAD_PARAMETER);
-    }
-
-#ifdef __APPLE__
-    {
-        char            *SemaphoreName = tmpnam (NULL);
-
-        Sem = sem_open (SemaphoreName, O_EXCL|O_CREAT, 0755, InitialUnits);
-        if (!Sem)
-        {
-            return (AE_NO_MEMORY);
-        }
-        sem_unlink (SemaphoreName); /* This just deletes the name */
-    }
-
-#else
-    Sem = AcpiOsAllocate (sizeof (sem_t));
-    if (!Sem)
-    {
-        return (AE_NO_MEMORY);
-    }
-
-    if (sem_init (Sem, 0, InitialUnits) == -1)
-    {
-        AcpiOsFree (Sem);
-        return (AE_BAD_PARAMETER);
-    }
-#endif
-
-    *OutHandle = (ACPI_HANDLE) Sem;
-    return (AE_OK);
-}
-
-
-/******************************************************************************
- *
- * FUNCTION:    AcpiOsDeleteSemaphore
- *
- * PARAMETERS:  Handle              - Handle returned by AcpiOsCreateSemaphore
- *
- * RETURN:      Status
- *
- * DESCRIPTION: Delete an OS semaphore
- *
- *****************************************************************************/
-
-ACPI_STATUS
-AcpiOsDeleteSemaphore (
-    ACPI_HANDLE         Handle)
-{
-    sem_t               *Sem = (sem_t *) Handle;
-
-
-    if (!Sem)
-    {
-        return (AE_BAD_PARAMETER);
-    }
-
-    if (sem_destroy (Sem) == -1)
-    {
-        return (AE_BAD_PARAMETER);
-    }
-
-    return (AE_OK);
-}
-
-
-/******************************************************************************
- *
- * FUNCTION:    AcpiOsWaitSemaphore
- *
- * PARAMETERS:  Handle              - Handle returned by AcpiOsCreateSemaphore
- *              Units               - How many units to wait for
- *              Timeout             - How long to wait
- *
- * RETURN:      Status
- *
- * DESCRIPTION: Wait for units
- *
- *****************************************************************************/
-
-ACPI_STATUS
-AcpiOsWaitSemaphore (
-    ACPI_HANDLE         Handle,
-    UINT32              Units,
-    UINT16              Timeout)
-{
-    ACPI_STATUS         Status = AE_OK;
-    sem_t               *Sem = (sem_t *) Handle;
-    struct timespec     T;
-
-
-    if (!Sem)
-    {
-        return (AE_BAD_PARAMETER);
-    }
-
-    switch (Timeout)
-    {
-    /*
-     * No Wait:
-     * --------
-     * A zero timeout value indicates that we shouldn't wait - just
-     * acquire the semaphore if available otherwise return AE_TIME
-     * (a.k.a. 'would block').
-     */
-    case 0:
-
-        if (sem_trywait(Sem) == -1)
-        {
-            Status = (AE_TIME);
-        }
-        break;
-
-    /* Wait Indefinitely */
-
-    case ACPI_WAIT_FOREVER:
-
-        if (sem_wait (Sem))
-        {
-            Status = (AE_TIME);
-        }
-        break;
-
-    /* Wait with Timeout */
-
-    default:
-
-        T.tv_sec = Timeout / 1000;
-        T.tv_nsec = (Timeout - (T.tv_sec * 1000)) * 1000000;
-
-#ifdef ACPI_USE_ALTERNATE_TIMEOUT
-        /*
-         * Alternate timeout mechanism for environments where
-         * sem_timedwait is not available or does not work properly.
-         */
-        while (Timeout)
-        {
-            if (sem_trywait (Sem) == 0)
-            {
-                /* Got the semaphore */
-                return (AE_OK);
-            }
-            usleep (1000);  /* one millisecond */
-            Timeout--;
-        }
-        Status = (AE_TIME);
-#else
-
-        if (sem_timedwait (Sem, &T))
-        {
-            Status = (AE_TIME);
-        }
-#endif
-
-        break;
-    }
-
-    return (Status);
-}
-
-
-/******************************************************************************
- *
- * FUNCTION:    AcpiOsSignalSemaphore
- *
- * PARAMETERS:  Handle              - Handle returned by AcpiOsCreateSemaphore
- *              Units               - Number of units to send
- *
- * RETURN:      Status
- *
- * DESCRIPTION: Send units
- *
- *****************************************************************************/
-
-ACPI_STATUS
-AcpiOsSignalSemaphore (
-    ACPI_HANDLE         Handle,
-    UINT32              Units)
-{
-    sem_t               *Sem = (sem_t *)Handle;
-
-
-    if (!Sem)
-    {
-        return (AE_BAD_PARAMETER);
-    }
-
-    if (sem_post (Sem) == -1)
-    {
-        return (AE_LIMIT);
-    }
-
-    return (AE_OK);
-}
-
-#endif /* ACPI_SINGLE_THREADED */
-
-
-/******************************************************************************
- *
- * FUNCTION:    Spinlock interfaces
- *
- * DESCRIPTION: Map these interfaces to semaphore interfaces
- *
- *****************************************************************************/
-
-ACPI_STATUS
-AcpiOsCreateLock (
-    ACPI_SPINLOCK           *OutHandle)
-{
-
-    return (AcpiOsCreateSemaphore (1, 1, OutHandle));
-}
-
-
-void
-AcpiOsDeleteLock (
-    ACPI_SPINLOCK           Handle)
-{
-    AcpiOsDeleteSemaphore (Handle);
-}
-
-
-ACPI_CPU_FLAGS
-AcpiOsAcquireLock (
-    ACPI_HANDLE             Handle)
-{
-    AcpiOsWaitSemaphore (Handle, 1, 0xFFFF);
-    return (0);
-}
-
-
-void
-AcpiOsReleaseLock (
-    ACPI_SPINLOCK           Handle,
-    ACPI_CPU_FLAGS          Flags)
-{
-    AcpiOsSignalSemaphore (Handle, 1);
-}
-
-
-/******************************************************************************
- *
- * FUNCTION:    AcpiOsInstallInterruptHandler
- *
- * PARAMETERS:  InterruptNumber     - Level handler should respond to.
- *              Isr                 - Address of the ACPI interrupt handler
- *              ExceptPtr           - Where status is returned
- *
- * RETURN:      Handle to the newly installed handler.
- *
- * DESCRIPTION: Install an interrupt handler. Used to install the ACPI
- *              OS-independent handler.
- *
- *****************************************************************************/
-
-UINT32
-AcpiOsInstallInterruptHandler (
-    UINT32                  InterruptNumber,
-    ACPI_OSD_HANDLER        ServiceRoutine,
-    void                    *Context)
-{
-
-    return (AE_OK);
-}
-
-
-/******************************************************************************
- *
- * FUNCTION:    AcpiOsRemoveInterruptHandler
- *
- * PARAMETERS:  Handle              - Returned when handler was installed
- *
- * RETURN:      Status
- *
- * DESCRIPTION: Uninstalls an interrupt handler.
- *
- *****************************************************************************/
-
-ACPI_STATUS
-AcpiOsRemoveInterruptHandler (
-    UINT32                  InterruptNumber,
-    ACPI_OSD_HANDLER        ServiceRoutine)
-{
-
-    return (AE_OK);
-}
-
-
-/******************************************************************************
- *
- * FUNCTION:    AcpiOsExecute
- *
- * PARAMETERS:  Type                - Type of execution
- *              Function            - Address of the function to execute
- *              Context             - Passed as a parameter to the function
- *
- * RETURN:      Status.
- *
- * DESCRIPTION: Execute a new thread
- *
- *****************************************************************************/
-
-ACPI_STATUS
-AcpiOsExecute (
-    ACPI_EXECUTE_TYPE       Type,
-    ACPI_OSD_EXEC_CALLBACK  Function,
-    void                    *Context)
-{
-    pthread_t               thread;
-    int                     ret;
-
-
-    ret = pthread_create (&thread, NULL, (PTHREAD_CALLBACK) Function, Context);
-    if (ret)
-    {
-        AcpiOsPrintf("Create thread failed");
-    }
-    return (0);
-}
-
-
-/******************************************************************************
- *
- * FUNCTION:    AcpiOsStall
- *
- * PARAMETERS:  microseconds        - Time to sleep
- *
- * RETURN:      Blocks until sleep is completed.
- *
- * DESCRIPTION: Sleep at microsecond granularity
- *
- *****************************************************************************/
-
-void
-AcpiOsStall (
-    UINT32                  microseconds)
-{
-
-    if (microseconds)
-    {
-        usleep (microseconds);
-    }
-}
-
-
-/******************************************************************************
- *
- * FUNCTION:    AcpiOsSleep
- *
- * PARAMETERS:  milliseconds        - Time to sleep
- *
- * RETURN:      Blocks until sleep is completed.
- *
- * DESCRIPTION: Sleep at millisecond granularity
- *
- *****************************************************************************/
-
-void
-AcpiOsSleep (
-    UINT64                  milliseconds)
-{
-
-    sleep (milliseconds / 1000);    /* Sleep for whole seconds */
-
-    /*
-     * Arg to usleep() must be less than 1,000,000 (1 second)
-     */
-    usleep ((milliseconds % 1000) * 1000);      /* Sleep for remaining usecs */
-}
-
-
-/******************************************************************************
- *
- * FUNCTION:    AcpiOsGetTimer
- *
- * PARAMETERS:  None
- *
- * RETURN:      Current time in 100 nanosecond units
- *
- * DESCRIPTION: Get the current system time
- *
- *****************************************************************************/
-
-UINT64
-AcpiOsGetTimer (
-    void)
-{
-    struct timeval          time;
-
-
-    gettimeofday (&time, NULL);
-
-    /* Seconds * 10^7 = 100ns(10^-7), Microseconds(10^-6) * 10^1 = 100ns */
-
-    return (((UINT64) time.tv_sec * 10000000) + ((UINT64) time.tv_usec * 10));
-}
-
-
-/******************************************************************************
- *
- * FUNCTION:    AcpiOsReadPciConfiguration
- *
- * PARAMETERS:  PciId               - Seg/Bus/Dev
- *              Register            - Device Register
- *              Value               - Buffer where value is placed
- *              Width               - Number of bits
- *
- * RETURN:      Status
- *
- * DESCRIPTION: Read data from PCI configuration space
- *
- *****************************************************************************/
-
-ACPI_STATUS
-AcpiOsReadPciConfiguration (
-    ACPI_PCI_ID             *PciId,
-    UINT32                  Register,
-    UINT64                  *Value,
-    UINT32                  Width)
-{
-
-    return (AE_OK);
-}
-
-
-/******************************************************************************
- *
- * FUNCTION:    AcpiOsWritePciConfiguration
- *
- * PARAMETERS:  PciId               - Seg/Bus/Dev
- *              Register            - Device Register
- *              Value               - Value to be written
- *              Width               - Number of bits
- *
- * RETURN:      Status.
- *
- * DESCRIPTION: Write data to PCI configuration space
- *
- *****************************************************************************/
-
-ACPI_STATUS
-AcpiOsWritePciConfiguration (
-    ACPI_PCI_ID             *PciId,
-    UINT32                  Register,
-    UINT64                  Value,
-    UINT32                  Width)
-{
-
-    return (AE_OK);
-}
-
-
-/******************************************************************************
- *
- * FUNCTION:    AcpiOsReadPort
- *
- * PARAMETERS:  Address             - Address of I/O port/register to read
- *              Value               - Where value is placed
- *              Width               - Number of bits
- *
- * RETURN:      Value read from port
- *
- * DESCRIPTION: Read data from an I/O port or register
- *
- *****************************************************************************/
-
-ACPI_STATUS
-AcpiOsReadPort (
-    ACPI_IO_ADDRESS         Address,
-    UINT32                  *Value,
-    UINT32                  Width)
-{
-
-    switch (Width)
-    {
-    case 8:
-        *Value = 0xFF;
-        break;
-
-    case 16:
-        *Value = 0xFFFF;
-        break;
-
-    case 32:
-        *Value = 0xFFFFFFFF;
-        break;
-
-    default:
-        return (AE_BAD_PARAMETER);
-    }
-
-    return (AE_OK);
-}
-
-
-/******************************************************************************
- *
- * FUNCTION:    AcpiOsWritePort
- *
- * PARAMETERS:  Address             - Address of I/O port/register to write
- *              Value               - Value to write
- *              Width               - Number of bits
- *
- * RETURN:      None
- *
- * DESCRIPTION: Write data to an I/O port or register
- *
- *****************************************************************************/
-
-ACPI_STATUS
-AcpiOsWritePort (
-    ACPI_IO_ADDRESS         Address,
-    UINT32                  Value,
-    UINT32                  Width)
-{
-
-    return (AE_OK);
-}
-
-
-/******************************************************************************
- *
- * FUNCTION:    AcpiOsReadMemory
- *
- * PARAMETERS:  Address             - Physical Memory Address to read
- *              Value               - Where value is placed
- *              Width               - Number of bits
- *
- * RETURN:      Value read from physical memory address
- *
- * DESCRIPTION: Read data from a physical memory address
- *
- *****************************************************************************/
-
-ACPI_STATUS
-AcpiOsReadMemory (
-    ACPI_PHYSICAL_ADDRESS   Address,
-    UINT32                  *Value,
-    UINT32                  Width)
-{
-
-    switch (Width)
-    {
-    case 8:
-    case 16:
-    case 32:
-        *Value = 0;
-        break;
-
-    default:
-        return (AE_BAD_PARAMETER);
-    }
-    return (AE_OK);
-}
-
-
-/******************************************************************************
- *
- * FUNCTION:    AcpiOsWriteMemory
- *
- * PARAMETERS:  Address             - Physical Memory Address to write
- *              Value               - Value to write
- *              Width               - Number of bits
- *
- * RETURN:      None
- *
- * DESCRIPTION: Write data to a physical memory address
- *
- *****************************************************************************/
-
-ACPI_STATUS
-AcpiOsWriteMemory (
-    ACPI_PHYSICAL_ADDRESS   Address,
-    UINT32                  Value,
-    UINT32                  Width)
-{
-
-    return (AE_OK);
-}
-
-
-/******************************************************************************
- *
- * FUNCTION:    AcpiOsReadable
- *
- * PARAMETERS:  Pointer             - Area to be verified
- *              Length              - Size of area
- *
- * RETURN:      TRUE if readable for entire length
- *
- * DESCRIPTION: Verify that a pointer is valid for reading
- *
- *****************************************************************************/
-
-BOOLEAN
-AcpiOsReadable (
-    void                    *Pointer,
-    ACPI_SIZE               Length)
-{
-
-    return (TRUE);
-}
-
-
-/******************************************************************************
- *
- * FUNCTION:    AcpiOsWritable
- *
- * PARAMETERS:  Pointer             - Area to be verified
- *              Length              - Size of area
- *
- * RETURN:      TRUE if writable for entire length
- *
- * DESCRIPTION: Verify that a pointer is valid for writing
- *
- *****************************************************************************/
-
-BOOLEAN
-AcpiOsWritable (
-    void                    *Pointer,
-    ACPI_SIZE               Length)
-{
-
-    return (TRUE);
-}
-
-
-/******************************************************************************
- *
- * FUNCTION:    AcpiOsGetThreadId
- *
- * PARAMETERS:  None
- *
- * RETURN:      Id of the running thread
- *
- * DESCRIPTION: Get the ID of the current (running) thread
- *
- *****************************************************************************/
-
-ACPI_THREAD_ID
-AcpiOsGetThreadId (
-    void)
-{
-
-    return (ACPI_CAST_PTHREAD_T (pthread_self()));
-}
-
-
-/******************************************************************************
- *
- * FUNCTION:    AcpiOsSignal
- *
- * PARAMETERS:  Function            - ACPI CA signal function code
- *              Info                - Pointer to function-dependent structure
- *
- * RETURN:      Status
- *
- * DESCRIPTION: Miscellaneous functions. Example implementation only.
- *
- *****************************************************************************/
-
-ACPI_STATUS
-AcpiOsSignal (
-    UINT32                  Function,
-    void                    *Info)
-{
-
-    switch (Function)
-    {
-    case ACPI_SIGNAL_FATAL:
-        break;
-
-    case ACPI_SIGNAL_BREAKPOINT:
-        break;
-
-    default:
-        break;
-    }
-
-    return (AE_OK);
-}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/parser/psargs.c
--- a/head/sys/contrib/dev/acpica/parser/psargs.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/parser/psargs.c	Tue Dec 06 20:26:16 2011 +0200
@@ -531,37 +531,57 @@
 AcpiPsGetNextField (
     ACPI_PARSE_STATE        *ParserState)
 {
-    UINT32                  AmlOffset = (UINT32)
-                                ACPI_PTR_DIFF (ParserState->Aml,
-                                               ParserState->AmlStart);
+    UINT32                  AmlOffset;
     ACPI_PARSE_OBJECT       *Field;
+    ACPI_PARSE_OBJECT       *Arg = NULL;
     UINT16                  Opcode;
     UINT32                  Name;
+    UINT8                   AccessType;
+    UINT8                   AccessAttribute;
+    UINT8                   AccessLength;
+    UINT32                  PkgLength;
+    UINT8                   *PkgEnd;
+    UINT32                  BufferLength;
 
 
     ACPI_FUNCTION_TRACE (PsGetNextField);
 
 
+    AmlOffset = (UINT32) ACPI_PTR_DIFF (
+        ParserState->Aml, ParserState->AmlStart);
+
     /* Determine field type */
 
     switch (ACPI_GET8 (ParserState->Aml))
     {
-    default:
-
-        Opcode = AML_INT_NAMEDFIELD_OP;
-        break;
-
-    case 0x00:
+    case AML_FIELD_OFFSET_OP:
 
         Opcode = AML_INT_RESERVEDFIELD_OP;
         ParserState->Aml++;
         break;
 
-    case 0x01:
+    case AML_FIELD_ACCESS_OP:
 
         Opcode = AML_INT_ACCESSFIELD_OP;
         ParserState->Aml++;
         break;
+
+    case AML_FIELD_CONNECTION_OP:
+
+        Opcode = AML_INT_CONNECTION_OP;
+        ParserState->Aml++;
+        break;
+
+    case AML_FIELD_EXT_ACCESS_OP:
+
+        Opcode = AML_INT_EXTACCESSFIELD_OP;
+        ParserState->Aml++;
+        break;
+
+    default:
+
+        Opcode = AML_INT_NAMEDFIELD_OP;
+        break;
     }
 
     /* Allocate a new field op */
@@ -601,17 +621,116 @@
 
 
     case AML_INT_ACCESSFIELD_OP:
+    case AML_INT_EXTACCESSFIELD_OP:
 
         /*
          * Get AccessType and AccessAttrib and merge into the field Op
-         * AccessType is first operand, AccessAttribute is second
+         * AccessType is first operand, AccessAttribute is second. stuff
+         * these bytes into the node integer value for convenience.
          */
-        Field->Common.Value.Integer = (((UINT32) ACPI_GET8 (ParserState->Aml) << 8));
+
+        /* Get the two bytes (Type/Attribute) */
+
+        AccessType = ACPI_GET8 (ParserState->Aml);
         ParserState->Aml++;
-        Field->Common.Value.Integer |= ACPI_GET8 (ParserState->Aml);
+        AccessAttribute = ACPI_GET8 (ParserState->Aml);
         ParserState->Aml++;
+
+        Field->Common.Value.Integer = (UINT8) AccessType;
+        Field->Common.Value.Integer |= (UINT16) (AccessAttribute << 8);
+
+        /* This opcode has a third byte, AccessLength */
+
+        if (Opcode == AML_INT_EXTACCESSFIELD_OP)
+        {
+            AccessLength = ACPI_GET8 (ParserState->Aml);
+            ParserState->Aml++;
+
+            Field->Common.Value.Integer |= (UINT32) (AccessLength << 16);
+        }
         break;
 
+
+    case AML_INT_CONNECTION_OP:
+
+        /*
+         * Argument for Connection operator can be either a Buffer
+         * (resource descriptor), or a NameString.
+         */
+        if (ACPI_GET8 (ParserState->Aml) == AML_BUFFER_OP)
+        {
+            ParserState->Aml++;
+
+            PkgEnd = ParserState->Aml;
+            PkgLength = AcpiPsGetNextPackageLength (ParserState);
+            PkgEnd += PkgLength;
+
+            if (ParserState->Aml < PkgEnd)
+            {
+                /* Non-empty list */
+
+                Arg = AcpiPsAllocOp (AML_INT_BYTELIST_OP);
+                if (!Arg)
+                {
+                    return_PTR (NULL);
+                }
+
+                /* Get the actual buffer length argument */
+
+                Opcode = ACPI_GET8 (ParserState->Aml);
+                ParserState->Aml++;
+
+                switch (Opcode)
+                {
+                case AML_BYTE_OP:       /* AML_BYTEDATA_ARG */
+                    BufferLength = ACPI_GET8 (ParserState->Aml);
+                    ParserState->Aml += 1;
+                    break;
+
+                case AML_WORD_OP:       /* AML_WORDDATA_ARG */
+                    BufferLength = ACPI_GET16 (ParserState->Aml);
+                    ParserState->Aml += 2;
+                    break;
+
+                case AML_DWORD_OP:      /* AML_DWORDATA_ARG */
+                    BufferLength = ACPI_GET32 (ParserState->Aml);
+                    ParserState->Aml += 4;
+                    break;
+
+                default:
+                    BufferLength = 0;
+                    break;
+                }
+
+                /* Fill in bytelist data */
+
+                Arg->Named.Value.Size = BufferLength;
+                Arg->Named.Data = ParserState->Aml;
+            }
+
+            /* Skip to End of byte data */
+
+            ParserState->Aml = PkgEnd;
+        }
+        else
+        {
+            Arg = AcpiPsAllocOp (AML_INT_NAMEPATH_OP);
+            if (!Arg)
+            {
+                return_PTR (NULL);
+            }
+
+            /* Get the Namestring argument */
+
+            Arg->Common.Value.Name = AcpiPsGetNextNamestring (ParserState);
+        }
+
+        /* Link the buffer/namestring to parent (CONNECTION_OP) */
+
+        AcpiPsAppendArg (Field, Arg);
+        break;
+
+
     default:
 
         /* Opcode was set in previous switch */
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/parser/psopcode.c
--- a/head/sys/contrib/dev/acpica/parser/psopcode.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/parser/psopcode.c	Tue Dec 06 20:26:16 2011 +0200
@@ -328,12 +328,17 @@
 /* 79 */ ACPI_OP ("Mid",                ARGP_MID_OP,               ARGI_MID_OP,                ACPI_TYPE_ANY,               AML_CLASS_EXECUTE,         AML_TYPE_EXEC_3A_1T_1R,   AML_FLAGS_EXEC_3A_1T_1R | AML_CONSTANT),
 /* 7A */ ACPI_OP ("Continue",           ARGP_CONTINUE_OP,          ARGI_CONTINUE_OP,           ACPI_TYPE_ANY,               AML_CLASS_CONTROL,         AML_TYPE_CONTROL,         0),
 /* 7B */ ACPI_OP ("LoadTable",          ARGP_LOAD_TABLE_OP,        ARGI_LOAD_TABLE_OP,         ACPI_TYPE_ANY,               AML_CLASS_EXECUTE,         AML_TYPE_EXEC_6A_0T_1R,   AML_FLAGS_EXEC_6A_0T_1R),
-/* 7C */ ACPI_OP ("DataTableRegion",    ARGP_DATA_REGION_OP,       ARGI_DATA_REGION_OP,        ACPI_TYPE_REGION,            AML_CLASS_NAMED_OBJECT,    AML_TYPE_NAMED_COMPLEX,    AML_HAS_ARGS | AML_NSOBJECT | AML_NSOPCODE | AML_NSNODE | AML_NAMED | AML_DEFER),
+/* 7C */ ACPI_OP ("DataTableRegion",    ARGP_DATA_REGION_OP,       ARGI_DATA_REGION_OP,        ACPI_TYPE_REGION,            AML_CLASS_NAMED_OBJECT,    AML_TYPE_NAMED_COMPLEX,   AML_HAS_ARGS | AML_NSOBJECT | AML_NSOPCODE | AML_NSNODE | AML_NAMED | AML_DEFER),
 /* 7D */ ACPI_OP ("[EvalSubTree]",      ARGP_SCOPE_OP,             ARGI_SCOPE_OP,              ACPI_TYPE_ANY,               AML_CLASS_NAMED_OBJECT,    AML_TYPE_NAMED_NO_OBJ,    AML_HAS_ARGS | AML_NSOBJECT | AML_NSOPCODE | AML_NSNODE),
 
 /* ACPI 3.0 opcodes */
 
-/* 7E */ ACPI_OP ("Timer",              ARGP_TIMER_OP,             ARGI_TIMER_OP,              ACPI_TYPE_ANY,               AML_CLASS_EXECUTE,         AML_TYPE_EXEC_0A_0T_1R,   AML_FLAGS_EXEC_0A_0T_1R)
+/* 7E */ ACPI_OP ("Timer",              ARGP_TIMER_OP,             ARGI_TIMER_OP,              ACPI_TYPE_ANY,               AML_CLASS_EXECUTE,         AML_TYPE_EXEC_0A_0T_1R,   AML_FLAGS_EXEC_0A_0T_1R),
+
+/* ACPI 5.0 opcodes */
+
+/* 7F */ ACPI_OP ("-ConnectField-",     ARGP_CONNECTFIELD_OP,      ARGI_CONNECTFIELD_OP,       ACPI_TYPE_ANY,               AML_CLASS_INTERNAL,        AML_TYPE_BOGUS,           AML_HAS_ARGS),
+/* 80 */ ACPI_OP ("-ExtAccessField-",   ARGP_CONNECTFIELD_OP,      ARGI_CONNECTFIELD_OP,       ACPI_TYPE_ANY,               AML_CLASS_INTERNAL,        AML_TYPE_BOGUS,           0)
 
 /*! [End] no source code translation !*/
 };
@@ -353,7 +358,7 @@
 /* 0x20 */    _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, _UNK,
 /* 0x28 */    _UNK, _UNK, _UNK, _UNK, _UNK, 0x63, _PFX, _PFX,
 /* 0x30 */    0x67, 0x66, 0x68, 0x65, 0x69, 0x64, 0x6A, 0x7D,
-/* 0x38 */    _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, _UNK, _UNK,
+/* 0x38 */    0x7F, 0x80, _UNK, _UNK, _UNK, _UNK, _UNK, _UNK,
 /* 0x40 */    _UNK, _ASC, _ASC, _ASC, _ASC, _ASC, _ASC, _ASC,
 /* 0x48 */    _ASC, _ASC, _ASC, _ASC, _ASC, _ASC, _ASC, _ASC,
 /* 0x50 */    _ASC, _ASC, _ASC, _ASC, _ASC, _ASC, _ASC, _ASC,
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/parser/pstree.c
--- a/head/sys/contrib/dev/acpica/parser/pstree.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/parser/pstree.c	Tue Dec 06 20:26:16 2011 +0200
@@ -85,7 +85,12 @@
 
     ACPI_FUNCTION_ENTRY ();
 
-
+/*
+    if (Op->Common.AmlOpcode == AML_INT_CONNECTION_OP)
+    {
+        return (Op->Common.Value.Arg);
+    }
+*/
     /* Get the info structure for this opcode */
 
     OpInfo = AcpiPsGetOpcodeInfo (Op->Common.AmlOpcode);
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/resources/rscalc.c
--- a/head/sys/contrib/dev/acpica/resources/rscalc.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/resources/rscalc.c	Tue Dec 06 20:26:16 2011 +0200
@@ -345,6 +345,26 @@
             break;
 
 
+        case ACPI_RESOURCE_TYPE_GPIO:
+
+            TotalSize = (ACPI_RS_LENGTH) (TotalSize + (Resource->Data.Gpio.PinTableLength * 2) +
+                Resource->Data.Gpio.ResourceSource.StringLength +
+                Resource->Data.Gpio.VendorLength);
+
+            break;
+
+
+        case ACPI_RESOURCE_TYPE_SERIAL_BUS:
+
+            TotalSize = AcpiGbl_AmlResourceSerialBusSizes [Resource->Data.CommonSerialBus.Type];
+
+            TotalSize = (ACPI_RS_LENGTH) (TotalSize +
+                Resource->Data.I2cSerialBus.ResourceSource.StringLength +
+                Resource->Data.I2cSerialBus.VendorLength);
+
+            break;
+
+
         default:
             break;
         }
@@ -395,12 +415,13 @@
     UINT32                  ExtraStructBytes;
     UINT8                   ResourceIndex;
     UINT8                   MinimumAmlResourceLength;
+    AML_RESOURCE            *AmlResource;
 
 
     ACPI_FUNCTION_TRACE (RsGetListLength);
 
 
-    *SizeNeeded = 0;
+    *SizeNeeded = ACPI_RS_SIZE_MIN;         /* Minimum size is one EndTag */
     EndAml = AmlBuffer + AmlBufferLength;
 
     /* Walk the list of AML resource descriptors */
@@ -412,9 +433,15 @@
         Status = AcpiUtValidateResource (AmlBuffer, &ResourceIndex);
         if (ACPI_FAILURE (Status))
         {
+            /*
+             * Exit on failure. Cannot continue because the descriptor length
+             * may be bogus also.
+             */
             return_ACPI_STATUS (Status);
         }
 
+        AmlResource = (void *) AmlBuffer;
+
         /* Get the resource length and base (minimum) AML size */
 
         ResourceLength = AcpiUtGetResourceLength (AmlBuffer);
@@ -460,10 +487,8 @@
 
         case ACPI_RESOURCE_NAME_END_TAG:
             /*
-             * End Tag:
-             * This is the normal exit, add size of EndTag
+             * End Tag: This is the normal exit
              */
-            *SizeNeeded += ACPI_RS_SIZE_MIN;
             return_ACPI_STATUS (AE_OK);
 
 
@@ -494,6 +519,30 @@
                 ResourceLength - ExtraStructBytes, MinimumAmlResourceLength);
             break;
 
+        case ACPI_RESOURCE_NAME_GPIO:
+
+            /* Vendor data is optional */
+
+            if (AmlResource->Gpio.VendorLength)
+            {
+                ExtraStructBytes += AmlResource->Gpio.VendorOffset -
+                    AmlResource->Gpio.PinTableOffset + AmlResource->Gpio.VendorLength;
+            }
+            else
+            {
+                ExtraStructBytes += AmlResource->LargeHeader.ResourceLength +
+                    sizeof (AML_RESOURCE_LARGE_HEADER) -
+                    AmlResource->Gpio.PinTableOffset;
+            }
+            break;
+
+        case ACPI_RESOURCE_NAME_SERIAL_BUS:
+
+            MinimumAmlResourceLength = AcpiGbl_ResourceAmlSerialBusSizes[
+                AmlResource->CommonSerialBus.Type];
+            ExtraStructBytes += AmlResource->CommonSerialBus.ResourceLength -
+                MinimumAmlResourceLength;
+            break;
 
         default:
             break;
@@ -505,8 +554,16 @@
          * Important: Round the size up for the appropriate alignment. This
          * is a requirement on IA64.
          */
-        BufferSize = AcpiGbl_ResourceStructSizes[ResourceIndex] +
+        if (AcpiUtGetResourceType (AmlBuffer) == ACPI_RESOURCE_NAME_SERIAL_BUS)
+        {
+            BufferSize = AcpiGbl_ResourceStructSerialBusSizes[
+                AmlResource->CommonSerialBus.Type] + ExtraStructBytes;
+        }
+        else
+        {
+            BufferSize = AcpiGbl_ResourceStructSizes[ResourceIndex] +
                         ExtraStructBytes;
+        }
         BufferSize = (UINT32) ACPI_ROUND_UP_TO_NATIVE_WORD (BufferSize);
 
         *SizeNeeded += BufferSize;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/resources/rscreate.c
--- a/head/sys/contrib/dev/acpica/resources/rscreate.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/resources/rscreate.c	Tue Dec 06 20:26:16 2011 +0200
@@ -54,6 +54,79 @@
 
 /*******************************************************************************
  *
+ * FUNCTION:    AcpiBufferToResource
+ *
+ * PARAMETERS:  AmlBuffer           - Pointer to the resource byte stream
+ *              AmlBufferLength     - Length of the AmlBuffer
+ *              ResourcePtr         - Where the converted resource is returned
+ *
+ * RETURN:      Status
+ *
+ * DESCRIPTION: Convert a raw AML buffer to a resource list
+ *
+ ******************************************************************************/
+
+ACPI_STATUS
+AcpiBufferToResource (
+    UINT8                   *AmlBuffer,
+    UINT16                  AmlBufferLength,
+    ACPI_RESOURCE           **ResourcePtr)
+{
+    ACPI_STATUS             Status;
+    ACPI_SIZE               ListSizeNeeded;
+    void                    *Resource;
+    void                    *CurrentResourcePtr;
+
+    /*
+     * Note: we allow AE_AML_NO_RESOURCE_END_TAG, since an end tag
+     * is not required here.
+     */
+
+    /* Get the required length for the converted resource */
+
+    Status = AcpiRsGetListLength (AmlBuffer, AmlBufferLength,
+                &ListSizeNeeded);
+    if (Status == AE_AML_NO_RESOURCE_END_TAG)
+    {
+        Status = AE_OK;
+    }
+    if (ACPI_FAILURE (Status))
+    {
+        return (Status);
+    }
+
+    /* Allocate a buffer for the converted resource */
+
+    Resource = ACPI_ALLOCATE_ZEROED (ListSizeNeeded);
+    CurrentResourcePtr = Resource;
+    if (!Resource)
+    {
+        return (AE_NO_MEMORY);
+    }
+
+    /* Perform the AML-to-Resource conversion */
+
+    Status = AcpiUtWalkAmlResources (AmlBuffer, AmlBufferLength,
+                AcpiRsConvertAmlToResources, &CurrentResourcePtr);
+    if (Status == AE_AML_NO_RESOURCE_END_TAG)
+    {
+        Status = AE_OK;
+    }
+    if (ACPI_FAILURE (Status))
+    {
+        ACPI_FREE (Resource);
+    }
+    else
+    {
+        *ResourcePtr = Resource;
+    }
+
+    return (Status);
+}
+
+
+/*******************************************************************************
+ *
  * FUNCTION:    AcpiRsCreateResourceList
  *
  * PARAMETERS:  AmlBuffer           - Pointer to the resource byte stream
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/resources/rsdump.c
--- a/head/sys/contrib/dev/acpica/resources/rsdump.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/resources/rsdump.c	Tue Dec 06 20:26:16 2011 +0200
@@ -91,6 +91,11 @@
     UINT8                   *Data);
 
 static void
+AcpiRsDumpWordList (
+    UINT16                   Length,
+    UINT16                   *Data);
+
+static void
 AcpiRsDumpDwordList (
     UINT8                   Length,
     UINT32                  *Data);
@@ -289,6 +294,87 @@
     {ACPI_RSD_UINT64,   ACPI_RSD_OFFSET (GenericReg.Address),               "Address",                  NULL}
 };
 
+ACPI_RSDUMP_INFO        AcpiRsDumpGpio[16] =
+{
+    {ACPI_RSD_TITLE,    ACPI_RSD_TABLE_SIZE (AcpiRsDumpGpio),               "GPIO",                     NULL},
+    {ACPI_RSD_UINT8,    ACPI_RSD_OFFSET (Gpio.RevisionId),                  "RevisionId",               NULL},
+    {ACPI_RSD_UINT8,    ACPI_RSD_OFFSET (Gpio.ConnectionType),              "ConnectionType",           AcpiGbl_CtDecode},
+    {ACPI_RSD_1BITFLAG, ACPI_RSD_OFFSET (Gpio.ProducerConsumer),            "ProducerConsumer",         AcpiGbl_ConsumeDecode},
+    {ACPI_RSD_UINT8,    ACPI_RSD_OFFSET (Gpio.PinConfig),                   "PinConfig",                AcpiGbl_PpcDecode},
+    {ACPI_RSD_2BITFLAG, ACPI_RSD_OFFSET (Gpio.Sharable),                    "Sharable",                 AcpiGbl_ShrDecode},
+    {ACPI_RSD_2BITFLAG, ACPI_RSD_OFFSET (Gpio.IoRestriction),               "IoRestriction",            AcpiGbl_IorDecode},
+    {ACPI_RSD_1BITFLAG, ACPI_RSD_OFFSET (Gpio.Triggering),                  "Triggering",               AcpiGbl_HeDecode},
+    {ACPI_RSD_2BITFLAG, ACPI_RSD_OFFSET (Gpio.Polarity),                    "Polarity",                 AcpiGbl_LlDecode},
+    {ACPI_RSD_UINT16,   ACPI_RSD_OFFSET (Gpio.DriveStrength),               "DriveStrength",            NULL},
+    {ACPI_RSD_UINT16,   ACPI_RSD_OFFSET (Gpio.DebounceTimeout),             "DebounceTimeout",          NULL},
+    {ACPI_RSD_SOURCE,   ACPI_RSD_OFFSET (Gpio.ResourceSource),              "ResourceSource",           NULL},
+    {ACPI_RSD_UINT16,   ACPI_RSD_OFFSET (Gpio.PinTableLength),              "PinTableLength",           NULL},
+    {ACPI_RSD_WORDLIST, ACPI_RSD_OFFSET (Gpio.PinTable),                    "PinTable",                 NULL},
+    {ACPI_RSD_UINT16,   ACPI_RSD_OFFSET (Gpio.VendorLength),                "VendorLength",             NULL},
+    {ACPI_RSD_SHORTLISTX,ACPI_RSD_OFFSET (Gpio.VendorData),                 "VendorData",               NULL},
+};
+
+ACPI_RSDUMP_INFO        AcpiRsDumpFixedDma[4] =
+{
+    {ACPI_RSD_TITLE,    ACPI_RSD_TABLE_SIZE (AcpiRsDumpFixedDma),           "FixedDma",                 NULL},
+    {ACPI_RSD_UINT16,   ACPI_RSD_OFFSET (FixedDma.RequestLines),            "RequestLines",             NULL},
+    {ACPI_RSD_UINT16,   ACPI_RSD_OFFSET (FixedDma.Channels),                "Channels",                 NULL},
+    {ACPI_RSD_UINT8,    ACPI_RSD_OFFSET (FixedDma.Width),                   "TransferWidth",            AcpiGbl_DtsDecode},
+};
+
+#define ACPI_RS_DUMP_COMMON_SERIAL_BUS \
+    {ACPI_RSD_UINT8,    ACPI_RSD_OFFSET (CommonSerialBus.RevisionId),       "RevisionId",               NULL}, \
+    {ACPI_RSD_UINT8,    ACPI_RSD_OFFSET (CommonSerialBus.Type),             "Type",                     AcpiGbl_SbtDecode}, \
+    {ACPI_RSD_1BITFLAG, ACPI_RSD_OFFSET (CommonSerialBus.ProducerConsumer), "ProducerConsumer",         AcpiGbl_ConsumeDecode}, \
+    {ACPI_RSD_1BITFLAG, ACPI_RSD_OFFSET (CommonSerialBus.SlaveMode),        "SlaveMode",                AcpiGbl_SmDecode}, \
+    {ACPI_RSD_UINT8,    ACPI_RSD_OFFSET (CommonSerialBus.TypeRevisionId),   "TypeRevisionId",           NULL}, \
+    {ACPI_RSD_UINT16,   ACPI_RSD_OFFSET (CommonSerialBus.TypeDataLength),   "TypeDataLength",           NULL}, \
+    {ACPI_RSD_SOURCE,   ACPI_RSD_OFFSET (CommonSerialBus.ResourceSource),   "ResourceSource",           NULL}, \
+    {ACPI_RSD_UINT16,   ACPI_RSD_OFFSET (CommonSerialBus.VendorLength),     "VendorLength",             NULL}, \
+    {ACPI_RSD_SHORTLISTX,ACPI_RSD_OFFSET (CommonSerialBus.VendorData),      "VendorData",               NULL},
+
+ACPI_RSDUMP_INFO        AcpiRsDumpCommonSerialBus[10] =
+{
+    {ACPI_RSD_TITLE,    ACPI_RSD_TABLE_SIZE (AcpiRsDumpCommonSerialBus),    "Common Serial Bus",        NULL},
+    ACPI_RS_DUMP_COMMON_SERIAL_BUS
+};
+
+ACPI_RSDUMP_INFO        AcpiRsDumpI2cSerialBus[13] =
+{
+    {ACPI_RSD_TITLE,    ACPI_RSD_TABLE_SIZE (AcpiRsDumpI2cSerialBus),       "I2C Serial Bus",           NULL},
+    ACPI_RS_DUMP_COMMON_SERIAL_BUS
+    {ACPI_RSD_1BITFLAG, ACPI_RSD_OFFSET (I2cSerialBus.AccessMode),          "AccessMode",               AcpiGbl_AmDecode},
+    {ACPI_RSD_UINT32,   ACPI_RSD_OFFSET (I2cSerialBus.ConnectionSpeed),     "ConnectionSpeed",          NULL},
+    {ACPI_RSD_UINT16,   ACPI_RSD_OFFSET (I2cSerialBus.SlaveAddress),        "SlaveAddress",             NULL},
+};
+
+ACPI_RSDUMP_INFO        AcpiRsDumpSpiSerialBus[17] =
+{
+    {ACPI_RSD_TITLE,    ACPI_RSD_TABLE_SIZE (AcpiRsDumpSpiSerialBus),       "Spi Serial Bus",           NULL},
+    ACPI_RS_DUMP_COMMON_SERIAL_BUS
+    {ACPI_RSD_1BITFLAG, ACPI_RSD_OFFSET (SpiSerialBus.WireMode),            "WireMode",                 AcpiGbl_WmDecode},
+    {ACPI_RSD_1BITFLAG, ACPI_RSD_OFFSET (SpiSerialBus.DevicePolarity),      "DevicePolarity",           AcpiGbl_DpDecode},
+    {ACPI_RSD_UINT8,    ACPI_RSD_OFFSET (SpiSerialBus.DataBitLength),       "DataBitLength",            NULL},
+    {ACPI_RSD_UINT8,    ACPI_RSD_OFFSET (SpiSerialBus.ClockPhase),          "ClockPhase",               AcpiGbl_CphDecode},
+    {ACPI_RSD_UINT8,    ACPI_RSD_OFFSET (SpiSerialBus.ClockPolarity),       "ClockPolarity",            AcpiGbl_CpoDecode},
+    {ACPI_RSD_UINT16,   ACPI_RSD_OFFSET (SpiSerialBus.DeviceSelection),     "DeviceSelection",          NULL},
+    {ACPI_RSD_UINT32,   ACPI_RSD_OFFSET (SpiSerialBus.ConnectionSpeed),     "ConnectionSpeed",          NULL},
+};
+
+ACPI_RSDUMP_INFO        AcpiRsDumpUartSerialBus[19] =
+{
+    {ACPI_RSD_TITLE,    ACPI_RSD_TABLE_SIZE (AcpiRsDumpUartSerialBus),       "Uart Serial Bus",         NULL},
+    ACPI_RS_DUMP_COMMON_SERIAL_BUS
+    {ACPI_RSD_2BITFLAG, ACPI_RSD_OFFSET (UartSerialBus.FlowControl),         "FlowControl",             AcpiGbl_FcDecode},
+    {ACPI_RSD_2BITFLAG, ACPI_RSD_OFFSET (UartSerialBus.StopBits),            "StopBits",                AcpiGbl_SbDecode},
+    {ACPI_RSD_3BITFLAG, ACPI_RSD_OFFSET (UartSerialBus.DataBits),            "DataBits",                AcpiGbl_BpbDecode},
+    {ACPI_RSD_1BITFLAG, ACPI_RSD_OFFSET (UartSerialBus.Endian),              "Endian",                  AcpiGbl_EdDecode},
+    {ACPI_RSD_UINT8,    ACPI_RSD_OFFSET (UartSerialBus.Parity),              "Parity",                  AcpiGbl_PtDecode},
+    {ACPI_RSD_UINT8,    ACPI_RSD_OFFSET (UartSerialBus.LinesEnabled),        "LinesEnabled",            NULL},
+    {ACPI_RSD_UINT16,   ACPI_RSD_OFFSET (UartSerialBus.RxFifoSize),          "RxFifoSize",              NULL},
+    {ACPI_RSD_UINT16,   ACPI_RSD_OFFSET (UartSerialBus.TxFifoSize),          "TxFifoSize",              NULL},
+    {ACPI_RSD_UINT32,   ACPI_RSD_OFFSET (UartSerialBus.DefaultBaudRate),     "ConnectionSpeed",         NULL},
+};
 
 /*
  * Tables used for common address descriptor flag fields
@@ -391,7 +477,15 @@
         /* Data items, 8/16/32/64 bit */
 
         case ACPI_RSD_UINT8:
-            AcpiRsOutInteger8 (Name, ACPI_GET8 (Target));
+            if (Table->Pointer)
+            {
+                AcpiRsOutString (Name, ACPI_CAST_PTR (char,
+                    Table->Pointer [*Target]));
+            }
+            else
+            {
+                AcpiRsOutInteger8 (Name, ACPI_GET8 (Target));
+            }
             break;
 
         case ACPI_RSD_UINT16:
@@ -418,6 +512,11 @@
                 Table->Pointer [*Target & 0x03]));
             break;
 
+        case ACPI_RSD_3BITFLAG:
+            AcpiRsOutString (Name, ACPI_CAST_PTR (char,
+                Table->Pointer [*Target & 0x07]));
+            break;
+
         case ACPI_RSD_SHORTLIST:
             /*
              * Short byte list (single line output) for DMA and IRQ resources
@@ -430,6 +529,19 @@
             }
             break;
 
+        case ACPI_RSD_SHORTLISTX:
+            /*
+             * Short byte list (single line output) for GPIO vendor data
+             * Note: The list length is obtained from the previous table entry
+             */
+            if (PreviousTarget)
+            {
+                AcpiRsOutTitle (Name);
+                AcpiRsDumpShortByteList (*PreviousTarget,
+                    *(ACPI_CAST_INDIRECT_PTR (UINT8, Target)));
+            }
+            break;
+
         case ACPI_RSD_LONGLIST:
             /*
              * Long byte list for Vendor resource data
@@ -453,6 +565,18 @@
             }
             break;
 
+        case ACPI_RSD_WORDLIST:
+            /*
+             * Word list for GPIO Pin Table
+             * Note: The list length is obtained from the previous table entry
+             */
+            if (PreviousTarget)
+            {
+                AcpiRsDumpWordList (*PreviousTarget,
+                    *(ACPI_CAST_INDIRECT_PTR (UINT16, Target)));
+            }
+            break;
+
         case ACPI_RSD_ADDRESS:
             /*
              * Common flags for all Address resources
@@ -613,13 +737,20 @@
 
         /* Dump the resource descriptor */
 
-        AcpiRsDumpDescriptor (&ResourceList->Data,
-            AcpiGbl_DumpResourceDispatch[Type]);
+        if (Type == ACPI_RESOURCE_TYPE_SERIAL_BUS)
+        {
+            AcpiRsDumpDescriptor (&ResourceList->Data,
+                AcpiGbl_DumpSerialBusDispatch[ResourceList->Data.CommonSerialBus.Type]);
+        }
+        else
+        {
+            AcpiRsDumpDescriptor (&ResourceList->Data,
+                AcpiGbl_DumpResourceDispatch[Type]);
+        }
 
         /* Point to the next resource structure */
 
-        ResourceList = ACPI_ADD_PTR (ACPI_RESOURCE, ResourceList,
-                            ResourceList->Length);
+        ResourceList = ACPI_NEXT_RESOURCE (ResourceList);
 
         /* Exit when END_TAG descriptor is reached */
 
@@ -796,5 +927,20 @@
     }
 }
 
+static void
+AcpiRsDumpWordList (
+    UINT16                  Length,
+    UINT16                  *Data)
+{
+    UINT16                  i;
+
+
+    for (i = 0; i < Length; i++)
+    {
+        AcpiOsPrintf ("%25s%2.2X : %4.4X\n",
+            "Word", i, Data[i]);
+    }
+}
+
 #endif
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/resources/rsinfo.c
--- a/head/sys/contrib/dev/acpica/resources/rsinfo.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/resources/rsinfo.c	Tue Dec 06 20:26:16 2011 +0200
@@ -82,7 +82,10 @@
     AcpiRsConvertAddress64,         /* 0x0D, ACPI_RESOURCE_TYPE_ADDRESS64 */
     AcpiRsConvertExtAddress64,      /* 0x0E, ACPI_RESOURCE_TYPE_EXTENDED_ADDRESS64 */
     AcpiRsConvertExtIrq,            /* 0x0F, ACPI_RESOURCE_TYPE_EXTENDED_IRQ */
-    AcpiRsConvertGenericReg         /* 0x10, ACPI_RESOURCE_TYPE_GENERIC_REGISTER */
+    AcpiRsConvertGenericReg,        /* 0x10, ACPI_RESOURCE_TYPE_GENERIC_REGISTER */
+    AcpiRsConvertGpio,              /* 0x11, ACPI_RESOURCE_TYPE_GPIO */
+    AcpiRsConvertFixedDma,          /* 0x12, ACPI_RESOURCE_TYPE_FIXED_DMA */
+    NULL,                           /* 0x13, ACPI_RESOURCE_TYPE_SERIAL_BUS - Use subtype table below */
 };
 
 /* Dispatch tables for AML-to-resource (Get Resource) conversion functions */
@@ -101,7 +104,7 @@
     AcpiRsConvertEndDpf,            /* 0x07, ACPI_RESOURCE_NAME_END_DEPENDENT */
     AcpiRsConvertIo,                /* 0x08, ACPI_RESOURCE_NAME_IO */
     AcpiRsConvertFixedIo,           /* 0x09, ACPI_RESOURCE_NAME_FIXED_IO */
-    NULL,                           /* 0x0A, Reserved */
+    AcpiRsConvertFixedDma,          /* 0x0A, ACPI_RESOURCE_NAME_FIXED_DMA */
     NULL,                           /* 0x0B, Reserved */
     NULL,                           /* 0x0C, Reserved */
     NULL,                           /* 0x0D, Reserved */
@@ -121,7 +124,20 @@
     AcpiRsConvertAddress16,         /* 0x08, ACPI_RESOURCE_NAME_ADDRESS16 */
     AcpiRsConvertExtIrq,            /* 0x09, ACPI_RESOURCE_NAME_EXTENDED_IRQ */
     AcpiRsConvertAddress64,         /* 0x0A, ACPI_RESOURCE_NAME_ADDRESS64 */
-    AcpiRsConvertExtAddress64       /* 0x0B, ACPI_RESOURCE_NAME_EXTENDED_ADDRESS64 */
+    AcpiRsConvertExtAddress64,      /* 0x0B, ACPI_RESOURCE_NAME_EXTENDED_ADDRESS64 */
+    AcpiRsConvertGpio,              /* 0x0C, ACPI_RESOURCE_NAME_GPIO */
+    NULL,                           /* 0x0D, Reserved */
+    NULL,                           /* 0x0E, ACPI_RESOURCE_NAME_SERIAL_BUS - Use subtype table below */
+};
+
+/* Subtype table for SerialBus -- I2C, SPI, and UART */
+
+ACPI_RSCONVERT_INFO         *AcpiGbl_ConvertResourceSerialBusDispatch[] =
+{
+    NULL,
+    AcpiRsConvertI2cSerialBus,
+    AcpiRsConvertSpiSerialBus,
+    AcpiRsConvertUartSerialBus,
 };
 
 
@@ -148,6 +164,17 @@
     AcpiRsDumpExtAddress64,         /* ACPI_RESOURCE_TYPE_EXTENDED_ADDRESS64 */
     AcpiRsDumpExtIrq,               /* ACPI_RESOURCE_TYPE_EXTENDED_IRQ */
     AcpiRsDumpGenericReg,           /* ACPI_RESOURCE_TYPE_GENERIC_REGISTER */
+    AcpiRsDumpGpio,                 /* ACPI_RESOURCE_TYPE_GPIO */
+    AcpiRsDumpFixedDma,             /* ACPI_RESOURCE_TYPE_FIXED_DMA */
+    NULL,                           /* ACPI_RESOURCE_TYPE_SERIAL_BUS */
+};
+
+ACPI_RSDUMP_INFO            *AcpiGbl_DumpSerialBusDispatch[] =
+{
+    NULL,
+    AcpiRsDumpI2cSerialBus,         /* AML_RESOURCE_I2C_BUS_TYPE */
+    AcpiRsDumpSpiSerialBus,         /* AML_RESOURCE_SPI_BUS_TYPE */
+    AcpiRsDumpUartSerialBus,        /* AML_RESOURCE_UART_BUS_TYPE */
 };
 #endif
 
@@ -175,7 +202,10 @@
     sizeof (AML_RESOURCE_ADDRESS64),        /* ACPI_RESOURCE_TYPE_ADDRESS64 */
     sizeof (AML_RESOURCE_EXTENDED_ADDRESS64),/*ACPI_RESOURCE_TYPE_EXTENDED_ADDRESS64 */
     sizeof (AML_RESOURCE_EXTENDED_IRQ),     /* ACPI_RESOURCE_TYPE_EXTENDED_IRQ */
-    sizeof (AML_RESOURCE_GENERIC_REGISTER)  /* ACPI_RESOURCE_TYPE_GENERIC_REGISTER */
+    sizeof (AML_RESOURCE_GENERIC_REGISTER), /* ACPI_RESOURCE_TYPE_GENERIC_REGISTER */
+    sizeof (AML_RESOURCE_GPIO),             /* ACPI_RESOURCE_TYPE_GPIO */
+    sizeof (AML_RESOURCE_FIXED_DMA),        /* ACPI_RESOURCE_TYPE_FIXED_DMA */
+    sizeof (AML_RESOURCE_COMMON_SERIALBUS), /* ACPI_RESOURCE_TYPE_SERIAL_BUS */
 };
 
 
@@ -193,7 +223,7 @@
     ACPI_RS_SIZE_MIN,
     ACPI_RS_SIZE (ACPI_RESOURCE_IO),
     ACPI_RS_SIZE (ACPI_RESOURCE_FIXED_IO),
-    0,
+    ACPI_RS_SIZE (ACPI_RESOURCE_FIXED_DMA),
     0,
     0,
     0,
@@ -213,6 +243,23 @@
     ACPI_RS_SIZE (ACPI_RESOURCE_ADDRESS16),
     ACPI_RS_SIZE (ACPI_RESOURCE_EXTENDED_IRQ),
     ACPI_RS_SIZE (ACPI_RESOURCE_ADDRESS64),
-    ACPI_RS_SIZE (ACPI_RESOURCE_EXTENDED_ADDRESS64)
+    ACPI_RS_SIZE (ACPI_RESOURCE_EXTENDED_ADDRESS64),
+    ACPI_RS_SIZE (ACPI_RESOURCE_GPIO),
+    ACPI_RS_SIZE (ACPI_RESOURCE_COMMON_SERIALBUS)
 };
 
+const UINT8                 AcpiGbl_AmlResourceSerialBusSizes[] =
+{
+    0,
+    sizeof (AML_RESOURCE_I2C_SERIALBUS),
+    sizeof (AML_RESOURCE_SPI_SERIALBUS),
+    sizeof (AML_RESOURCE_UART_SERIALBUS),
+};
+
+const UINT8                 AcpiGbl_ResourceStructSerialBusSizes[] =
+{
+    0,
+    ACPI_RS_SIZE (ACPI_RESOURCE_I2C_SERIALBUS),
+    ACPI_RS_SIZE (ACPI_RESOURCE_SPI_SERIALBUS),
+    ACPI_RS_SIZE (ACPI_RESOURCE_UART_SERIALBUS),
+};
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/resources/rsirq.c
--- a/head/sys/contrib/dev/acpica/resources/rsirq.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/resources/rsirq.c	Tue Dec 06 20:26:16 2011 +0200
@@ -274,3 +274,35 @@
                         ACPI_RS_OFFSET (Data.Dma.ChannelCount)}
 };
 
+
+/*******************************************************************************
+ *
+ * AcpiRsConvertFixedDma
+ *
+ ******************************************************************************/
+
+ACPI_RSCONVERT_INFO     AcpiRsConvertFixedDma[4] =
+{
+    {ACPI_RSC_INITGET,  ACPI_RESOURCE_TYPE_FIXED_DMA,
+                        ACPI_RS_SIZE (ACPI_RESOURCE_FIXED_DMA),
+                        ACPI_RSC_TABLE_SIZE (AcpiRsConvertFixedDma)},
+
+    {ACPI_RSC_INITSET,  ACPI_RESOURCE_NAME_FIXED_DMA,
+                        sizeof (AML_RESOURCE_FIXED_DMA),
+                        0},
+
+    /*
+     * These fields are contiguous in both the source and destination:
+     * RequestLines
+     * Channels
+     */
+
+    {ACPI_RSC_MOVE16,   ACPI_RS_OFFSET (Data.FixedDma.RequestLines),
+                        AML_OFFSET (FixedDma.RequestLines),
+                        2},
+
+    {ACPI_RSC_MOVE8,    ACPI_RS_OFFSET (Data.FixedDma.Width),
+                        AML_OFFSET (FixedDma.Width),
+                        1},
+
+};
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/resources/rslist.c
--- a/head/sys/contrib/dev/acpica/resources/rslist.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/resources/rslist.c	Tue Dec 06 20:26:16 2011 +0200
@@ -77,6 +77,8 @@
     ACPI_RESOURCE           **ResourcePtr = ACPI_CAST_INDIRECT_PTR (
                                 ACPI_RESOURCE, Context);
     ACPI_RESOURCE           *Resource;
+    AML_RESOURCE            *AmlResource;
+    ACPI_RSCONVERT_INFO     *ConversionTable;
     ACPI_STATUS             Status;
 
 
@@ -94,11 +96,42 @@
             "Misaligned resource pointer %p", Resource));
     }
 
-    /* Convert the AML byte stream resource to a local resource struct */
+    /* Get the appropriate conversion info table */
+
+    AmlResource = ACPI_CAST_PTR (AML_RESOURCE, Aml);
+    if (AcpiUtGetResourceType (Aml) == ACPI_RESOURCE_NAME_SERIAL_BUS)
+    {
+        if (AmlResource->CommonSerialBus.Type > AML_RESOURCE_MAX_SERIALBUSTYPE)
+        {
+            ConversionTable = NULL;
+        }
+        else
+        {
+            /* This is an I2C, SPI, or UART SerialBus descriptor */
+
+            ConversionTable =
+                AcpiGbl_ConvertResourceSerialBusDispatch[
+                    AmlResource->CommonSerialBus.Type];
+        }
+    }
+    else
+    {
+        ConversionTable =
+            AcpiGbl_GetResourceDispatch[ResourceIndex];
+    }
+
+    if (!ConversionTable)
+    {
+        ACPI_ERROR ((AE_INFO,
+            "Invalid/unsupported resource descriptor: Type 0x%2.2X",
+            ResourceIndex));
+        return (AE_AML_INVALID_RESOURCE_TYPE);
+    }
+
+     /* Convert the AML byte stream resource to a local resource struct */
 
     Status = AcpiRsConvertAmlToResource (
-                Resource, ACPI_CAST_PTR (AML_RESOURCE, Aml),
-                AcpiGbl_GetResourceDispatch[ResourceIndex]);
+        Resource, AmlResource, ConversionTable);
     if (ACPI_FAILURE (Status))
     {
         ACPI_EXCEPTION ((AE_INFO, Status,
@@ -113,7 +146,7 @@
 
     /* Point to the next structure in the output buffer */
 
-    *ResourcePtr = ACPI_ADD_PTR (void, Resource, Resource->Length);
+    *ResourcePtr = ACPI_NEXT_RESOURCE (Resource);
     return_ACPI_STATUS (AE_OK);
 }
 
@@ -145,6 +178,7 @@
 {
     UINT8                   *Aml = OutputBuffer;
     UINT8                   *EndAml = OutputBuffer + AmlSizeNeeded;
+    ACPI_RSCONVERT_INFO     *ConversionTable;
     ACPI_STATUS             Status;
 
 
@@ -167,9 +201,36 @@
 
         /* Perform the conversion */
 
+        if (Resource->Type == ACPI_RESOURCE_TYPE_SERIAL_BUS)
+        {
+            if (Resource->Data.CommonSerialBus.Type > AML_RESOURCE_MAX_SERIALBUSTYPE)
+            {
+                ConversionTable = NULL;
+            }
+            else
+            {
+                /* This is an I2C, SPI, or UART SerialBus descriptor */
+
+                ConversionTable = AcpiGbl_ConvertResourceSerialBusDispatch[
+                    Resource->Data.CommonSerialBus.Type];
+            }
+        }
+        else
+        {
+            ConversionTable = AcpiGbl_SetResourceDispatch[Resource->Type];
+        }
+
+        if (!ConversionTable)
+        {
+            ACPI_ERROR ((AE_INFO,
+                "Invalid/unsupported resource descriptor: Type 0x%2.2X",
+                Resource->Type));
+            return (AE_AML_INVALID_RESOURCE_TYPE);
+        }
+
         Status = AcpiRsConvertResourceToAml (Resource,
-                    ACPI_CAST_PTR (AML_RESOURCE, Aml),
-                    AcpiGbl_SetResourceDispatch[Resource->Type]);
+                ACPI_CAST_PTR (AML_RESOURCE, Aml),
+                ConversionTable);
         if (ACPI_FAILURE (Status))
         {
             ACPI_EXCEPTION ((AE_INFO, Status,
@@ -204,7 +265,7 @@
 
         /* Point to the next input resource descriptor */
 
-        Resource = ACPI_ADD_PTR (ACPI_RESOURCE, Resource, Resource->Length);
+        Resource = ACPI_NEXT_RESOURCE (Resource);
     }
 
     /* Completed buffer, but did not find an EndTag resource descriptor */
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/resources/rsmisc.c
--- a/head/sys/contrib/dev/acpica/resources/rsmisc.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/resources/rsmisc.c	Tue Dec 06 20:26:16 2011 +0200
@@ -94,6 +94,11 @@
     ACPI_FUNCTION_TRACE (RsConvertAmlToResource);
 
 
+    if (!Info)
+    {
+        return_ACPI_STATUS (AE_BAD_PARAMETER);
+    }
+
     if (((ACPI_SIZE) Resource) & 0x3)
     {
         /* Each internal resource struct is expected to be 32-bit aligned */
@@ -112,7 +117,6 @@
      * table length (# of table entries)
      */
     Count = INIT_TABLE_LENGTH (Info);
-
     while (Count)
     {
         /*
@@ -162,6 +166,15 @@
             break;
 
 
+        case ACPI_RSC_3BITFLAG:
+            /*
+             * Mask and shift the flag bits
+             */
+            ACPI_SET8 (Destination) = (UINT8)
+                ((ACPI_GET8 (Source) >> Info->Value) & 0x07);
+            break;
+
+
         case ACPI_RSC_COUNT:
 
             ItemCount = ACPI_GET8 (Source);
@@ -182,6 +195,75 @@
             break;
 
 
+        case ACPI_RSC_COUNT_GPIO_PIN:
+
+            Target = ACPI_ADD_PTR (void, Aml, Info->Value);
+            ItemCount = ACPI_GET16 (Target) - ACPI_GET16 (Source);
+
+            Resource->Length = Resource->Length + ItemCount;
+            ItemCount = ItemCount / 2;
+            ACPI_SET16 (Destination) = ItemCount;
+            break;
+
+
+        case ACPI_RSC_COUNT_GPIO_VEN:
+
+            ItemCount = ACPI_GET8 (Source);
+            ACPI_SET8 (Destination) = (UINT8) ItemCount;
+
+            Resource->Length = Resource->Length +
+                (Info->Value * ItemCount);
+            break;
+
+
+        case ACPI_RSC_COUNT_GPIO_RES:
+
+            /*
+             * Vendor data is optional (length/offset may both be zero)
+             * Examine vendor data length field first
+             */
+            Target = ACPI_ADD_PTR (void, Aml, (Info->Value + 2));
+            if (ACPI_GET16 (Target))
+            {
+                /* Use vendor offset to get resource source length */
+
+                Target = ACPI_ADD_PTR (void, Aml, Info->Value);
+                ItemCount = ACPI_GET16 (Target) - ACPI_GET16 (Source);
+            }
+            else
+            {
+                /* No vendor data to worry about */
+
+                ItemCount = Aml->LargeHeader.ResourceLength +
+                    sizeof (AML_RESOURCE_LARGE_HEADER) -
+                    ACPI_GET16 (Source);
+            }
+
+            Resource->Length = Resource->Length + ItemCount;
+            ACPI_SET16 (Destination) = ItemCount;
+            break;
+
+
+        case ACPI_RSC_COUNT_SERIAL_VEN:
+
+            ItemCount = ACPI_GET16 (Source) - Info->Value;
+
+            Resource->Length = Resource->Length + ItemCount;
+            ACPI_SET16 (Destination) = ItemCount;
+            break;
+
+
+        case ACPI_RSC_COUNT_SERIAL_RES:
+
+            ItemCount = (AmlResourceLength +
+                sizeof (AML_RESOURCE_LARGE_HEADER)) -
+                ACPI_GET16 (Source) - Info->Value;
+
+            Resource->Length = Resource->Length + ItemCount;
+            ACPI_SET16 (Destination) = ItemCount;
+            break;
+
+
         case ACPI_RSC_LENGTH:
 
             Resource->Length = Resource->Length + Info->Value;
@@ -204,6 +286,66 @@
             break;
 
 
+        case ACPI_RSC_MOVE_GPIO_PIN:
+
+            /* Generate and set the PIN data pointer */
+
+            Target = (char *) ACPI_ADD_PTR (void, Resource,
+                  (Resource->Length - ItemCount * 2));
+            *(UINT16 **) Destination = ACPI_CAST_PTR (UINT16, Target);
+
+            /* Copy the PIN data */
+
+            Source = ACPI_ADD_PTR (void, Aml, ACPI_GET16 (Source));
+            AcpiRsMoveData (Target, Source, ItemCount, Info->Opcode);
+            break;
+
+
+        case ACPI_RSC_MOVE_GPIO_RES:
+
+            /* Generate and set the ResourceSource string pointer */
+
+            Target = (char *) ACPI_ADD_PTR (void, Resource,
+                  (Resource->Length - ItemCount));
+            *(UINT8 **) Destination = ACPI_CAST_PTR (UINT8, Target);
+
+            /* Copy the ResourceSource string */
+
+            Source = ACPI_ADD_PTR (void, Aml, ACPI_GET16 (Source));
+            AcpiRsMoveData (Target, Source, ItemCount, Info->Opcode);
+            break;
+
+
+        case ACPI_RSC_MOVE_SERIAL_VEN:
+
+            /* Generate and set the Vendor Data pointer */
+
+            Target = (char *) ACPI_ADD_PTR (void, Resource,
+                  (Resource->Length - ItemCount));
+            *(UINT8 **) Destination = ACPI_CAST_PTR (UINT8, Target);
+
+            /* Copy the Vendor Data */
+
+            Source = ACPI_ADD_PTR (void, Aml, Info->Value);
+            AcpiRsMoveData (Target, Source, ItemCount, Info->Opcode);
+            break;
+
+
+        case ACPI_RSC_MOVE_SERIAL_RES:
+
+            /* Generate and set the ResourceSource string pointer */
+
+            Target = (char *) ACPI_ADD_PTR (void, Resource,
+                  (Resource->Length - ItemCount));
+            *(UINT8 **) Destination = ACPI_CAST_PTR (UINT8, Target);
+
+            /* Copy the ResourceSource string */
+
+            Source = ACPI_ADD_PTR (void, Aml, (ACPI_GET16 (Source) + Info->Value));
+            AcpiRsMoveData (Target, Source, ItemCount, Info->Opcode);
+            break;
+
+
         case ACPI_RSC_SET8:
 
             ACPI_MEMSET (Destination, Info->AmlOffset, Info->Value);
@@ -243,11 +385,12 @@
              * Optional ResourceSource (Index and String). This is the more
              * complicated case used by the Interrupt() macro
              */
-            Target = ACPI_ADD_PTR (char, Resource, Info->AmlOffset + (ItemCount * 4));
+            Target = ACPI_ADD_PTR (char, Resource,
+                Info->AmlOffset + (ItemCount * 4));
 
             Resource->Length +=
-                AcpiRsGetResourceSource (AmlResourceLength,
-                    (ACPI_RS_LENGTH) (((ItemCount - 1) * sizeof (UINT32)) + Info->Value),
+                AcpiRsGetResourceSource (AmlResourceLength, (ACPI_RS_LENGTH)
+                    (((ItemCount - 1) * sizeof (UINT32)) + Info->Value),
                     Destination, Aml, Target);
             break;
 
@@ -356,6 +499,7 @@
 {
     void                    *Source = NULL;
     void                    *Destination;
+    char                    *Target;
     ACPI_RSDESC_SIZE        AmlLength = 0;
     UINT8                   Count;
     UINT16                  Temp16 = 0;
@@ -365,6 +509,11 @@
     ACPI_FUNCTION_TRACE (RsConvertResourceToAml);
 
 
+    if (!Info)
+    {
+        return_ACPI_STATUS (AE_BAD_PARAMETER);
+    }
+
     /*
      * First table entry must be ACPI_RSC_INITxxx and must contain the
      * table length (# of table entries)
@@ -420,6 +569,15 @@
             break;
 
 
+        case ACPI_RSC_3BITFLAG:
+            /*
+             * Mask and shift the flag bits
+             */
+            ACPI_SET8 (Destination) |= (UINT8)
+                ((ACPI_GET8 (Source) & 0x07) << Info->Value);
+            break;
+
+
         case ACPI_RSC_COUNT:
 
             ItemCount = ACPI_GET8 (Source);
@@ -437,6 +595,68 @@
             break;
 
 
+        case ACPI_RSC_COUNT_GPIO_PIN:
+
+            ItemCount = ACPI_GET16 (Source);
+            ACPI_SET16 (Destination) = (UINT16) AmlLength;
+
+            AmlLength = (UINT16) (AmlLength + ItemCount * 2);
+            Target = ACPI_ADD_PTR (void, Aml, Info->Value);
+            ACPI_SET16 (Target) = (UINT16) AmlLength;
+            AcpiRsSetResourceLength (AmlLength, Aml);
+            break;
+
+
+        case ACPI_RSC_COUNT_GPIO_VEN:
+
+            ItemCount = ACPI_GET16 (Source);
+            ACPI_SET16 (Destination) = (UINT16) ItemCount;
+
+            AmlLength = (UINT16) (AmlLength + (Info->Value * ItemCount));
+            AcpiRsSetResourceLength (AmlLength, Aml);
+            break;
+
+
+        case ACPI_RSC_COUNT_GPIO_RES:
+
+            /* Set resource source string length */
+
+            ItemCount = ACPI_GET16 (Source);
+            ACPI_SET16 (Destination) = (UINT16) AmlLength;
+
+            /* Compute offset for the Vendor Data */
+
+            AmlLength = (UINT16) (AmlLength + ItemCount);
+            Target = ACPI_ADD_PTR (void, Aml, Info->Value);
+
+            /* Set vendor offset only if there is vendor data */
+
+            if (Resource->Data.Gpio.VendorLength)
+            {
+                ACPI_SET16 (Target) = (UINT16) AmlLength;
+            }
+
+            AcpiRsSetResourceLength (AmlLength, Aml);
+            break;
+
+
+        case ACPI_RSC_COUNT_SERIAL_VEN:
+
+            ItemCount = ACPI_GET16 (Source);
+            ACPI_SET16 (Destination) = ItemCount + Info->Value;
+            AmlLength = (UINT16) (AmlLength + ItemCount);
+            AcpiRsSetResourceLength (AmlLength, Aml);
+            break;
+
+
+        case ACPI_RSC_COUNT_SERIAL_RES:
+
+            ItemCount = ACPI_GET16 (Source);
+            AmlLength = (UINT16) (AmlLength + ItemCount);
+            AcpiRsSetResourceLength (AmlLength, Aml);
+            break;
+
+
         case ACPI_RSC_LENGTH:
 
             AcpiRsSetResourceLength (Info->Value, Aml);
@@ -456,6 +676,44 @@
             break;
 
 
+        case ACPI_RSC_MOVE_GPIO_PIN:
+
+            Destination = (char *) ACPI_ADD_PTR (void, Aml,
+                  ACPI_GET16 (Destination));
+            Source = * (UINT16 **) Source;
+            AcpiRsMoveData (Destination, Source, ItemCount, Info->Opcode);
+            break;
+
+
+        case ACPI_RSC_MOVE_GPIO_RES:
+
+            /* Used for both ResourceSource string and VendorData */
+
+            Destination = (char *) ACPI_ADD_PTR (void, Aml,
+                  ACPI_GET16 (Destination));
+            Source = * (UINT8 **) Source;
+            AcpiRsMoveData (Destination, Source, ItemCount, Info->Opcode);
+            break;
+
+
+        case ACPI_RSC_MOVE_SERIAL_VEN:
+
+            Destination = (char *) ACPI_ADD_PTR (void, Aml,
+                  (AmlLength - ItemCount));
+            Source = * (UINT8 **) Source;
+            AcpiRsMoveData (Destination, Source, ItemCount, Info->Opcode);
+            break;
+
+
+        case ACPI_RSC_MOVE_SERIAL_RES:
+
+            Destination = (char *) ACPI_ADD_PTR (void, Aml,
+                  (AmlLength - ItemCount));
+            Source = * (UINT8 **) Source;
+            AcpiRsMoveData (Destination, Source, ItemCount, Info->Opcode);
+            break;
+
+
         case ACPI_RSC_ADDRESS:
 
             /* Set the Resource Type, General Flags, and Type-Specific Flags */
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/resources/rsserial.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/sys/contrib/dev/acpica/resources/rsserial.c	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,425 @@
+/*******************************************************************************
+ *
+ * Module Name: rsserial - GPIO/SerialBus resource descriptors
+ *
+ ******************************************************************************/
+
+/*
+ * Copyright (C) 2000 - 2011, Intel Corp.
+ * 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.
+ * 3. Neither the names of the above-listed copyright holders nor the names
+ *    of any contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ * Alternatively, this software may be distributed under the terms of the
+ * GNU General Public License ("GPL") version 2 as published by the Free
+ * Software Foundation.
+ *
+ * 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.
+ */
+
+#define __RSIRQ_C__
+
+#include <contrib/dev/acpica/include/acpi.h>
+#include <contrib/dev/acpica/include/accommon.h>
+#include <contrib/dev/acpica/include/acresrc.h>
+
+#define _COMPONENT          ACPI_RESOURCES
+        ACPI_MODULE_NAME    ("rsserial")
+
+
+/*******************************************************************************
+ *
+ * AcpiRsConvertGpio
+ *
+ ******************************************************************************/
+
+ACPI_RSCONVERT_INFO     AcpiRsConvertGpio[17] =
+{
+    {ACPI_RSC_INITGET,  ACPI_RESOURCE_TYPE_GPIO,
+                        ACPI_RS_SIZE (ACPI_RESOURCE_GPIO),
+                        ACPI_RSC_TABLE_SIZE (AcpiRsConvertGpio)},
+
+    {ACPI_RSC_INITSET,  ACPI_RESOURCE_NAME_GPIO,
+                        sizeof (AML_RESOURCE_GPIO),
+                        0},
+
+    /*
+     * These fields are contiguous in both the source and destination:
+     * RevisionId
+     * ConnectionType
+     */
+    {ACPI_RSC_MOVE8,    ACPI_RS_OFFSET (Data.Gpio.RevisionId),
+                        AML_OFFSET (Gpio.RevisionId),
+                        2},
+
+    {ACPI_RSC_1BITFLAG, ACPI_RS_OFFSET (Data.Gpio.ProducerConsumer),
+                        AML_OFFSET (Gpio.Flags),
+                        0},
+
+    {ACPI_RSC_2BITFLAG, ACPI_RS_OFFSET (Data.Gpio.Sharable),
+                        AML_OFFSET (Gpio.IntFlags),
+                        3},
+
+    {ACPI_RSC_2BITFLAG, ACPI_RS_OFFSET (Data.Gpio.IoRestriction),
+                        AML_OFFSET (Gpio.IntFlags),
+                        0},
+
+    {ACPI_RSC_1BITFLAG, ACPI_RS_OFFSET (Data.Gpio.Triggering),
+                        AML_OFFSET (Gpio.IntFlags),
+                        0},
+
+    {ACPI_RSC_2BITFLAG, ACPI_RS_OFFSET (Data.Gpio.Polarity),
+                        AML_OFFSET (Gpio.IntFlags),
+                        1},
+
+    {ACPI_RSC_MOVE8,    ACPI_RS_OFFSET (Data.Gpio.PinConfig),
+                        AML_OFFSET (Gpio.PinConfig),
+                        1},
+
+    /*
+     * These fields are contiguous in both the source and destination:
+     * DriveStrength
+     * DebounceTimeout
+     */
+    {ACPI_RSC_MOVE16,   ACPI_RS_OFFSET (Data.Gpio.DriveStrength),
+                        AML_OFFSET (Gpio.DriveStrength),
+                        2},
+
+    /* Pin Table */
+
+    {ACPI_RSC_COUNT_GPIO_PIN, ACPI_RS_OFFSET (Data.Gpio.PinTableLength),
+                        AML_OFFSET (Gpio.PinTableOffset),
+                        AML_OFFSET (Gpio.ResSourceOffset)},
+
+    {ACPI_RSC_MOVE_GPIO_PIN, ACPI_RS_OFFSET (Data.Gpio.PinTable),
+                        AML_OFFSET (Gpio.PinTableOffset),
+                        0},
+
+    /* Resource Source */
+
+    {ACPI_RSC_MOVE8,    ACPI_RS_OFFSET (Data.Gpio.ResourceSource.Index),
+                        AML_OFFSET (Gpio.ResSourceIndex),
+                        1},
+
+    {ACPI_RSC_COUNT_GPIO_RES,  ACPI_RS_OFFSET (Data.Gpio.ResourceSource.StringLength),
+                        AML_OFFSET (Gpio.ResSourceOffset),
+                        AML_OFFSET (Gpio.VendorOffset)},
+
+    {ACPI_RSC_MOVE_GPIO_RES,   ACPI_RS_OFFSET (Data.Gpio.ResourceSource.StringPtr),
+                        AML_OFFSET (Gpio.ResSourceOffset),
+                        0},
+
+    /* Vendor Data */
+
+    {ACPI_RSC_COUNT_GPIO_VEN,   ACPI_RS_OFFSET (Data.Gpio.VendorLength),
+                        AML_OFFSET (Gpio.VendorLength),
+                        1},
+
+    {ACPI_RSC_MOVE_GPIO_RES,   ACPI_RS_OFFSET (Data.Gpio.VendorData),
+                        AML_OFFSET (Gpio.VendorOffset),
+                        0},
+};
+
+
+/*******************************************************************************
+ *
+ * AcpiRsConvertI2cSerialBus
+ *
+ ******************************************************************************/
+
+ACPI_RSCONVERT_INFO     AcpiRsConvertI2cSerialBus[16] =
+{
+    {ACPI_RSC_INITGET,  ACPI_RESOURCE_TYPE_SERIAL_BUS,
+                        ACPI_RS_SIZE (ACPI_RESOURCE_I2C_SERIALBUS),
+                        ACPI_RSC_TABLE_SIZE (AcpiRsConvertI2cSerialBus)},
+
+    {ACPI_RSC_INITSET,  ACPI_RESOURCE_NAME_SERIAL_BUS,
+                        sizeof (AML_RESOURCE_I2C_SERIALBUS),
+                        0},
+
+    {ACPI_RSC_MOVE8,    ACPI_RS_OFFSET (Data.CommonSerialBus.RevisionId),
+                        AML_OFFSET (CommonSerialBus.RevisionId),
+                        1},
+
+    {ACPI_RSC_MOVE8,    ACPI_RS_OFFSET (Data.CommonSerialBus.Type),
+                        AML_OFFSET (CommonSerialBus.Type),
+                        1},
+
+    {ACPI_RSC_1BITFLAG, ACPI_RS_OFFSET (Data.CommonSerialBus.SlaveMode),
+                        AML_OFFSET (CommonSerialBus.Flags),
+                        0},
+
+    {ACPI_RSC_1BITFLAG, ACPI_RS_OFFSET (Data.CommonSerialBus.ProducerConsumer),
+                        AML_OFFSET (CommonSerialBus.Flags),
+                        1},
+
+    {ACPI_RSC_MOVE8,    ACPI_RS_OFFSET (Data.CommonSerialBus.TypeRevisionId),
+                        AML_OFFSET (CommonSerialBus.TypeRevisionId),
+                        1},
+
+    {ACPI_RSC_MOVE16,   ACPI_RS_OFFSET (Data.CommonSerialBus.TypeDataLength),
+                        AML_OFFSET (CommonSerialBus.TypeDataLength),
+                        1},
+
+    /* Vendor data */
+
+    {ACPI_RSC_COUNT_SERIAL_VEN, ACPI_RS_OFFSET (Data.CommonSerialBus.VendorLength),
+                        AML_OFFSET (CommonSerialBus.TypeDataLength),
+                        AML_RESOURCE_I2C_MIN_DATA_LEN},
+
+    {ACPI_RSC_MOVE_SERIAL_VEN,  ACPI_RS_OFFSET (Data.CommonSerialBus.VendorData),
+                        0,
+                        sizeof (AML_RESOURCE_I2C_SERIALBUS)},
+
+    /* Resource Source */
+
+    {ACPI_RSC_MOVE8,    ACPI_RS_OFFSET (Data.CommonSerialBus.ResourceSource.Index),
+                        AML_OFFSET (CommonSerialBus.ResSourceIndex),
+                        1},
+
+    {ACPI_RSC_COUNT_SERIAL_RES, ACPI_RS_OFFSET (Data.CommonSerialBus.ResourceSource.StringLength),
+                        AML_OFFSET (CommonSerialBus.TypeDataLength),
+                        sizeof (AML_RESOURCE_COMMON_SERIALBUS)},
+
+    {ACPI_RSC_MOVE_SERIAL_RES,  ACPI_RS_OFFSET (Data.CommonSerialBus.ResourceSource.StringPtr),
+                        AML_OFFSET (CommonSerialBus.TypeDataLength),
+                        sizeof (AML_RESOURCE_COMMON_SERIALBUS)},
+
+    /* I2C bus type specific */
+
+    {ACPI_RSC_1BITFLAG, ACPI_RS_OFFSET (Data.I2cSerialBus.AccessMode),
+                        AML_OFFSET (I2cSerialBus.TypeSpecificFlags),
+                        0},
+
+    {ACPI_RSC_MOVE32,   ACPI_RS_OFFSET (Data.I2cSerialBus.ConnectionSpeed),
+                        AML_OFFSET (I2cSerialBus.ConnectionSpeed),
+                        1},
+
+    {ACPI_RSC_MOVE16,   ACPI_RS_OFFSET (Data.I2cSerialBus.SlaveAddress),
+                        AML_OFFSET (I2cSerialBus.SlaveAddress),
+                        1},
+};
+
+
+/*******************************************************************************
+ *
+ * AcpiRsConvertSpiSerialBus
+ *
+ ******************************************************************************/
+
+ACPI_RSCONVERT_INFO     AcpiRsConvertSpiSerialBus[20] =
+{
+    {ACPI_RSC_INITGET,  ACPI_RESOURCE_TYPE_SERIAL_BUS,
+                        ACPI_RS_SIZE (ACPI_RESOURCE_SPI_SERIALBUS),
+                        ACPI_RSC_TABLE_SIZE (AcpiRsConvertSpiSerialBus)},
+
+    {ACPI_RSC_INITSET,  ACPI_RESOURCE_NAME_SERIAL_BUS,
+                        sizeof (AML_RESOURCE_SPI_SERIALBUS),
+                        0},
+
+    {ACPI_RSC_MOVE8,    ACPI_RS_OFFSET (Data.CommonSerialBus.RevisionId),
+                        AML_OFFSET (CommonSerialBus.RevisionId),
+                        1},
+
+    {ACPI_RSC_MOVE8,    ACPI_RS_OFFSET (Data.CommonSerialBus.Type),
+                        AML_OFFSET (CommonSerialBus.Type),
+                        1},
+
+    {ACPI_RSC_1BITFLAG, ACPI_RS_OFFSET (Data.CommonSerialBus.SlaveMode),
+                        AML_OFFSET (CommonSerialBus.Flags),
+                        0},
+
+    {ACPI_RSC_1BITFLAG, ACPI_RS_OFFSET (Data.CommonSerialBus.ProducerConsumer),
+                        AML_OFFSET (CommonSerialBus.Flags),
+                        1},
+
+    {ACPI_RSC_MOVE8,    ACPI_RS_OFFSET (Data.CommonSerialBus.TypeRevisionId),
+                        AML_OFFSET (CommonSerialBus.TypeRevisionId),
+                        1},
+
+    {ACPI_RSC_MOVE16,   ACPI_RS_OFFSET (Data.CommonSerialBus.TypeDataLength),
+                        AML_OFFSET (CommonSerialBus.TypeDataLength),
+                        1},
+
+    /* Vendor data */
+
+    {ACPI_RSC_COUNT_SERIAL_VEN, ACPI_RS_OFFSET (Data.CommonSerialBus.VendorLength),
+                        AML_OFFSET (CommonSerialBus.TypeDataLength),
+                        AML_RESOURCE_SPI_MIN_DATA_LEN},
+
+    {ACPI_RSC_MOVE_SERIAL_VEN,  ACPI_RS_OFFSET (Data.CommonSerialBus.VendorData),
+                        0,
+                        sizeof (AML_RESOURCE_SPI_SERIALBUS)},
+
+    /* Resource Source */
+
+    {ACPI_RSC_MOVE8,    ACPI_RS_OFFSET (Data.CommonSerialBus.ResourceSource.Index),
+                        AML_OFFSET (CommonSerialBus.ResSourceIndex),
+                        1},
+
+    {ACPI_RSC_COUNT_SERIAL_RES, ACPI_RS_OFFSET (Data.CommonSerialBus.ResourceSource.StringLength),
+                        AML_OFFSET (CommonSerialBus.TypeDataLength),
+                        sizeof (AML_RESOURCE_COMMON_SERIALBUS)},
+
+    {ACPI_RSC_MOVE_SERIAL_RES,  ACPI_RS_OFFSET (Data.CommonSerialBus.ResourceSource.StringPtr),
+                        AML_OFFSET (CommonSerialBus.TypeDataLength),
+                        sizeof (AML_RESOURCE_COMMON_SERIALBUS)},
+
+    /* Spi bus type specific  */
+
+    {ACPI_RSC_1BITFLAG, ACPI_RS_OFFSET (Data.SpiSerialBus.WireMode),
+                        AML_OFFSET (SpiSerialBus.TypeSpecificFlags),
+                        0},
+
+    {ACPI_RSC_1BITFLAG, ACPI_RS_OFFSET (Data.SpiSerialBus.DevicePolarity),
+                        AML_OFFSET (SpiSerialBus.TypeSpecificFlags),
+                        1},
+
+    {ACPI_RSC_MOVE8,    ACPI_RS_OFFSET (Data.SpiSerialBus.DataBitLength),
+                        AML_OFFSET (SpiSerialBus.DataBitLength),
+                        1},
+
+    {ACPI_RSC_MOVE8,    ACPI_RS_OFFSET (Data.SpiSerialBus.ClockPhase),
+                        AML_OFFSET (SpiSerialBus.ClockPhase),
+                        1},
+
+    {ACPI_RSC_MOVE8,    ACPI_RS_OFFSET (Data.SpiSerialBus.ClockPolarity),
+                        AML_OFFSET (SpiSerialBus.ClockPolarity),
+                        1},
+
+    {ACPI_RSC_MOVE16,   ACPI_RS_OFFSET (Data.SpiSerialBus.DeviceSelection),
+                        AML_OFFSET (SpiSerialBus.DeviceSelection),
+                        1},
+
+    {ACPI_RSC_MOVE32,   ACPI_RS_OFFSET (Data.SpiSerialBus.ConnectionSpeed),
+                        AML_OFFSET (SpiSerialBus.ConnectionSpeed),
+                        1},
+};
+
+
+/*******************************************************************************
+ *
+ * AcpiRsConvertUartSerialBus
+ *
+ ******************************************************************************/
+
+ACPI_RSCONVERT_INFO     AcpiRsConvertUartSerialBus[22] =
+{
+    {ACPI_RSC_INITGET,  ACPI_RESOURCE_TYPE_SERIAL_BUS,
+                        ACPI_RS_SIZE (ACPI_RESOURCE_UART_SERIALBUS),
+                        ACPI_RSC_TABLE_SIZE (AcpiRsConvertUartSerialBus)},
+
+    {ACPI_RSC_INITSET,  ACPI_RESOURCE_NAME_SERIAL_BUS,
+                        sizeof (AML_RESOURCE_UART_SERIALBUS),
+                        0},
+
+    {ACPI_RSC_MOVE8,    ACPI_RS_OFFSET (Data.CommonSerialBus.RevisionId),
+                        AML_OFFSET (CommonSerialBus.RevisionId),
+                        1},
+
+    {ACPI_RSC_MOVE8,    ACPI_RS_OFFSET (Data.CommonSerialBus.Type),
+                        AML_OFFSET (CommonSerialBus.Type),
+                        1},
+
+    {ACPI_RSC_1BITFLAG, ACPI_RS_OFFSET (Data.CommonSerialBus.SlaveMode),
+                        AML_OFFSET (CommonSerialBus.Flags),
+                        0},
+
+    {ACPI_RSC_1BITFLAG, ACPI_RS_OFFSET (Data.CommonSerialBus.ProducerConsumer),
+                        AML_OFFSET (CommonSerialBus.Flags),
+                        1},
+
+    {ACPI_RSC_MOVE8,    ACPI_RS_OFFSET (Data.CommonSerialBus.TypeRevisionId),
+                        AML_OFFSET (CommonSerialBus.TypeRevisionId),
+                        1},
+
+    {ACPI_RSC_MOVE16,   ACPI_RS_OFFSET (Data.CommonSerialBus.TypeDataLength),
+                        AML_OFFSET (CommonSerialBus.TypeDataLength),
+                        1},
+
+    /* Vendor data */
+
+    {ACPI_RSC_COUNT_SERIAL_VEN, ACPI_RS_OFFSET (Data.CommonSerialBus.VendorLength),
+                        AML_OFFSET (CommonSerialBus.TypeDataLength),
+                        AML_RESOURCE_UART_MIN_DATA_LEN},
+
+    {ACPI_RSC_MOVE_SERIAL_VEN,  ACPI_RS_OFFSET (Data.CommonSerialBus.VendorData),
+                        0,
+                        sizeof (AML_RESOURCE_UART_SERIALBUS)},
+
+    /* Resource Source */
+
+    {ACPI_RSC_MOVE8,    ACPI_RS_OFFSET (Data.CommonSerialBus.ResourceSource.Index),
+                        AML_OFFSET (CommonSerialBus.ResSourceIndex),
+                        1},
+
+    {ACPI_RSC_COUNT_SERIAL_RES, ACPI_RS_OFFSET (Data.CommonSerialBus.ResourceSource.StringLength),
+                        AML_OFFSET (CommonSerialBus.TypeDataLength),
+                        sizeof (AML_RESOURCE_COMMON_SERIALBUS)},
+
+    {ACPI_RSC_MOVE_SERIAL_RES,  ACPI_RS_OFFSET (Data.CommonSerialBus.ResourceSource.StringPtr),
+                        AML_OFFSET (CommonSerialBus.TypeDataLength),
+                        sizeof (AML_RESOURCE_COMMON_SERIALBUS)},
+
+    /* Uart bus type specific  */
+
+    {ACPI_RSC_2BITFLAG, ACPI_RS_OFFSET (Data.UartSerialBus.FlowControl),
+                        AML_OFFSET (UartSerialBus.TypeSpecificFlags),
+                        0},
+
+    {ACPI_RSC_2BITFLAG, ACPI_RS_OFFSET (Data.UartSerialBus.StopBits),
+                        AML_OFFSET (UartSerialBus.TypeSpecificFlags),
+                        2},
+
+    {ACPI_RSC_3BITFLAG, ACPI_RS_OFFSET (Data.UartSerialBus.DataBits),
+                        AML_OFFSET (UartSerialBus.TypeSpecificFlags),
+                        4},
+
+    {ACPI_RSC_1BITFLAG, ACPI_RS_OFFSET (Data.UartSerialBus.Endian),
+                        AML_OFFSET (UartSerialBus.TypeSpecificFlags),
+                        7},
+
+    {ACPI_RSC_MOVE8,    ACPI_RS_OFFSET (Data.UartSerialBus.Parity),
+                        AML_OFFSET (UartSerialBus.Parity),
+                        1},
+
+    {ACPI_RSC_MOVE8,    ACPI_RS_OFFSET (Data.UartSerialBus.LinesEnabled),
+                        AML_OFFSET (UartSerialBus.LinesEnabled),
+                        1},
+
+    {ACPI_RSC_MOVE16,   ACPI_RS_OFFSET (Data.UartSerialBus.RxFifoSize),
+                        AML_OFFSET (UartSerialBus.RxFifoSize),
+                        1},
+
+    {ACPI_RSC_MOVE16,   ACPI_RS_OFFSET (Data.UartSerialBus.TxFifoSize),
+                        AML_OFFSET (UartSerialBus.TxFifoSize),
+                        1},
+
+    {ACPI_RSC_MOVE32,   ACPI_RS_OFFSET (Data.UartSerialBus.DefaultBaudRate),
+                        AML_OFFSET (UartSerialBus.DefaultBaudRate),
+                        1},
+};
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/resources/rsutils.c
--- a/head/sys/contrib/dev/acpica/resources/rsutils.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/resources/rsutils.c	Tue Dec 06 20:26:16 2011 +0200
@@ -173,6 +173,9 @@
          * since there are no alignment or endian issues
          */
         case ACPI_RSC_MOVE8:
+        case ACPI_RSC_MOVE_GPIO_RES:
+        case ACPI_RSC_MOVE_SERIAL_VEN:
+        case ACPI_RSC_MOVE_SERIAL_RES:
             ACPI_MEMCPY (Destination, Source, ItemCount);
             return;
 
@@ -182,6 +185,7 @@
          * misaligned memory transfers
          */
         case ACPI_RSC_MOVE16:
+        case ACPI_RSC_MOVE_GPIO_PIN:
             ACPI_MOVE_16_TO_16 (&ACPI_CAST_PTR (UINT16, Destination)[i],
                                 &ACPI_CAST_PTR (UINT16, Source)[i]);
             break;
@@ -653,6 +657,61 @@
 
 /*******************************************************************************
  *
+ * FUNCTION:    AcpiRsGetAeiMethodData
+ *
+ * PARAMETERS:  Node            - Device node
+ *              RetBuffer       - Pointer to a buffer structure for the
+ *                                results
+ *
+ * RETURN:      Status
+ *
+ * DESCRIPTION: This function is called to get the _AEI value of an object
+ *              contained in an object specified by the handle passed in
+ *
+ *              If the function fails an appropriate status will be returned
+ *              and the contents of the callers buffer is undefined.
+ *
+ ******************************************************************************/
+
+ACPI_STATUS
+AcpiRsGetAeiMethodData (
+    ACPI_NAMESPACE_NODE     *Node,
+    ACPI_BUFFER             *RetBuffer)
+{
+    ACPI_OPERAND_OBJECT     *ObjDesc;
+    ACPI_STATUS             Status;
+
+
+    ACPI_FUNCTION_TRACE (RsGetAeiMethodData);
+
+
+    /* Parameters guaranteed valid by caller */
+
+    /* Execute the method, no parameters */
+
+    Status = AcpiUtEvaluateObject (Node, METHOD_NAME__AEI,
+                ACPI_BTYPE_BUFFER, &ObjDesc);
+    if (ACPI_FAILURE (Status))
+    {
+        return_ACPI_STATUS (Status);
+    }
+
+    /*
+     * Make the call to create a resource linked list from the
+     * byte stream buffer that comes back from the _CRS method
+     * execution.
+     */
+    Status = AcpiRsCreateResourceList (ObjDesc, RetBuffer);
+
+    /* On exit, we must delete the object returned by evaluateObject */
+
+    AcpiUtRemoveReference (ObjDesc);
+    return_ACPI_STATUS (Status);
+}
+
+
+/*******************************************************************************
+ *
  * FUNCTION:    AcpiRsGetMethodData
  *
  * PARAMETERS:  Handle          - Handle to the containing object
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/resources/rsxface.c
--- a/head/sys/contrib/dev/acpica/resources/rsxface.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/resources/rsxface.c	Tue Dec 06 20:26:16 2011 +0200
@@ -351,6 +351,52 @@
 ACPI_EXPORT_SYMBOL (AcpiSetCurrentResources)
 
 
+/*******************************************************************************
+ *
+ * FUNCTION:    AcpiGetEventResources
+ *
+ * PARAMETERS:  DeviceHandle    - Handle to the device object for the
+ *                                device we are getting resources
+ *              InBuffer        - Pointer to a buffer containing the
+ *                                resources to be set for the device
+ *
+ * RETURN:      Status
+ *
+ * DESCRIPTION: This function is called to get the event resources for a
+ *              specific device. The caller must first acquire a handle for
+ *              the desired device. The resource data is passed to the routine
+ *              the buffer pointed to by the InBuffer variable. Uses the
+ *              _AEI method.
+ *
+ ******************************************************************************/
+
+ACPI_STATUS
+AcpiGetEventResources (
+    ACPI_HANDLE             DeviceHandle,
+    ACPI_BUFFER             *RetBuffer)
+{
+    ACPI_STATUS             Status;
+    ACPI_NAMESPACE_NODE     *Node;
+
+
+    ACPI_FUNCTION_TRACE (AcpiGetEventResources);
+
+
+    /* Validate parameters then dispatch to internal routine */
+
+    Status = AcpiRsValidateParameters (DeviceHandle, RetBuffer, &Node);
+    if (ACPI_FAILURE (Status))
+    {
+        return_ACPI_STATUS (Status);
+    }
+
+    Status = AcpiRsGetAeiMethodData (Node, RetBuffer);
+    return_ACPI_STATUS (Status);
+}
+
+ACPI_EXPORT_SYMBOL (AcpiGetEventResources)
+
+
 /******************************************************************************
  *
  * FUNCTION:    AcpiResourceToAddress64
@@ -544,8 +590,9 @@
  *
  * PARAMETERS:  DeviceHandle    - Handle to the device object for the
  *                                device we are querying
- *              Name            - Method name of the resources we want
- *                                (METHOD_NAME__CRS or METHOD_NAME__PRS)
+ *              Name            - Method name of the resources we want.
+ *                                (METHOD_NAME__CRS, METHOD_NAME__PRS, or
+ *                                METHOD_NAME__AEI)
  *              UserFunction    - Called for each resource
  *              Context         - Passed to UserFunction
  *
@@ -577,12 +624,13 @@
 
     if (!DeviceHandle || !UserFunction || !Name ||
         (!ACPI_COMPARE_NAME (Name, METHOD_NAME__CRS) &&
-         !ACPI_COMPARE_NAME (Name, METHOD_NAME__PRS)))
+         !ACPI_COMPARE_NAME (Name, METHOD_NAME__PRS) &&
+         !ACPI_COMPARE_NAME (Name, METHOD_NAME__AEI)))
     {
         return_ACPI_STATUS (AE_BAD_PARAMETER);
     }
 
-    /* Get the _CRS or _PRS resource list */
+    /* Get the _CRS/_PRS/_AEI resource list */
 
     Buffer.Length = ACPI_ALLOCATE_LOCAL_BUFFER;
     Status = AcpiRsGetMethodData (DeviceHandle, Name, &Buffer);
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/tables/tbfadt.c
--- a/head/sys/contrib/dev/acpica/tables/tbfadt.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/tables/tbfadt.c	Tue Dec 06 20:26:16 2011 +0200
@@ -280,8 +280,13 @@
     AcpiTbInstallTable ((ACPI_PHYSICAL_ADDRESS) AcpiGbl_FADT.XDsdt,
         ACPI_SIG_DSDT, ACPI_TABLE_INDEX_DSDT);
 
-    AcpiTbInstallTable ((ACPI_PHYSICAL_ADDRESS) AcpiGbl_FADT.XFacs,
-        ACPI_SIG_FACS, ACPI_TABLE_INDEX_FACS);
+    /* If Hardware Reduced flag is set, there is no FACS */
+
+    if (!AcpiGbl_ReducedHardware)
+    {
+        AcpiTbInstallTable ((ACPI_PHYSICAL_ADDRESS) AcpiGbl_FADT.XFacs,
+            ACPI_SIG_FACS, ACPI_TABLE_INDEX_FACS);
+    }
 }
 
 
@@ -309,13 +314,13 @@
 
     /*
      * Check if the FADT is larger than the largest table that we expect
-     * (the ACPI 2.0/3.0 version). If so, truncate the table, and issue
+     * (the ACPI 5.0 version). If so, truncate the table, and issue
      * a warning.
      */
     if (Length > sizeof (ACPI_TABLE_FADT))
     {
         ACPI_WARNING ((AE_INFO,
-            "FADT (revision %u) is longer than ACPI 2.0 version, "
+            "FADT (revision %u) is longer than ACPI 5.0 version, "
             "truncating length %u to %u",
             Table->Revision, Length, (UINT32) sizeof (ACPI_TABLE_FADT)));
     }
@@ -329,6 +334,14 @@
     ACPI_MEMCPY (&AcpiGbl_FADT, Table,
         ACPI_MIN (Length, sizeof (ACPI_TABLE_FADT)));
 
+    /* Take a copy of the Hardware Reduced flag */
+
+    AcpiGbl_ReducedHardware = FALSE;
+    if (AcpiGbl_FADT.Flags & ACPI_FADT_HW_REDUCED)
+    {
+        AcpiGbl_ReducedHardware = TRUE;
+    }
+
     /* Convert the local copy of the FADT to the common internal format */
 
     AcpiTbConvertFadt ();
@@ -530,6 +543,13 @@
         AcpiGbl_FADT.XDsdt = (UINT64) AcpiGbl_FADT.Dsdt;
     }
 
+    /* If Hardware Reduced flag is set, we are all done */
+
+    if (AcpiGbl_ReducedHardware)
+    {
+        return;
+    }
+
     /* Examine all of the 64-bit extended address fields (X fields) */
 
     for (i = 0; i < ACPI_FADT_INFO_ENTRIES; i++)
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/tables/tbutils.c
--- a/head/sys/contrib/dev/acpica/tables/tbutils.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/tables/tbutils.c	Tue Dec 06 20:26:16 2011 +0200
@@ -88,6 +88,14 @@
     ACPI_STATUS             Status;
 
 
+    /* If Hardware Reduced flag is set, there is no FACS */
+
+    if (AcpiGbl_ReducedHardware)
+    {
+        AcpiGbl_FACS = NULL;
+        return (AE_OK);
+    }
+
     Status = AcpiGetTableByIndex (ACPI_TABLE_INDEX_FACS,
                 ACPI_CAST_INDIRECT_PTR (ACPI_TABLE_HEADER, &AcpiGbl_FACS));
     return (Status);
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/tools/acpiexec/aecommon.h
--- a/head/sys/contrib/dev/acpica/tools/acpiexec/aecommon.h	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,197 +0,0 @@
-/******************************************************************************
- *
- * Module Name: aecommon - common include for the AcpiExec utility
- *
- *****************************************************************************/
-
-/*
- * Copyright (C) 2000 - 2011, Intel Corp.
- * 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.
- * 3. Neither the names of the above-listed copyright holders nor the names
- *    of any contributors may be used to endorse or promote products derived
- *    from this software without specific prior written permission.
- *
- * Alternatively, this software may be distributed under the terms of the
- * GNU General Public License ("GPL") version 2 as published by the Free
- * Software Foundation.
- *
- * 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.
- */
-
-#ifndef _AECOMMON
-#define _AECOMMON
-
-#ifdef _MSC_VER                 /* disable some level-4 warnings */
-#pragma warning(disable:4100)   /* warning C4100: unreferenced formal parameter */
-#endif
-
-#include <contrib/dev/acpica/include/acpi.h>
-#include <contrib/dev/acpica/include/accommon.h>
-#include <contrib/dev/acpica/include/acparser.h>
-#include <contrib/dev/acpica/include/amlcode.h>
-#include <contrib/dev/acpica/include/acnamesp.h>
-#include <contrib/dev/acpica/include/acdebug.h>
-#include <contrib/dev/acpica/include/actables.h>
-#include <contrib/dev/acpica/include/acinterp.h>
-#include <contrib/dev/acpica/include/acapps.h>
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <signal.h>
-
-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
-{
-    ACPI_TABLE_HEADER       *Table;
-    struct ae_table_desc    *Next;
-
-} AE_TABLE_DESC;
-
-/*
- * Debug Regions
- */
-typedef struct ae_region
-{
-    ACPI_PHYSICAL_ADDRESS   Address;
-    UINT32                  Length;
-    void                    *Buffer;
-    void                    *NextRegion;
-    UINT8                   SpaceId;
-
-} AE_REGION;
-
-typedef struct ae_debug_regions
-{
-    UINT32                  NumberOfRegions;
-    AE_REGION               *RegionList;
-
-} AE_DEBUG_REGIONS;
-
-
-#define TEST_OUTPUT_LEVEL(lvl)          if ((lvl) & OutputLevel)
-
-#define OSD_PRINT(lvl,fp)               TEST_OUTPUT_LEVEL(lvl) {\
-                                            AcpiOsPrintf PARAM_LIST(fp);}
-
-void ACPI_SYSTEM_XFACE
-AeCtrlCHandler (
-    int                     Sig);
-
-ACPI_STATUS
-AeBuildLocalTables (
-    UINT32                  TableCount,
-    AE_TABLE_DESC           *TableList);
-
-ACPI_STATUS
-AeInstallTables (
-    void);
-
-void
-AeDumpNamespace (
-    void);
-
-void
-AeDumpObject (
-    char                    *MethodName,
-    ACPI_BUFFER             *ReturnObj);
-
-void
-AeDumpBuffer (
-    UINT32                  Address);
-
-void
-AeExecute (
-    char                    *Name);
-
-void
-AeSetScope (
-    char                    *Name);
-
-void
-AeCloseDebugFile (
-    void);
-
-void
-AeOpenDebugFile (
-    char                    *Name);
-
-ACPI_STATUS
-AeDisplayAllMethods (
-    UINT32                  DisplayCount);
-
-ACPI_STATUS
-AeInstallEarlyHandlers (
-    void);
-
-ACPI_STATUS
-AeInstallLateHandlers (
-    void);
-
-void
-AeMiscellaneousTests (
-    void);
-
-ACPI_STATUS
-AeRegionHandler (
-    UINT32                  Function,
-    ACPI_PHYSICAL_ADDRESS   Address,
-    UINT32                  BitWidth,
-    UINT64                  *Value,
-    void                    *HandlerContext,
-    void                    *RegionContext);
-
-UINT32
-AeGpeHandler (
-    ACPI_HANDLE             GpeDevice,
-    UINT32                  GpeNumber,
-    void                    *Context);
-
-void
-AeGlobalEventHandler (
-    UINT32                  Type,
-    ACPI_HANDLE             GpeDevice,
-    UINT32                  EventNumber,
-    void                    *Context);
-
-#endif /* _AECOMMON */
-
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/utilities/utdecode.c
--- a/head/sys/contrib/dev/acpica/utilities/utdecode.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/utilities/utdecode.c	Tue Dec 06 20:26:16 2011 +0200
@@ -187,7 +187,9 @@
     "SMBus",
     "SystemCMOS",
     "PCIBARTarget",
-    "IPMI"
+    "IPMI",
+    "GeneralPurposeIo",
+    "GenericSerialBus"
 };
 
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/utilities/utmutex.c
--- a/head/sys/contrib/dev/acpica/utilities/utmutex.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/utilities/utmutex.c	Tue Dec 06 20:26:16 2011 +0200
@@ -335,15 +335,10 @@
 AcpiUtReleaseMutex (
     ACPI_MUTEX_HANDLE       MutexId)
 {
-    ACPI_THREAD_ID          ThisThreadId;
-
-
     ACPI_FUNCTION_NAME (UtReleaseMutex);
 
-
-    ThisThreadId = AcpiOsGetThreadId ();
     ACPI_DEBUG_PRINT ((ACPI_DB_MUTEX, "Thread %u releasing Mutex [%s]\n",
-        (UINT32) ThisThreadId, AcpiUtGetMutexName (MutexId)));
+        (UINT32) AcpiOsGetThreadId (), AcpiUtGetMutexName (MutexId)));
 
     if (MutexId > ACPI_MAX_MUTEX)
     {
@@ -374,7 +369,7 @@
          */
         for (i = MutexId; i < ACPI_NUM_MUTEX; i++)
         {
-            if (AcpiGbl_MutexInfo[i].ThreadId == ThisThreadId)
+            if (AcpiGbl_MutexInfo[i].ThreadId == AcpiOsGetThreadId ())
             {
                 if (i == MutexId)
                 {
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/utilities/utresrc.c
--- a/head/sys/contrib/dev/acpica/utilities/utresrc.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/dev/acpica/utilities/utresrc.c	Tue Dec 06 20:26:16 2011 +0200
@@ -46,7 +46,7 @@
 
 #include <contrib/dev/acpica/include/acpi.h>
 #include <contrib/dev/acpica/include/accommon.h>
-#include <contrib/dev/acpica/include/amlresrc.h>
+#include <contrib/dev/acpica/include/acresrc.h>
 
 
 #define _COMPONENT          ACPI_UTILITIES
@@ -179,6 +179,154 @@
     "TypeF"
 };
 
+const char                      *AcpiGbl_PpcDecode[] =
+{
+    "PullDefault",
+    "PullUp",
+    "PullDown",
+    "PullNone"
+};
+
+const char                      *AcpiGbl_IorDecode[] =
+{
+    "IoRestrictionNone",
+    "IoRestrictionInputOnly",
+    "IoRestrictionOutputOnly",
+    "IoRestrictionNoneAndPreserve"
+};
+
+const char                      *AcpiGbl_DtsDecode[] =
+{
+    "Width8bit",
+    "Width16bit",
+    "Width32bit",
+    "Width64bit",
+    "Width128bit",
+    "Width256bit",
+};
+
+/* GPIO connection type */
+
+const char                      *AcpiGbl_CtDecode[] =
+{
+    "Interrupt",
+    "I/O"
+};
+
+/* Serial bus type */
+
+const char                      *AcpiGbl_SbtDecode[] =
+{
+    "/* UNKNOWN serial bus type */",
+    "I2C",
+    "SPI",
+    "UART"
+};
+
+/* I2C serial bus access mode */
+
+const char                      *AcpiGbl_AmDecode[] =
+{
+    "AddressingMode7Bit",
+    "AddressingMode10Bit"
+};
+
+/* I2C serial bus slave mode */
+
+const char                      *AcpiGbl_SmDecode[] =
+{
+    "ControllerInitiated",
+    "DeviceInitiated"
+};
+
+/* SPI serial bus wire mode */
+
+const char                      *AcpiGbl_WmDecode[] =
+{
+    "FourWireMode",
+    "ThreeWireMode"
+};
+
+/* SPI serial clock phase */
+
+const char                      *AcpiGbl_CphDecode[] =
+{
+    "ClockPhaseFirst",
+    "ClockPhaseSecond"
+};
+
+/* SPI serial bus clock polarity */
+
+const char                      *AcpiGbl_CpoDecode[] =
+{
+    "ClockPolarityLow",
+    "ClockPolarityHigh"
+};
+
+/* SPI serial bus device polarity */
+
+const char                      *AcpiGbl_DpDecode[] =
+{
+    "PolarityLow",
+    "PolarityHigh"
+};
+
+/* UART serial bus endian */
+
+const char                      *AcpiGbl_EdDecode[] =
+{
+    "LittleEndian",
+    "BigEndian"
+};
+
+/* UART serial bus bits per byte */
+
+const char                      *AcpiGbl_BpbDecode[] =
+{
+    "DataBitsFive",
+    "DataBitsSix",
+    "DataBitsSeven",
+    "DataBitsEight",
+    "DataBitsNine",
+    "/* UNKNOWN Bits per byte */",
+    "/* UNKNOWN Bits per byte */",
+    "/* UNKNOWN Bits per byte */"
+};
+
+/* UART serial bus stop bits */
+
+const char                      *AcpiGbl_SbDecode[] =
+{
+    "StopBitsNone",
+    "StopBitsOne",
+    "StopBitsOnePlusHalf",
+    "StopBitsTwo"
+};
+
+/* UART serial bus flow control */
+
+const char                      *AcpiGbl_FcDecode[] =
+{
+    "FlowControlNone",
+    "FlowControlHardware",
+    "FlowControlXON",
+    "/* UNKNOWN flow control keyword */"
+};
+
+/* UART serial bus parity type */
+
+const char                      *AcpiGbl_PtDecode[] =
+{
+    "ParityTypeNone",
+    "ParityTypeEven",
+    "ParityTypeOdd",
+    "ParityTypeMark",
+    "ParityTypeSpace",
+    "/* UNKNOWN parity keyword */",
+    "/* UNKNOWN parity keyword */",
+    "/* UNKNOWN parity keyword */"
+};
+
 #endif
 
 
@@ -200,7 +348,7 @@
     ACPI_AML_SIZE_SMALL (AML_RESOURCE_END_DEPENDENT),
     ACPI_AML_SIZE_SMALL (AML_RESOURCE_IO),
     ACPI_AML_SIZE_SMALL (AML_RESOURCE_FIXED_IO),
-    0,
+    ACPI_AML_SIZE_SMALL (AML_RESOURCE_FIXED_DMA),
     0,
     0,
     0,
@@ -220,7 +368,18 @@
     ACPI_AML_SIZE_LARGE (AML_RESOURCE_ADDRESS16),
     ACPI_AML_SIZE_LARGE (AML_RESOURCE_EXTENDED_IRQ),
     ACPI_AML_SIZE_LARGE (AML_RESOURCE_ADDRESS64),
-    ACPI_AML_SIZE_LARGE (AML_RESOURCE_EXTENDED_ADDRESS64)
+    ACPI_AML_SIZE_LARGE (AML_RESOURCE_EXTENDED_ADDRESS64),
+    ACPI_AML_SIZE_LARGE (AML_RESOURCE_GPIO),
+    0,
+    ACPI_AML_SIZE_LARGE (AML_RESOURCE_COMMON_SERIALBUS),
+};
+
+const UINT8                 AcpiGbl_ResourceAmlSerialBusSizes[] =
+{
+    0,
+    ACPI_AML_SIZE_LARGE (AML_RESOURCE_I2C_SERIALBUS),
+    ACPI_AML_SIZE_LARGE (AML_RESOURCE_SPI_SERIALBUS),
+    ACPI_AML_SIZE_LARGE (AML_RESOURCE_UART_SERIALBUS),
 };
 
 
@@ -238,35 +397,49 @@
     0,
     0,
     0,
-    ACPI_SMALL_VARIABLE_LENGTH,
-    ACPI_FIXED_LENGTH,
-    ACPI_SMALL_VARIABLE_LENGTH,
-    ACPI_FIXED_LENGTH,
-    ACPI_FIXED_LENGTH,
-    ACPI_FIXED_LENGTH,
+    ACPI_SMALL_VARIABLE_LENGTH,     /* 04 IRQ */
+    ACPI_FIXED_LENGTH,              /* 05 DMA */
+    ACPI_SMALL_VARIABLE_LENGTH,     /* 06 StartDependentFunctions */
+    ACPI_FIXED_LENGTH,              /* 07 EndDependentFunctions */
+    ACPI_FIXED_LENGTH,              /* 08 IO */
+    ACPI_FIXED_LENGTH,              /* 09 FixedIO */
+    ACPI_FIXED_LENGTH,              /* 0A FixedDMA */
     0,
     0,
     0,
-    0,
-    ACPI_VARIABLE_LENGTH,
-    ACPI_FIXED_LENGTH,
+    ACPI_VARIABLE_LENGTH,           /* 0E VendorShort */
+    ACPI_FIXED_LENGTH,              /* 0F EndTag */
 
     /* Large descriptors */
 
     0,
-    ACPI_FIXED_LENGTH,
-    ACPI_FIXED_LENGTH,
+    ACPI_FIXED_LENGTH,              /* 01 Memory24 */
+    ACPI_FIXED_LENGTH,              /* 02 GenericRegister */
     0,
-    ACPI_VARIABLE_LENGTH,
-    ACPI_FIXED_LENGTH,
-    ACPI_FIXED_LENGTH,
-    ACPI_VARIABLE_LENGTH,
-    ACPI_VARIABLE_LENGTH,
-    ACPI_VARIABLE_LENGTH,
-    ACPI_VARIABLE_LENGTH,
-    ACPI_FIXED_LENGTH
+    ACPI_VARIABLE_LENGTH,           /* 04 VendorLong */
+    ACPI_FIXED_LENGTH,              /* 05 Memory32 */
+    ACPI_FIXED_LENGTH,              /* 06 Memory32Fixed */
+    ACPI_VARIABLE_LENGTH,           /* 07 Dword* address */
+    ACPI_VARIABLE_LENGTH,           /* 08 Word* address */
+    ACPI_VARIABLE_LENGTH,           /* 09 ExtendedIRQ */
+    ACPI_VARIABLE_LENGTH,           /* 0A Qword* address */
+    ACPI_FIXED_LENGTH,              /* 0B Extended* address */
+    ACPI_VARIABLE_LENGTH,           /* 0C Gpio* */
+    0,
+    ACPI_VARIABLE_LENGTH            /* 0E *SerialBus */
 };
 
+/*
+ * For the iASL compiler/disassembler, we don't want any error messages
+ * because the disassembler uses the resource validation code to determine
+ * if Buffer objects are actually Resource Templates.
+ */
+#ifdef ACPI_ASL_COMPILER
+#define ACPI_RESOURCE_ERROR(plist)
+#else
+#define ACPI_RESOURCE_ERROR(plist)  ACPI_ERROR(plist)
+#endif
+
 
 /*******************************************************************************
  *
@@ -297,6 +470,7 @@
     UINT8                   ResourceIndex;
     UINT32                  Length;
     UINT32                  Offset = 0;
+    UINT8                   EndTag[2] = {0x79, 0x00};
 
 
     ACPI_FUNCTION_TRACE (UtWalkAmlResources);
@@ -322,6 +496,10 @@
         Status = AcpiUtValidateResource (Aml, &ResourceIndex);
         if (ACPI_FAILURE (Status))
         {
+            /*
+             * Exit on failure. Cannot continue because the descriptor length
+             * may be bogus also.
+             */
             return_ACPI_STATUS (Status);
         }
 
@@ -336,7 +514,7 @@
             Status = UserFunction (Aml, Length, Offset, ResourceIndex, Context);
             if (ACPI_FAILURE (Status))
             {
-                return (Status);
+                return_ACPI_STATUS (Status);
             }
         }
 
@@ -371,7 +549,19 @@
 
     /* Did not find an EndTag descriptor */
 
-    return (AE_AML_NO_RESOURCE_END_TAG);
+    if (UserFunction)
+    {
+        /* Insert an EndTag anyway. AcpiRsGetListLength always leaves room */
+
+        (void) AcpiUtValidateResource (EndTag, &ResourceIndex);
+        Status = UserFunction (EndTag, 2, Offset, ResourceIndex, Context);
+        if (ACPI_FAILURE (Status))
+        {
+            return_ACPI_STATUS (Status);
+        }
+    }
+
+    return_ACPI_STATUS (AE_AML_NO_RESOURCE_END_TAG);
 }
 
 
@@ -396,6 +586,7 @@
     void                    *Aml,
     UINT8                   *ReturnIndex)
 {
+    AML_RESOURCE            *AmlResource;
     UINT8                   ResourceType;
     UINT8                   ResourceIndex;
     ACPI_RS_LENGTH          ResourceLength;
@@ -420,7 +611,7 @@
 
         if (ResourceType > ACPI_RESOURCE_NAME_LARGE_MAX)
         {
-            return (AE_AML_INVALID_RESOURCE_TYPE);
+            goto InvalidResource;
         }
 
         /*
@@ -439,17 +630,18 @@
             ((ResourceType & ACPI_RESOURCE_NAME_SMALL_MASK) >> 3);
     }
 
-    /* Check validity of the resource type, zero indicates name is invalid */
-
+    /*
+     * Check validity of the resource type, via AcpiGbl_ResourceTypes. Zero
+     * indicates an invalid resource.
+     */
     if (!AcpiGbl_ResourceTypes[ResourceIndex])
     {
-        return (AE_AML_INVALID_RESOURCE_TYPE);
+        goto InvalidResource;
     }
 
-
     /*
-     * 2) Validate the ResourceLength field. This ensures that the length
-     *    is at least reasonable, and guarantees that it is non-zero.
+     * Validate the ResourceLength field. This ensures that the length
+     * is at least reasonable, and guarantees that it is non-zero.
      */
     ResourceLength = AcpiUtGetResourceLength (Aml);
     MinimumResourceLength = AcpiGbl_ResourceAmlSizes[ResourceIndex];
@@ -464,7 +656,7 @@
 
         if (ResourceLength != MinimumResourceLength)
         {
-            return (AE_AML_BAD_RESOURCE_LENGTH);
+            goto BadResourceLength;
         }
         break;
 
@@ -474,7 +666,7 @@
 
         if (ResourceLength < MinimumResourceLength)
         {
-            return (AE_AML_BAD_RESOURCE_LENGTH);
+            goto BadResourceLength;
         }
         break;
 
@@ -485,7 +677,7 @@
         if ((ResourceLength > MinimumResourceLength) ||
             (ResourceLength < (MinimumResourceLength - 1)))
         {
-            return (AE_AML_BAD_RESOURCE_LENGTH);
+            goto BadResourceLength;
         }
         break;
 
@@ -493,7 +685,22 @@
 
         /* Shouldn't happen (because of validation earlier), but be sure */
 
-        return (AE_AML_INVALID_RESOURCE_TYPE);
+        goto InvalidResource;
+    }
+
+    AmlResource = ACPI_CAST_PTR (AML_RESOURCE, Aml);
+    if (ResourceType == ACPI_RESOURCE_NAME_SERIAL_BUS)
+    {
+        /* Validate the BusType field */
+
+        if ((AmlResource->CommonSerialBus.Type == 0) ||
+            (AmlResource->CommonSerialBus.Type > AML_RESOURCE_MAX_SERIALBUSTYPE))
+        {
+            ACPI_RESOURCE_ERROR ((AE_INFO,
+                "Invalid/unsupported SerialBus resource descriptor: BusType 0x%2.2X",
+                AmlResource->CommonSerialBus.Type));
+            return (AE_AML_INVALID_RESOURCE_TYPE);
+        }
     }
 
     /* Optionally return the resource table index */
@@ -504,6 +711,22 @@
     }
 
     return (AE_OK);
+
+
+InvalidResource:
+
+    ACPI_RESOURCE_ERROR ((AE_INFO,
+        "Invalid/unsupported resource descriptor: Type 0x%2.2X",
+        ResourceType));
+    return (AE_AML_INVALID_RESOURCE_TYPE);
+
+BadResourceLength:
+
+    ACPI_RESOURCE_ERROR ((AE_INFO,
+        "Invalid resource descriptor length: Type "
+        "0x%2.2X, Length 0x%4.4X, MinLength 0x%4.4X",
+        ResourceType, ResourceLength, MinimumResourceLength));
+    return (AE_AML_BAD_RESOURCE_LENGTH);
 }
 
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/dev/acpica/utilities/utxfmutex.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/sys/contrib/dev/acpica/utilities/utxfmutex.c	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,213 @@
+/*******************************************************************************
+ *
+ * Module Name: utxfmutex - external AML mutex access functions
+ *
+ ******************************************************************************/
+
+/*
+ * Copyright (C) 2000 - 2011, Intel Corp.
+ * 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.
+ * 3. Neither the names of the above-listed copyright holders nor the names
+ *    of any contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ * Alternatively, this software may be distributed under the terms of the
+ * GNU General Public License ("GPL") version 2 as published by the Free
+ * Software Foundation.
+ *
+ * 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.
+ */
+
+#define __UTXFMUTEX_C__
+
+#include <contrib/dev/acpica/include/acpi.h>
+#include <contrib/dev/acpica/include/accommon.h>
+#include <contrib/dev/acpica/include/acnamesp.h>
+
+
+#define _COMPONENT          ACPI_UTILITIES
+        ACPI_MODULE_NAME    ("utxfmutex")
+
+
+/* Local prototypes */
+
+static ACPI_STATUS
+AcpiUtGetMutexObject (
+    ACPI_HANDLE             Handle,
+    ACPI_STRING             Pathname,
+    ACPI_OPERAND_OBJECT     **RetObj);
+
+
+/*******************************************************************************
+ *
+ * FUNCTION:    AcpiUtGetMutexObject
+ *
+ * PARAMETERS:  Handle              - Mutex or prefix handle (optional)
+ *              Pathname            - Mutex pathname (optional)
+ *              RetObj              - Where the mutex object is returned
+ *
+ * RETURN:      Status
+ *
+ * DESCRIPTION: Get an AML mutex object. The mutex node is pointed to by
+ *              Handle:Pathname. Either Handle or Pathname can be NULL, but
+ *              not both.
+ *
+ ******************************************************************************/
+
+static ACPI_STATUS
+AcpiUtGetMutexObject (
+    ACPI_HANDLE             Handle,
+    ACPI_STRING             Pathname,
+    ACPI_OPERAND_OBJECT     **RetObj)
+{
+    ACPI_NAMESPACE_NODE     *MutexNode;
+    ACPI_OPERAND_OBJECT     *MutexObj;
+    ACPI_STATUS             Status;
+
+
+    /* Parameter validation */
+
+    if (!RetObj || (!Handle && !Pathname))
+    {
+        return (AE_BAD_PARAMETER);
+    }
+
+    /* Get a the namespace node for the mutex */
+
+    MutexNode = Handle;
+    if (Pathname != NULL)
+    {
+        Status = AcpiGetHandle (Handle, Pathname,
+            ACPI_CAST_PTR (ACPI_HANDLE, &MutexNode));
+        if (ACPI_FAILURE (Status))
+        {
+            return (Status);
+        }
+    }
+
+    /* Ensure that we actually have a Mutex object */
+
+    if (!MutexNode ||
+        (MutexNode->Type != ACPI_TYPE_MUTEX))
+    {
+        return (AE_TYPE);
+    }
+
+    /* Get the low-level mutex object */
+
+    MutexObj = AcpiNsGetAttachedObject (MutexNode);
+    if (!MutexObj)
+    {
+        return (AE_NULL_OBJECT);
+    }
+
+    *RetObj = MutexObj;
+    return (AE_OK);
+}
+
+
+/*******************************************************************************
+ *
+ * FUNCTION:    AcpiAcquireMutex
+ *
+ * PARAMETERS:  Handle              - Mutex or prefix handle (optional)
+ *              Pathname            - Mutex pathname (optional)
+ *              Timeout             - Max time to wait for the lock (millisec)
+ *
+ * RETURN:      Status
+ *
+ * DESCRIPTION: Acquire an AML mutex. This is a device driver interface to
+ *              AML mutex objects, and allows for transaction locking between
+ *              drivers and AML code. The mutex node is pointed to by
+ *              Handle:Pathname. Either Handle or Pathname can be NULL, but
+ *              not both.
+ *
+ ******************************************************************************/
+
+ACPI_STATUS
+AcpiAcquireMutex (
+    ACPI_HANDLE             Handle,
+    ACPI_STRING             Pathname,
+    UINT16                  Timeout)
+{
+    ACPI_STATUS             Status;
+    ACPI_OPERAND_OBJECT     *MutexObj;
+
+
+    /* Get the low-level mutex associated with Handle:Pathname */
+
+    Status = AcpiUtGetMutexObject (Handle, Pathname, &MutexObj);
+    if (ACPI_FAILURE (Status))
+    {
+        return (Status);
+    }
+
+    /* Acquire the OS mutex */
+
+    Status = AcpiOsAcquireMutex (MutexObj->Mutex.OsMutex, Timeout);
+    return (Status);
+}
+
+
+/*******************************************************************************
+ *
+ * FUNCTION:    AcpiReleaseMutex
+ *
+ * PARAMETERS:  Handle              - Mutex or prefix handle (optional)
+ *              Pathname            - Mutex pathname (optional)
+ *
+ * RETURN:      Status
+ *
+ * DESCRIPTION: Release an AML mutex. This is a device driver interface to
+ *              AML mutex objects, and allows for transaction locking between
+ *              drivers and AML code. The mutex node is pointed to by
+ *              Handle:Pathname. Either Handle or Pathname can be NULL, but
+ *              not both.
+ *
+ ******************************************************************************/
+
+ACPI_STATUS
+AcpiReleaseMutex (
+    ACPI_HANDLE             Handle,
+    ACPI_STRING             Pathname)
+{
+    ACPI_STATUS             Status;
+    ACPI_OPERAND_OBJECT     *MutexObj;
+
+
+    /* Get the low-level mutex associated with Handle:Pathname */
+
+    Status = AcpiUtGetMutexObject (Handle, Pathname, &MutexObj);
+    if (ACPI_FAILURE (Status))
+    {
+        return (Status);
+    }
+
+    /* Release the OS mutex */
+
+    AcpiOsReleaseMutex (MutexObj->Mutex.OsMutex);
+    return (AE_OK);
+}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/ipfilter/netinet/ip_compat.h
--- a/head/sys/contrib/ipfilter/netinet/ip_compat.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/ipfilter/netinet/ip_compat.h	Tue Dec 06 20:26:16 2011 +0200
@@ -4,7 +4,7 @@
  * See the IPFILTER.LICENCE file for details on licencing.
  *
  * @(#)ip_compat.h	1.8 1/14/96
- * $FreeBSD$
+ * $FreeBSD: head/sys/contrib/ipfilter/netinet/ip_compat.h 227957 2011-11-24 21:23:58Z rmh $
  * Id: ip_compat.h,v 2.142.2.57 2007/10/10 09:51:42 darrenr Exp $
  */
 
@@ -985,10 +985,10 @@
 typedef struct mbuf mb_t;
 # endif /* _KERNEL */
 
-# if __FreeBSD__ < 3
+# if __FreeBSD_version < 300000
 #  include <machine/spl.h>
 # else
-#  if __FreeBSD__ == 3
+#  if __FreeBSD_version < 400000
 #   if defined(IPFILTER_LKM) && !defined(ACTUALLY_LKM_NOT_KERNEL)
 #    define	ACTUALLY_LKM_NOT_KERNEL
 #   endif
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/ipfilter/netinet/ip_proxy.c
--- a/head/sys/contrib/ipfilter/netinet/ip_proxy.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/ipfilter/netinet/ip_proxy.c	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-/*	$FreeBSD$	*/
+/*	$FreeBSD: head/sys/contrib/ipfilter/netinet/ip_proxy.c 227957 2011-11-24 21:23:58Z rmh $	*/
 
 /*
  * Copyright (C) 1997-2003 by Darren Reed.
@@ -63,7 +63,7 @@
 # include <sys/stream.h>
 # include <sys/kmem.h>
 #endif
-#if __FreeBSD__ > 2
+#if __FreeBSD_version >= 300000
 # include <sys/queue.h>
 #endif
 #include <net/if.h>
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/octeon-sdk/cvmx-helper-board.c
--- a/head/sys/contrib/octeon-sdk/cvmx-helper-board.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/octeon-sdk/cvmx-helper-board.c	Tue Dec 06 20:26:16 2011 +0200
@@ -259,12 +259,15 @@
 	case CVMX_BOARD_TYPE_CUST_DLINK_DSR500:
 	case CVMX_BOARD_TYPE_CUST_DLINK_DSR500N:
 	case CVMX_BOARD_TYPE_CUST_DLINK_DSR1000N:
-	    if (ipd_port == 0 || ipd_port == 1)
-	        return -1; /* Port 0, 1 connect to switch */
-	    else if (ipd_port == 2)
-	        return 8; /* Port 2 connect to B5081 */
-	    else
-	        return -1;
+//	    if (ipd_port == 0 || ipd_port == 1)
+//	        return -1; /* Port 0, 1 connect to switch */
+//	    else if (ipd_port == 2)
+//	        return 8; /* Port 2 connect to B5081 */
+//	    else
+//	        return -1;
+	    if (ipd_port == 0)	return -1;
+	    if (ipd_port == 1)	return -1;
+	    if (ipd_port == 2)	return -1;
 	case CVMX_BOARD_TYPE_CUST_WSX16:
 		if (ipd_port >= 0 && ipd_port <= 3)
 			return ipd_port;
@@ -426,15 +429,15 @@
 	case CVMX_BOARD_TYPE_CUST_DLINK_DSR500:
 	case CVMX_BOARD_TYPE_CUST_DLINK_DSR500N:
 	case CVMX_BOARD_TYPE_CUST_DLINK_DSR1000N:
-            if (ipd_port == 0 || ipd_port == 1) //BCM53115 in RGMII 0,1
-            {
+//            if (ipd_port == 0 || ipd_port == 1) //BCM53115 in RGMII 0,1
+//            {
                 result.s.link_up = 1;
                 result.s.full_duplex = 1;
                 result.s.speed = 1000;
                 return result;
-            }
-            else /* The other port uses a broadcom PHY (B5081) */
-                is_broadcom_phy = 1;
+//            }
+//            else /* The other port uses a broadcom PHY (B5081) */
+//                is_broadcom_phy = 1;
 	    break;
 #if defined(OCTEON_VENDOR_LANNER)
 	case CVMX_BOARD_TYPE_CUST_LANNER_MR730:
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/contrib/pf/net/pf.c
--- a/head/sys/contrib/pf/net/pf.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/contrib/pf/net/pf.c	Tue Dec 06 20:26:16 2011 +0200
@@ -40,7 +40,7 @@
 #include "opt_inet6.h"
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/contrib/pf/net/pf.c 226938 2011-10-30 14:55:00Z kevlo $");
+__FBSDID("$FreeBSD: head/sys/contrib/pf/net/pf.c 228150 2011-11-30 08:47:17Z glebius $");
 #endif
 
 #ifdef __FreeBSD__
@@ -3770,8 +3770,8 @@
 		 * replies through it.
 		 */
 #ifdef __FreeBSD__
-		if (pfsync_defer_ptr != NULL)
-			pfsync_defer_ptr(*sm, m);
+		if (pfsync_defer_ptr != NULL &&
+			pfsync_defer_ptr(*sm, m))
 #else
 		if (pfsync_defer(*sm, m))
 #endif
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/acpica/acpi_battery.c
--- a/head/sys/dev/acpica/acpi_battery.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/acpica/acpi_battery.c	Tue Dec 06 20:26:16 2011 +0200
@@ -26,7 +26,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/sys/dev/acpica/acpi_battery.c 227992 2011-11-26 13:43:50Z dumbbell $");
 
 #include "opt_acpi.h"
 #include <sys/param.h>
@@ -205,6 +205,14 @@
 	    bif->lfcap = (bif->lfcap * bif->dvol) / 1000;
 	}
 
+	/*
+	 * The calculation above may set bif->lfcap to zero. This was
+	 * seen on a laptop with a broken battery. The result of the
+	 * division was rounded to zero.
+	 */
+	if (!acpi_battery_bif_valid(bif))
+	    continue;
+
 	/* Calculate percent capacity remaining. */
 	bi[i].cap = (100 * bst[i].cap) / bif->lfcap;
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/ahci/ahci.c
--- a/head/sys/dev/ahci/ahci.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/ahci/ahci.c	Tue Dec 06 20:26:16 2011 +0200
@@ -25,7 +25,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/ahci/ahci.c 227849 2011-11-22 21:56:55Z hselasky $");
+__FBSDID("$FreeBSD: head/sys/dev/ahci/ahci.c 228200 2011-12-02 12:52:33Z mav $");
 
 #include <sys/param.h>
 #include <sys/module.h>
@@ -293,6 +293,9 @@
 #define RECOVERY_REQUEST_SENSE	2
 #define recovery_slot		spriv_field1
 
+static int force_ahci = 1;
+TUNABLE_INT("hw.ahci.force", &force_ahci);
+
 static int
 ahci_probe(device_t dev)
 {
@@ -310,7 +313,8 @@
 	for (i = 0; ahci_ids[i].id != 0; i++) {
 		if (ahci_ids[i].id == devid &&
 		    ahci_ids[i].rev <= revid &&
-		    (valid || !(ahci_ids[i].quirks & AHCI_Q_NOFORCE))) {
+		    (valid || (force_ahci == 1 &&
+		     !(ahci_ids[i].quirks & AHCI_Q_NOFORCE)))) {
 			/* Do not attach JMicrons with single PCI function. */
 			if (pci_get_vendor(dev) == 0x197b &&
 			    (pci_read_config(dev, 0xdf, 1) & 0x40) == 0)
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/amd/amd.c
--- a/head/sys/dev/amd/amd.c	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,2539 +0,0 @@
-/*-
- *********************************************************************
- *	FILE NAME  : amd.c
- *	     BY    : C.L. Huang 	(ching at tekram.com.tw)
- *		     Erich Chen     (erich at tekram.com.tw)
- *	Description: Device Driver for the amd53c974 PCI Bus Master
- *		     SCSI Host adapter found on cards such as
- *		     the Tekram DC-390(T).
- * (C)Copyright 1995-1999 Tekram Technology Co., Ltd.
- *
- * 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$
- */
-
-/*
- *********************************************************************
- *	HISTORY:
- *
- *	REV#	DATE	NAME    	DESCRIPTION
- *	1.00  07/02/96	CLH	        First release for RELEASE-2.1.0
- *	1.01  08/20/96	CLH	        Update for RELEASE-2.1.5
- *	1.02  11/06/96	CLH	        Fixed more than 1 LUN scanning
- *	1.03  12/20/96	CLH	        Modify to support 2.2-ALPHA
- *	1.04  12/26/97	CLH	        Modify to support RELEASE-2.2.5
- *	1.05  01/01/99  ERICH CHEN	Modify to support RELEASE-3.0.x (CAM)
- *********************************************************************
- */
-
-/* #define AMD_DEBUG0		*/
-/* #define AMD_DEBUG_SCSI_PHASE */
-
-#include <sys/param.h>
-
-#include <sys/systm.h>
-#include <sys/queue.h>
-#include <sys/kernel.h>
-#include <sys/module.h>
-#include <sys/lock.h>
-#include <sys/mutex.h>
-#include <sys/malloc.h>
-
-#include <vm/vm.h>
-#include <vm/pmap.h>
-
-#include <machine/bus.h>
-#include <machine/resource.h>
-#include <sys/bus.h>
-#include <sys/rman.h>
-
-#include <cam/cam.h>
-#include <cam/cam_ccb.h>
-#include <cam/cam_sim.h>
-#include <cam/cam_xpt_sim.h>
-#include <cam/cam_debug.h>
-
-#include <cam/scsi/scsi_all.h>
-#include <cam/scsi/scsi_message.h>
-
-#include <dev/pci/pcivar.h>
-#include <dev/pci/pcireg.h>
-#include <dev/amd/amd.h>
-
-#define PCI_DEVICE_ID_AMD53C974 	0x20201022ul
-#define PCI_BASE_ADDR0	    		0x10
-
-typedef u_int (phase_handler_t)(struct amd_softc *, struct amd_srb *, u_int);
-typedef phase_handler_t *phase_handler_func_t;
-
-static void amd_intr(void *vamd);
-static int amdstart(struct amd_softc *amd, struct amd_srb * pSRB);
-static phase_handler_t amd_NopPhase;
-
-static phase_handler_t amd_DataOutPhase0;
-static phase_handler_t amd_DataInPhase0;
-#define amd_CommandPhase0 amd_NopPhase
-static phase_handler_t amd_StatusPhase0;
-static phase_handler_t amd_MsgOutPhase0;
-static phase_handler_t amd_MsgInPhase0;
-static phase_handler_t amd_DataOutPhase1;
-static phase_handler_t amd_DataInPhase1;
-static phase_handler_t amd_CommandPhase1;
-static phase_handler_t amd_StatusPhase1;
-static phase_handler_t amd_MsgOutPhase1;
-static phase_handler_t amd_MsgInPhase1;
-
-static void	amdsetupcommand(struct amd_softc *amd, struct amd_srb *srb);
-static int	amdparsemsg(struct amd_softc *amd);
-static int	amdhandlemsgreject(struct amd_softc *amd);
-static void	amdconstructsdtr(struct amd_softc *amd,
-				 u_int period, u_int offset);
-static u_int	amdfindclockrate(struct amd_softc *amd, u_int *period);
-static int	amdsentmsg(struct amd_softc *amd, u_int msgtype, int full);
-
-static void DataIO_Comm(struct amd_softc *amd, struct amd_srb *pSRB, u_int dir);
-static void amd_Disconnect(struct amd_softc *amd);
-static void amd_Reselect(struct amd_softc *amd);
-static void SRBdone(struct amd_softc *amd, struct amd_srb *pSRB);
-static void amd_ScsiRstDetect(struct amd_softc *amd);
-static void amd_ResetSCSIBus(struct amd_softc *amd);
-static void RequestSense(struct amd_softc *amd, struct amd_srb *pSRB);
-static void amd_InvalidCmd(struct amd_softc *amd);
-
-static void amd_dmamap_cb(void *arg, bus_dma_segment_t *segs, int nsegs,
-			  int error);
-
-#if 0
-static void amd_timeout(void *arg1);
-static void amd_reset(struct amd_softc *amd);
-#endif
-static u_int8_t * phystovirt(struct amd_srb *pSRB, u_int32_t xferCnt);
-
-void    amd_linkSRB(struct amd_softc *amd);
-static int amd_init(device_t);
-static void amd_load_defaults(struct amd_softc *amd);
-static void amd_load_eeprom_or_defaults(struct amd_softc *amd);
-static int amd_EEpromInDO(struct amd_softc *amd);
-static u_int16_t EEpromGetData1(struct amd_softc *amd);
-static void amd_EnDisableCE(struct amd_softc *amd, int mode, int *regval);
-static void amd_EEpromOutDI(struct amd_softc *amd, int *regval, int Carry);
-static void amd_Prepare(struct amd_softc *amd, int *regval, u_int8_t EEpromCmd);
-static void amd_ReadEEprom(struct amd_softc *amd);
-
-static int amd_probe(device_t);
-static int amd_attach(device_t);
-static void amdcompletematch(struct amd_softc *amd, target_id_t target,
-			     lun_id_t lun, u_int tag, struct srb_queue *queue,
-			     cam_status status);
-static void amdsetsync(struct amd_softc *amd, u_int target, u_int clockrate,
-		       u_int period, u_int offset, u_int type);
-static void amdsettags(struct amd_softc *amd, u_int target, int tagenb);
-
-static __inline void amd_clear_msg_state(struct amd_softc *amd);
-
-static __inline void
-amd_clear_msg_state(struct amd_softc *amd)
-{
-	amd->msgout_len = 0;
-	amd->msgout_index = 0;
-	amd->msgin_index = 0;
-}
-
-static __inline uint32_t
-amd_get_sense_bufaddr(struct amd_softc *amd, struct amd_srb *pSRB)
-{
-	int offset;
-
-	offset = pSRB->TagNumber;
-	return (amd->sense_busaddr + (offset * sizeof(struct scsi_sense_data)));
-}
-
-static __inline struct scsi_sense_data *
-amd_get_sense_buf(struct amd_softc *amd, struct amd_srb *pSRB)
-{
-	int offset;
-
-	offset = pSRB->TagNumber;
-	return (&amd->sense_buffers[offset]);
-}
-
-static __inline uint32_t
-amd_get_sense_bufsize(struct amd_softc *amd, struct amd_srb *pSRB)
-{
-	return (sizeof(struct scsi_sense_data));
-}
-
-/* CAM SIM entry points */
-#define ccb_srb_ptr spriv_ptr0
-#define ccb_amd_ptr spriv_ptr1
-static void	amd_action(struct cam_sim *sim, union ccb *ccb);
-static void	amd_poll(struct cam_sim *sim);
-
-/*
- * State engine function tables indexed by SCSI phase number
- */
-phase_handler_func_t amd_SCSI_phase0[] = {
-	amd_DataOutPhase0,
-	amd_DataInPhase0,
-	amd_CommandPhase0,
-	amd_StatusPhase0,
-	amd_NopPhase,
-	amd_NopPhase,
-	amd_MsgOutPhase0,
-	amd_MsgInPhase0
-};
-
-phase_handler_func_t amd_SCSI_phase1[] = {
-	amd_DataOutPhase1,
-	amd_DataInPhase1,
-	amd_CommandPhase1,
-	amd_StatusPhase1,
-	amd_NopPhase,
-	amd_NopPhase,
-	amd_MsgOutPhase1,
-	amd_MsgInPhase1
-};
-
-/*
- * EEProm/BIOS negotiation periods
- */
-u_int8_t   eeprom_period[] = {
-	 25,	/* 10.0MHz */
-	 32,	/*  8.0MHz */
-	 38,	/*  6.6MHz */
-	 44,	/*  5.7MHz */
-	 50,	/*  5.0MHz */
-	 63,	/*  4.0MHz */
-	 83,	/*  3.0MHz */
-	125	/*  2.0MHz */
-};
-
-/*
- * chip clock setting to SCSI specified sync parameter table.
- */
-u_int8_t tinfo_sync_period[] = {
-	25,	/* 10.0 */
-	32,	/* 8.0 */
-	38,	/* 6.6 */
-	44,	/* 5.7 */
-	50,	/* 5.0 */
-	57,	/* 4.4 */
-	63,	/* 4.0 */
-	70,	/* 3.6 */
-	76,	/* 3.3 */
-	83	/* 3.0 */
-};
-
-static __inline struct amd_srb *
-amdgetsrb(struct amd_softc * amd)
-{
-	int     intflag;
-	struct amd_srb *    pSRB;
-
-	intflag = splcam();
-	pSRB = TAILQ_FIRST(&amd->free_srbs);
-	if (pSRB)
-		TAILQ_REMOVE(&amd->free_srbs, pSRB, links);
-	splx(intflag);
-	return (pSRB);
-}
-
-static void
-amdsetupcommand(struct amd_softc *amd, struct amd_srb *srb)
-{
-	struct scsi_request_sense sense_cmd;
-	u_int8_t *cdb;
-	u_int cdb_len;
-
-	if (srb->SRBFlag & AUTO_REQSENSE) {
-		sense_cmd.opcode = REQUEST_SENSE;
-		sense_cmd.byte2 = srb->pccb->ccb_h.target_lun << 5;
-		sense_cmd.unused[0] = 0;
-		sense_cmd.unused[1] = 0;
-		sense_cmd.length = sizeof(struct scsi_sense_data);
-		sense_cmd.control = 0;
-		cdb = &sense_cmd.opcode;
-		cdb_len = sizeof(sense_cmd);
-	} else {
-		cdb = &srb->CmdBlock[0];
-		cdb_len = srb->ScsiCmdLen;
-	}
-	amd_write8_multi(amd, SCSIFIFOREG, cdb, cdb_len);
-}
-
-/*
- * Attempt to start a waiting transaction.  Interrupts must be disabled
- * upon entry to this function.
- */
-static void
-amdrunwaiting(struct amd_softc *amd) {
-	struct amd_srb *srb;
-
-	if (amd->last_phase != SCSI_BUS_FREE)
-		return;
-
-	srb = TAILQ_FIRST(&amd->waiting_srbs);
-	if (srb == NULL)
-		return;
-	
-	if (amdstart(amd, srb) == 0) {
-		TAILQ_REMOVE(&amd->waiting_srbs, srb, links);
-		TAILQ_INSERT_HEAD(&amd->running_srbs, srb, links);
-	}
-}
-
-static void
-amdexecutesrb(void *arg, bus_dma_segment_t *dm_segs, int nseg, int error)
-{
-	struct	 amd_srb *srb;
-	union	 ccb *ccb;
-	struct	 amd_softc *amd;
-	int	 s;
-
-	srb = (struct amd_srb *)arg;
-	ccb = srb->pccb;
-	amd = (struct amd_softc *)ccb->ccb_h.ccb_amd_ptr;
-
-	if (error != 0) {
-		if (error != EFBIG)
-			printf("amd%d: Unexepected error 0x%x returned from "
-			       "bus_dmamap_load\n", amd->unit, error);
-		if (ccb->ccb_h.status == CAM_REQ_INPROG) {
-			xpt_freeze_devq(ccb->ccb_h.path, /*count*/1);
-			ccb->ccb_h.status = CAM_REQ_TOO_BIG|CAM_DEV_QFRZN;
-		}
-		TAILQ_INSERT_HEAD(&amd->free_srbs, srb, links);
-		xpt_done(ccb);
-		return;
-	}
-
-	if (nseg != 0) {
-		struct amd_sg *sg;
-		bus_dma_segment_t *end_seg;
-		bus_dmasync_op_t op;
-
-		end_seg = dm_segs + nseg;
-
-		/* Copy the segments into our SG list */
-		srb->pSGlist = &srb->SGsegment[0];
-		sg = srb->pSGlist;
-		while (dm_segs < end_seg) {
-			sg->SGXLen = dm_segs->ds_len;
-			sg->SGXPtr = dm_segs->ds_addr;
-			sg++;
-			dm_segs++;
-		}
-
-		if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN)
-			op = BUS_DMASYNC_PREREAD;
-		else
-			op = BUS_DMASYNC_PREWRITE;
-
-		bus_dmamap_sync(amd->buffer_dmat, srb->dmamap, op);
-
-	}
-	srb->SGcount = nseg;
-	srb->SGIndex = 0;
-	srb->AdaptStatus = 0;
-	srb->TargetStatus = 0;
-	srb->MsgCnt = 0;
-	srb->SRBStatus = 0;
-	srb->SRBFlag = 0;
-	srb->SRBState = 0;
-	srb->TotalXferredLen = 0;
-	srb->SGPhysAddr = 0;
-	srb->SGToBeXferLen = 0;
-	srb->EndMessage = 0;
-
-	s = splcam();
-
-	/*
-	 * Last time we need to check if this CCB needs to
-	 * be aborted.
-	 */
-	if (ccb->ccb_h.status != CAM_REQ_INPROG) {
-		if (nseg != 0)
-			bus_dmamap_unload(amd->buffer_dmat, srb->dmamap);
-		TAILQ_INSERT_HEAD(&amd->free_srbs, srb, links);
-		xpt_done(ccb);
-		splx(s);
-		return;
-	}
-	ccb->ccb_h.status |= CAM_SIM_QUEUED;
-#if 0
-	/* XXX Need a timeout handler */
-	ccb->ccb_h.timeout_ch =
-	    timeout(amdtimeout, (caddr_t)srb,
-		    (ccb->ccb_h.timeout * hz) / 1000);
-#endif
-	TAILQ_INSERT_TAIL(&amd->waiting_srbs, srb, links);
-	amdrunwaiting(amd);
-	splx(s);
-}
-
-static void
-amd_action(struct cam_sim * psim, union ccb * pccb)
-{
-	struct amd_softc *    amd;
-	u_int   target_id;
-
-	CAM_DEBUG(pccb->ccb_h.path, CAM_DEBUG_TRACE, ("amd_action\n"));
-
-	amd = (struct amd_softc *) cam_sim_softc(psim);
-	target_id = pccb->ccb_h.target_id;
-
-	switch (pccb->ccb_h.func_code) {
-	case XPT_SCSI_IO:
-	{
-		struct amd_srb *    pSRB;
-		struct ccb_scsiio *pcsio;
-
-		pcsio = &pccb->csio;
-
-		/*
-		 * Assign an SRB and connect it with this ccb.
-		 */
-		pSRB = amdgetsrb(amd);
-
-		if (!pSRB) {
-			/* Freeze SIMQ */
-			pccb->ccb_h.status = CAM_RESRC_UNAVAIL;
-			xpt_done(pccb);
-			return;
-		}
-		pSRB->pccb = pccb;
-		pccb->ccb_h.ccb_srb_ptr = pSRB;
-		pccb->ccb_h.ccb_amd_ptr = amd;
-		pSRB->ScsiCmdLen = pcsio->cdb_len;
-		bcopy(pcsio->cdb_io.cdb_bytes, pSRB->CmdBlock, pcsio->cdb_len);
-		if ((pccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
-			if ((pccb->ccb_h.flags & CAM_SCATTER_VALID) == 0) {
-				/*
-				 * We've been given a pointer
-				 * to a single buffer.
-				 */
-				if ((pccb->ccb_h.flags & CAM_DATA_PHYS) == 0) {
-					int s;
-					int error;
-
-					s = splsoftvm();
-					error =
-					    bus_dmamap_load(amd->buffer_dmat,
-							    pSRB->dmamap,
-							    pcsio->data_ptr,
-							    pcsio->dxfer_len,
-							    amdexecutesrb,
-							    pSRB, /*flags*/0);
-					if (error == EINPROGRESS) {
-						/*
-						 * So as to maintain
-						 * ordering, freeze the
-						 * controller queue
-						 * until our mapping is
-						 * returned.
-						 */
-						xpt_freeze_simq(amd->psim, 1);
-						pccb->ccb_h.status |=
-						    CAM_RELEASE_SIMQ;
-					}
-					splx(s);
-				} else {
-					struct bus_dma_segment seg;
-
-					/* Pointer to physical buffer */
-					seg.ds_addr =
-					    (bus_addr_t)pcsio->data_ptr;
-					seg.ds_len = pcsio->dxfer_len;
-					amdexecutesrb(pSRB, &seg, 1, 0);
-				}
-			} else {
-				struct bus_dma_segment *segs;
-
-				if ((pccb->ccb_h.flags & CAM_SG_LIST_PHYS) == 0
-				 || (pccb->ccb_h.flags & CAM_DATA_PHYS) != 0) {
-					TAILQ_INSERT_HEAD(&amd->free_srbs,
-							  pSRB, links);
-					pccb->ccb_h.status = CAM_PROVIDE_FAIL;
-					xpt_done(pccb);
-					return;
-				}
-
-				/* Just use the segments provided */
-				segs =
-				    (struct bus_dma_segment *)pcsio->data_ptr;
-				amdexecutesrb(pSRB, segs, pcsio->sglist_cnt, 0);
-			}
-		} else
-			amdexecutesrb(pSRB, NULL, 0, 0);
-		break;
-	}
-	case XPT_PATH_INQ:
-	{
-		struct ccb_pathinq *cpi = &pccb->cpi;
-
-		cpi->version_num = 1;
-		cpi->hba_inquiry = PI_SDTR_ABLE | PI_TAG_ABLE;
-		cpi->target_sprt = 0;
-		cpi->hba_misc = 0;
-		cpi->hba_eng_cnt = 0;
-		cpi->max_target = 7;
-		cpi->max_lun = amd->max_lun;	/* 7 or 0 */
-		cpi->initiator_id = amd->AdaptSCSIID;
-		cpi->bus_id = cam_sim_bus(psim);
-		strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
-		strncpy(cpi->hba_vid, "TRM-AMD", HBA_IDLEN);
-		strncpy(cpi->dev_name, cam_sim_name(psim), DEV_IDLEN);
-		cpi->unit_number = cam_sim_unit(psim);
-                cpi->transport = XPORT_SPI;
-                cpi->transport_version = 2;
-                cpi->protocol = PROTO_SCSI;
-                cpi->protocol_version = SCSI_REV_2;
-		cpi->ccb_h.status = CAM_REQ_CMP;
-		xpt_done(pccb);
-		break;
-	}
-	case XPT_ABORT:
-		pccb->ccb_h.status = CAM_REQ_INVALID;
-		xpt_done(pccb);
-		break;
-	case XPT_RESET_BUS:
-	{
-
-		int     i;
-
-		amd_ResetSCSIBus(amd);
-		amd->ACBFlag = 0;
-
-		for (i = 0; i < 500; i++) {
-			DELAY(1000);	/* Wait until our interrupt
-					 * handler sees it */
-		}
-
-		pccb->ccb_h.status = CAM_REQ_CMP;
-		xpt_done(pccb);
-		break;
-	}
-	case XPT_RESET_DEV:
-		pccb->ccb_h.status = CAM_REQ_INVALID;
-		xpt_done(pccb);
-		break;
-	case XPT_TERM_IO:
-		pccb->ccb_h.status = CAM_REQ_INVALID;
-		xpt_done(pccb);
-		break;
-	case XPT_GET_TRAN_SETTINGS:
-	{
-		struct ccb_trans_settings *cts = &pccb->cts;
-		struct amd_target_info *targ_info = &amd->tinfo[target_id];
-		struct amd_transinfo *tinfo;
-		int     intflag;
-		struct ccb_trans_settings_scsi *scsi =
-		    &cts->proto_specific.scsi;
-		struct ccb_trans_settings_spi *spi =
-		    &cts->xport_specific.spi;
-
-		cts->protocol = PROTO_SCSI;
-		cts->protocol_version = SCSI_REV_2;
-		cts->transport = XPORT_SPI;
-		cts->transport_version = 2;
-
-		intflag = splcam();
-		if (cts->type == CTS_TYPE_CURRENT_SETTINGS) {
-			/* current transfer settings */
-			if (targ_info->disc_tag & AMD_CUR_DISCENB) {
-				spi->flags = CTS_SPI_FLAGS_DISC_ENB;
-			} else {
-				spi->flags = 0;
-			}
-			if (targ_info->disc_tag & AMD_CUR_TAGENB) {
-				scsi->flags = CTS_SCSI_FLAGS_TAG_ENB;
-			} else {
-				scsi->flags = 0;
-			}
-			tinfo = &targ_info->current;
-		} else {
-			/* default(user) transfer settings */
-			if (targ_info->disc_tag & AMD_USR_DISCENB) {
-				spi->flags = CTS_SPI_FLAGS_DISC_ENB;
-			} else {
-				spi->flags = 0;
-			}
-			if (targ_info->disc_tag & AMD_USR_TAGENB) {
-				scsi->flags = CTS_SCSI_FLAGS_TAG_ENB;
-			} else {
-				scsi->flags = 0;
-			}
-			tinfo = &targ_info->user;
-		}
-		spi->sync_period = tinfo->period;
-		spi->sync_offset = tinfo->offset;
-		splx(intflag);
-
-		spi->bus_width = MSG_EXT_WDTR_BUS_8_BIT;
-		spi->valid = CTS_SPI_VALID_SYNC_RATE
-			   | CTS_SPI_VALID_SYNC_OFFSET
-			   | CTS_SPI_VALID_BUS_WIDTH
-			   | CTS_SPI_VALID_DISC;
-		scsi->valid = CTS_SCSI_VALID_TQ;
-		pccb->ccb_h.status = CAM_REQ_CMP;
-		xpt_done(pccb);
-		break;
-	}
-#define	IS_CURRENT_SETTINGS(c)	(c->type == CTS_TYPE_CURRENT_SETTINGS)
-#define	IS_USER_SETTINGS(c)	(c->type == CTS_TYPE_USER_SETTINGS)
-	case XPT_SET_TRAN_SETTINGS:
-	{
-		struct ccb_trans_settings *cts = &pccb->cts;
-		struct amd_target_info *targ_info;
-		u_int  update_type = 0;
-		int    intflag;
-		int    last_entry;
-		struct ccb_trans_settings_scsi *scsi =
-		    &cts->proto_specific.scsi;
-		struct ccb_trans_settings_spi *spi =
-		    &cts->xport_specific.spi;
-		if (IS_CURRENT_SETTINGS(cts)) {
-			update_type |= AMD_TRANS_GOAL;
-		} else if (IS_USER_SETTINGS(cts)) {
-			update_type |= AMD_TRANS_USER;
-		}
-		if (update_type == 0
-		 || update_type == (AMD_TRANS_USER|AMD_TRANS_GOAL)) {
-			cts->ccb_h.status = CAM_REQ_INVALID;
-			xpt_done(pccb);
-		}
-
-		intflag = splcam();
-		targ_info = &amd->tinfo[target_id];
-
-		if ((spi->valid & CTS_SPI_VALID_DISC) != 0) {
-			if (update_type & AMD_TRANS_GOAL) {
-				if ((spi->flags & CTS_SPI_FLAGS_DISC_ENB)
-				   != 0) {
-					targ_info->disc_tag |= AMD_CUR_DISCENB;
-				} else {
-					targ_info->disc_tag &= ~AMD_CUR_DISCENB;
-				}
-			}
-			if (update_type & AMD_TRANS_USER) {
-				if ((spi->flags & CTS_SPI_FLAGS_DISC_ENB)
-				   != 0) {
-					targ_info->disc_tag |= AMD_USR_DISCENB;
-				} else {
-					targ_info->disc_tag &= ~AMD_USR_DISCENB;
-				}
-			}
-		}
-		if ((scsi->valid & CTS_SCSI_VALID_TQ) != 0) {
-			if (update_type & AMD_TRANS_GOAL) {
-				if ((scsi->flags & CTS_SCSI_FLAGS_TAG_ENB)
-				   != 0) {
-					targ_info->disc_tag |= AMD_CUR_TAGENB;
-				} else {
-					targ_info->disc_tag &= ~AMD_CUR_TAGENB;
-				}
-			}
-			if (update_type & AMD_TRANS_USER) {
-				if ((scsi->flags & CTS_SCSI_FLAGS_TAG_ENB)
-				    != 0) {
-					targ_info->disc_tag |= AMD_USR_TAGENB;
-				} else {
-					targ_info->disc_tag &= ~AMD_USR_TAGENB;
-				}
-			}
-		}
-
-		if ((spi->valid & CTS_SPI_VALID_SYNC_OFFSET) == 0) {
-			if (update_type & AMD_TRANS_GOAL)
-				spi->sync_offset = targ_info->goal.offset;
-			else
-				spi->sync_offset = targ_info->user.offset;
-		}
-
-		if (spi->sync_offset > AMD_MAX_SYNC_OFFSET)
-			spi->sync_offset = AMD_MAX_SYNC_OFFSET;
-
-		if ((spi->valid & CTS_SPI_VALID_SYNC_RATE) == 0) {
-			if (update_type & AMD_TRANS_GOAL)
-				spi->sync_period = targ_info->goal.period;
-			else
-				spi->sync_period = targ_info->user.period;
-		}
-
-		last_entry = sizeof(tinfo_sync_period) - 1;
-		if ((spi->sync_period != 0)
-		 && (spi->sync_period < tinfo_sync_period[0]))
-			spi->sync_period = tinfo_sync_period[0];
-		if (spi->sync_period > tinfo_sync_period[last_entry])
-		 	spi->sync_period = 0;
-		if (spi->sync_offset == 0)
-			spi->sync_period = 0;
-
-		if ((update_type & AMD_TRANS_USER) != 0) {
-			targ_info->user.period = spi->sync_period;
-			targ_info->user.offset = spi->sync_offset;
-		}
-		if ((update_type & AMD_TRANS_GOAL) != 0) {
-			targ_info->goal.period = spi->sync_period;
-			targ_info->goal.offset = spi->sync_offset;
-		}
-		splx(intflag);
-		pccb->ccb_h.status = CAM_REQ_CMP;
-		xpt_done(pccb);
-		break;
-	}
-	case XPT_CALC_GEOMETRY:
-	{
-		int     extended;
-
-		extended = (amd->eepromBuf[EE_MODE2] & GREATER_1G) != 0;
-		cam_calc_geometry(&pccb->ccg, extended);
-		xpt_done(pccb);
-		break;
-	}
-	default:
-		pccb->ccb_h.status = CAM_REQ_INVALID;
-		xpt_done(pccb);
-		break;
-	}
-}
-
-static void
-amd_poll(struct cam_sim * psim)
-{
-	amd_intr(cam_sim_softc(psim));
-}
-
-static u_int8_t * 
-phystovirt(struct amd_srb * pSRB, u_int32_t xferCnt)
-{
-	intptr_t   dataPtr;
-	struct ccb_scsiio *pcsio;
-	u_int8_t   i;
-	struct amd_sg *    pseg;
-
-	dataPtr = 0;
-	pcsio = &pSRB->pccb->csio;
-
-	dataPtr = (intptr_t) pcsio->data_ptr;
-	pseg = pSRB->SGsegment;
-	for (i = 0; i < pSRB->SGIndex; i++) {
-		dataPtr += (int) pseg->SGXLen;
-		pseg++;
-	}
-	dataPtr += (int) xferCnt;
-	return ((u_int8_t *) dataPtr);
-}
-
-static void
-amd_dmamap_cb(void *arg, bus_dma_segment_t *segs, int nseg, int error)
-{
-	bus_addr_t *baddr;
-
-	baddr = (bus_addr_t *)arg;
-	*baddr = segs->ds_addr;
-}
-
-static void
-ResetDevParam(struct amd_softc * amd)
-{
-	u_int target;
-
-	for (target = 0; target <= amd->max_id; target++) {
-		if (amd->AdaptSCSIID != target) {
-			amdsetsync(amd, target, /*clockrate*/0,
-				   /*period*/0, /*offset*/0, AMD_TRANS_CUR);
-		}
-	}
-}
-
-static void
-amdcompletematch(struct amd_softc *amd, target_id_t target, lun_id_t lun,
-		 u_int tag, struct srb_queue *queue, cam_status status)
-{
-	struct amd_srb *srb;
-	struct amd_srb *next_srb;
-
-	for (srb = TAILQ_FIRST(queue); srb != NULL; srb = next_srb) {
-		union ccb *ccb;
-
-		next_srb = TAILQ_NEXT(srb, links);
-		if (srb->pccb->ccb_h.target_id != target
-		 && target != CAM_TARGET_WILDCARD)
-			continue;
-
-		if (srb->pccb->ccb_h.target_lun != lun
-		 && lun != CAM_LUN_WILDCARD)
-			continue;
-
-		if (srb->TagNumber != tag
-		 && tag != AMD_TAG_WILDCARD)
-			continue;
-		
-		ccb = srb->pccb;
-		TAILQ_REMOVE(queue, srb, links);
-		TAILQ_INSERT_HEAD(&amd->free_srbs, srb, links);
-		if ((ccb->ccb_h.status & CAM_DEV_QFRZN) == 0
-		 && (status & CAM_DEV_QFRZN) != 0)
-			xpt_freeze_devq(ccb->ccb_h.path, /*count*/1);
-		ccb->ccb_h.status = status;
-		xpt_done(ccb);
-	}
-
-}
-
-static void
-amdsetsync(struct amd_softc *amd, u_int target, u_int clockrate,
-	   u_int period, u_int offset, u_int type)
-{
-	struct amd_target_info *tinfo;
-	u_int old_period;
-	u_int old_offset;
-
-	tinfo = &amd->tinfo[target];
-	old_period = tinfo->current.period;
-	old_offset = tinfo->current.offset;
-	if ((type & AMD_TRANS_CUR) != 0
-	 && (old_period != period || old_offset != offset)) {
-		struct cam_path *path;
-
-		tinfo->current.period = period;
-		tinfo->current.offset = offset;
-		tinfo->sync_period_reg = clockrate;
-		tinfo->sync_offset_reg = offset;
-		tinfo->CtrlR3 &= ~FAST_SCSI;
-		tinfo->CtrlR4 &= ~EATER_25NS;
-		if (clockrate > 7)
-			tinfo->CtrlR4 |= EATER_25NS;
-		else
-			tinfo->CtrlR3 |= FAST_SCSI;
-
-		if ((type & AMD_TRANS_ACTIVE) == AMD_TRANS_ACTIVE) {
-			amd_write8(amd, SYNCPERIOREG, tinfo->sync_period_reg);
-			amd_write8(amd, SYNCOFFREG, tinfo->sync_offset_reg);
-			amd_write8(amd, CNTLREG3, tinfo->CtrlR3);
-			amd_write8(amd, CNTLREG4, tinfo->CtrlR4);
-		}
-		/* If possible, update the XPT's notion of our transfer rate */
-		if (xpt_create_path(&path, /*periph*/NULL,
-				    cam_sim_path(amd->psim), target,
-				    CAM_LUN_WILDCARD) == CAM_REQ_CMP) {
-			struct ccb_trans_settings neg;
-			struct ccb_trans_settings_spi *spi =
-			    &neg.xport_specific.spi;
-			xpt_setup_ccb(&neg.ccb_h, path, /*priority*/1);
-			memset(&neg, 0, sizeof (neg));
-			spi->sync_period = period;
-			spi->sync_offset = offset;
-			spi->valid = CTS_SPI_VALID_SYNC_RATE
-				  | CTS_SPI_VALID_SYNC_OFFSET;
-			xpt_async(AC_TRANSFER_NEG, path, &neg);
-			xpt_free_path(path);	
-		}
-	}
-	if ((type & AMD_TRANS_GOAL) != 0) {
-		tinfo->goal.period = period;
-		tinfo->goal.offset = offset;
-	}
-
-	if ((type & AMD_TRANS_USER) != 0) {
-		tinfo->user.period = period;
-		tinfo->user.offset = offset;
-	}
-}
-
-static void
-amdsettags(struct amd_softc *amd, u_int target, int tagenb)
-{
-	panic("Implement me!\n");
-}
-
-
-#if 0
-/*
- **********************************************************************
- * Function : amd_reset (struct amd_softc * amd)
- * Purpose  : perform a hard reset on the SCSI bus( and AMD chip).
- * Inputs   : cmd - command which caused the SCSI RESET
- **********************************************************************
- */
-static void
-amd_reset(struct amd_softc * amd)
-{
-	int	   intflag;
-	u_int8_t   bval;
-	u_int16_t  i;
-
-
-#ifdef AMD_DEBUG0
-	printf("DC390: RESET");
-#endif
-
-	intflag = splcam();
-	bval = amd_read8(amd, CNTLREG1);
-	bval |= DIS_INT_ON_SCSI_RST;
-	amd_write8(amd, CNTLREG1, bval);	/* disable interrupt */
-	amd_ResetSCSIBus(amd);
-
-	for (i = 0; i < 500; i++) {
-		DELAY(1000);
-	}
-
-	bval = amd_read8(amd, CNTLREG1);
-	bval &= ~DIS_INT_ON_SCSI_RST;
-	amd_write8(amd, CNTLREG1, bval);	/* re-enable interrupt */
-
-	amd_write8(amd, DMA_Cmd, DMA_IDLE_CMD);
-	amd_write8(amd, SCSICMDREG, CLEAR_FIFO_CMD);
-
-	ResetDevParam(amd);
-	amdcompletematch(amd, CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD,
-			 AMD_TAG_WILDCARD, &amd->running_srbs,
-			 CAM_DEV_QFRZN|CAM_SCSI_BUS_RESET);
-	amdcompletematch(amd, CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD,
-			 AMD_TAG_WILDCARD, &amd->waiting_srbs,
-			 CAM_DEV_QFRZN|CAM_SCSI_BUS_RESET);
-	amd->active_srb = NULL;
-	amd->ACBFlag = 0;
-	splx(intflag);
-	return;
-}
-
-void
-amd_timeout(void *arg1)
-{
-	struct amd_srb *    pSRB;
-
-	pSRB = (struct amd_srb *) arg1;
-}
-#endif
-
-static int
-amdstart(struct amd_softc *amd, struct amd_srb *pSRB)
-{
-	union ccb *pccb;
-	struct ccb_scsiio *pcsio;
-	struct amd_target_info *targ_info;
-	u_int identify_msg;
-	u_int command;
-	u_int target;
-	u_int lun;
-
-	pccb = pSRB->pccb;
-	pcsio = &pccb->csio;
-	target = pccb->ccb_h.target_id;
-	lun = pccb->ccb_h.target_lun;
-	targ_info = &amd->tinfo[target];
-
-	amd_clear_msg_state(amd);
-	amd_write8(amd, SCSIDESTIDREG, target);
-	amd_write8(amd, SYNCPERIOREG, targ_info->sync_period_reg);
-	amd_write8(amd, SYNCOFFREG, targ_info->sync_offset_reg);
-	amd_write8(amd, CNTLREG1, targ_info->CtrlR1);
-	amd_write8(amd, CNTLREG3, targ_info->CtrlR3);
-	amd_write8(amd, CNTLREG4, targ_info->CtrlR4);
-	amd_write8(amd, SCSICMDREG, CLEAR_FIFO_CMD);
-
-	identify_msg = MSG_IDENTIFYFLAG | lun;
-	if ((targ_info->disc_tag & AMD_CUR_DISCENB) != 0
-	  && (pccb->ccb_h.flags & CAM_DIS_DISCONNECT) == 0
-	  && (pSRB->CmdBlock[0] != REQUEST_SENSE)
-	  && (pSRB->SRBFlag & AUTO_REQSENSE) == 0)
-		identify_msg |= MSG_IDENTIFY_DISCFLAG;
-
-	amd_write8(amd, SCSIFIFOREG, identify_msg);
-	if ((targ_info->disc_tag & AMD_CUR_TAGENB) == 0
-	  || (identify_msg & MSG_IDENTIFY_DISCFLAG) == 0)
-		pccb->ccb_h.flags &= ~CAM_TAG_ACTION_VALID;
-	if (targ_info->current.period != targ_info->goal.period
-	 || targ_info->current.offset != targ_info->goal.offset) {
-		command = SEL_W_ATN_STOP;
-		amdconstructsdtr(amd, targ_info->goal.period,
-				 targ_info->goal.offset);
-	} else if ((pccb->ccb_h.flags & CAM_TAG_ACTION_VALID) != 0) {
-		command = SEL_W_ATN2;
-		pSRB->SRBState = SRB_START;
-		amd_write8(amd, SCSIFIFOREG, pcsio->tag_action);
-		amd_write8(amd, SCSIFIFOREG, pSRB->TagNumber);
-	} else {
-		command = SEL_W_ATN;
-		pSRB->SRBState = SRB_START;
-	}
-	if (command != SEL_W_ATN_STOP)
-		amdsetupcommand(amd, pSRB);
-
-	if (amd_read8(amd, SCSISTATREG) & INTERRUPT) {
-		pSRB->SRBState = SRB_READY;
-		return (1);
-	} else {
-		amd->last_phase = SCSI_ARBITRATING;
-		amd_write8(amd, SCSICMDREG, command);
-		amd->active_srb = pSRB;
-		amd->cur_target = target;
-		amd->cur_lun = lun;
-		return (0);
-	}
-}
-
-/*
- *  Catch an interrupt from the adapter.
- *  Process pending device interrupts.
- */
-static void 
-amd_intr(void   *arg)
-{
-	struct amd_softc *amd;
-	struct amd_srb *pSRB;
-	u_int  internstat = 0;
-	u_int  scsistat;
-	u_int  intstat;
-
-	amd = (struct amd_softc *)arg;
-
-	if (amd == NULL) {
-#ifdef AMD_DEBUG0
-		printf("amd_intr: amd NULL return......");
-#endif
-		return;
-	}
-
-	scsistat = amd_read8(amd, SCSISTATREG);
-	if (!(scsistat & INTERRUPT)) {
-#ifdef AMD_DEBUG0
-		printf("amd_intr: scsistat = NULL ,return......");
-#endif
-		return;
-	}
-#ifdef AMD_DEBUG_SCSI_PHASE
-	printf("scsistat=%2x,", scsistat);
-#endif
-
-	internstat = amd_read8(amd, INTERNSTATREG);
-	intstat = amd_read8(amd, INTSTATREG);
-
-#ifdef AMD_DEBUG_SCSI_PHASE
-	printf("intstat=%2x,", intstat);
-#endif
-
-	if (intstat & DISCONNECTED) {
-		amd_Disconnect(amd);
-		return;
-	}
-	if (intstat & RESELECTED) {
-		amd_Reselect(amd);
-		return;
-	}
-	if (intstat & INVALID_CMD) {
-		amd_InvalidCmd(amd);
-		return;
-	}
-	if (intstat & SCSI_RESET_) {
-		amd_ScsiRstDetect(amd);
-		return;
-	}
-	if (intstat & (SUCCESSFUL_OP + SERVICE_REQUEST)) {
-		pSRB = amd->active_srb;
-		/*
-		 * Run our state engine.  First perform
-		 * post processing for the last phase we
-		 * were in, followed by any processing
-		 * required to handle the current phase.
-		 */
-		scsistat =
-		    amd_SCSI_phase0[amd->last_phase](amd, pSRB, scsistat);
-		amd->last_phase = scsistat & SCSI_PHASE_MASK;
-		(void)amd_SCSI_phase1[amd->last_phase](amd, pSRB, scsistat);
-	}
-}
-
-static u_int
-amd_DataOutPhase0(struct amd_softc *amd, struct amd_srb *pSRB, u_int scsistat)
-{
-	struct amd_sg *psgl;
-	u_int32_t   ResidCnt, xferCnt;
-
-	if (!(pSRB->SRBState & SRB_XFERPAD)) {
-		if (scsistat & PARITY_ERR) {
-			pSRB->SRBStatus |= PARITY_ERROR;
-		}
-		if (scsistat & COUNT_2_ZERO) {
-			while ((amd_read8(amd, DMA_Status)&DMA_XFER_DONE) == 0)
-				;
-			pSRB->TotalXferredLen += pSRB->SGToBeXferLen;
-			pSRB->SGIndex++;
-			if (pSRB->SGIndex < pSRB->SGcount) {
-				pSRB->pSGlist++;
-				psgl = pSRB->pSGlist;
-				pSRB->SGPhysAddr = psgl->SGXPtr;
-				pSRB->SGToBeXferLen = psgl->SGXLen;
-			} else {
-				pSRB->SGToBeXferLen = 0;
-			}
-		} else {
-			ResidCnt = amd_read8(amd, CURRENTFIFOREG) & 0x1f;
-			ResidCnt += amd_read8(amd, CTCREG_LOW)
-				  | (amd_read8(amd, CTCREG_MID) << 8)
-				  | (amd_read8(amd, CURTXTCNTREG) << 16);
-
-			xferCnt = pSRB->SGToBeXferLen - ResidCnt;
-			pSRB->SGPhysAddr += xferCnt;
-			pSRB->TotalXferredLen += xferCnt;
-			pSRB->SGToBeXferLen = ResidCnt;
-		}
-	}
-	amd_write8(amd, DMA_Cmd, WRITE_DIRECTION | DMA_IDLE_CMD);
-	return (scsistat);
-}
-
-static u_int
-amd_DataInPhase0(struct amd_softc *amd, struct amd_srb *pSRB, u_int scsistat)
-{
-	u_int8_t bval;
-	u_int16_t  i, residual;
-	struct amd_sg *psgl;
-	u_int32_t   ResidCnt, xferCnt;
-	u_int8_t *  ptr;
-
-	if (!(pSRB->SRBState & SRB_XFERPAD)) {
-		if (scsistat & PARITY_ERR) {
-			pSRB->SRBStatus |= PARITY_ERROR;
-		}
-		if (scsistat & COUNT_2_ZERO) {
-			while (1) {
-				bval = amd_read8(amd, DMA_Status);
-				if ((bval & DMA_XFER_DONE) != 0)
-					break;
-			}
-			amd_write8(amd, DMA_Cmd, READ_DIRECTION|DMA_IDLE_CMD);
-
-			pSRB->TotalXferredLen += pSRB->SGToBeXferLen;
-			pSRB->SGIndex++;
-			if (pSRB->SGIndex < pSRB->SGcount) {
-				pSRB->pSGlist++;
-				psgl = pSRB->pSGlist;
-				pSRB->SGPhysAddr = psgl->SGXPtr;
-				pSRB->SGToBeXferLen = psgl->SGXLen;
-			} else {
-				pSRB->SGToBeXferLen = 0;
-			}
-		} else {	/* phase changed */
-			residual = 0;
-			bval = amd_read8(amd, CURRENTFIFOREG);
-			while (bval & 0x1f) {
-				if ((bval & 0x1f) == 1) {
-					for (i = 0; i < 0x100; i++) {
-						bval = amd_read8(amd, CURRENTFIFOREG);
-						if (!(bval & 0x1f)) {
-							goto din_1;
-						} else if (i == 0x0ff) {
-							residual = 1;
-							goto din_1;
-						}
-					}
-				} else {
-					bval = amd_read8(amd, CURRENTFIFOREG);
-				}
-			}
-	din_1:
-			amd_write8(amd, DMA_Cmd, READ_DIRECTION|DMA_BLAST_CMD);
-			for (i = 0; i < 0x8000; i++) {
-				if ((amd_read8(amd, DMA_Status)&BLAST_COMPLETE))
-					break;
-			}
-			amd_write8(amd, DMA_Cmd, READ_DIRECTION|DMA_IDLE_CMD);
-
-			ResidCnt = amd_read8(amd, CTCREG_LOW)
-				 | (amd_read8(amd, CTCREG_MID) << 8)
-				 | (amd_read8(amd, CURTXTCNTREG) << 16);
-			xferCnt = pSRB->SGToBeXferLen - ResidCnt;
-			pSRB->SGPhysAddr += xferCnt;
-			pSRB->TotalXferredLen += xferCnt;
-			pSRB->SGToBeXferLen = ResidCnt;
-			if (residual) {
-				/* get residual byte */	
-				bval = amd_read8(amd, SCSIFIFOREG);
-				ptr = phystovirt(pSRB, xferCnt);
-				*ptr = bval;
-				pSRB->SGPhysAddr++;
-				pSRB->TotalXferredLen++;
-				pSRB->SGToBeXferLen--;
-			}
-		}
-	}
-	return (scsistat);
-}
-
-static u_int
-amd_StatusPhase0(struct amd_softc *amd, struct amd_srb *pSRB, u_int scsistat)
-{
-	pSRB->TargetStatus = amd_read8(amd, SCSIFIFOREG);
-	/* get message */
-	pSRB->EndMessage = amd_read8(amd, SCSIFIFOREG);
-	pSRB->SRBState = SRB_COMPLETED;
-	amd_write8(amd, SCSICMDREG, MSG_ACCEPTED_CMD);
-	return (SCSI_NOP0);
-}
-
-static u_int
-amd_MsgOutPhase0(struct amd_softc *amd, struct amd_srb *pSRB, u_int scsistat)
-{
-	if (pSRB->SRBState & (SRB_UNEXPECT_RESEL + SRB_ABORT_SENT)) {
-		scsistat = SCSI_NOP0;
-	}
-	return (scsistat);
-}
-
-static u_int
-amd_MsgInPhase0(struct amd_softc *amd, struct amd_srb *pSRB, u_int scsistat)
-{
-	int done;
-	
-	amd->msgin_buf[amd->msgin_index]  = amd_read8(amd, SCSIFIFOREG);
-
-	done = amdparsemsg(amd);
-	if (done)
-		amd->msgin_index = 0;
-	else 
-		amd->msgin_index++;
-	return (SCSI_NOP0);
-}
-
-static int
-amdparsemsg(struct amd_softc *amd)
-{
-	int	reject;
-	int	done;
-	int	response;
-
-	done = FALSE;
-	response = FALSE;
-	reject = FALSE;
-
-	/*
-	 * Parse as much of the message as is availible,
-	 * rejecting it if we don't support it.  When
-	 * the entire message is availible and has been
-	 * handled, return TRUE indicating that we have
-	 * parsed an entire message.
-	 */
-	switch (amd->msgin_buf[0]) {
-	case MSG_DISCONNECT:
-		amd->active_srb->SRBState = SRB_DISCONNECT;
-		amd->disc_count[amd->cur_target][amd->cur_lun]++;
-		done = TRUE;
-		break;
-	case MSG_SIMPLE_Q_TAG:
-	{
-		struct amd_srb *disc_srb;
-
-		if (amd->msgin_index < 1)
-			break;		
-		disc_srb = &amd->SRB_array[amd->msgin_buf[1]];
-		if (amd->active_srb != NULL
-		 || disc_srb->SRBState != SRB_DISCONNECT
-		 || disc_srb->pccb->ccb_h.target_id != amd->cur_target
-		 || disc_srb->pccb->ccb_h.target_lun != amd->cur_lun) {
-			printf("amd%d: Unexpected tagged reselection "
-			       "for target %d, Issuing Abort\n", amd->unit,
-			       amd->cur_target);
-			amd->msgout_buf[0] = MSG_ABORT;
-			amd->msgout_len = 1;
-			response = TRUE;
-			break;
-		}
-		amd->active_srb = disc_srb;
-		amd->disc_count[amd->cur_target][amd->cur_lun]--;
-		done = TRUE;
-		break;
-	}
-	case MSG_MESSAGE_REJECT:
-		response = amdhandlemsgreject(amd);
-		if (response == FALSE)
-			amd_write8(amd, SCSICMDREG, RESET_ATN_CMD);
-		/* FALLTHROUGH */
-	case MSG_NOOP:
-		done = TRUE;
-		break;
-	case MSG_EXTENDED:
-	{
-		u_int clockrate;
-		u_int period;
-		u_int offset;
-		u_int saved_offset;
-
-		/* Wait for enough of the message to begin validation */
-		if (amd->msgin_index < 1)
-			break;
-		if (amd->msgin_buf[1] != MSG_EXT_SDTR_LEN) {
-			reject = TRUE;
-			break;
-		}
-
-		/* Wait for opcode */
-		if (amd->msgin_index < 2)
-			break;
-
-		if (amd->msgin_buf[2] != MSG_EXT_SDTR) {
-			reject = TRUE;
-			break;
-		}
-
-		/*
-		 * Wait until we have both args before validating
-		 * and acting on this message.
-		 *
-		 * Add one to MSG_EXT_SDTR_LEN to account for
-		 * the extended message preamble.
-		 */
-		if (amd->msgin_index < (MSG_EXT_SDTR_LEN + 1))
-			break;
-
-		period = amd->msgin_buf[3];
-		saved_offset = offset = amd->msgin_buf[4];
-		clockrate = amdfindclockrate(amd, &period);
-		if (offset > AMD_MAX_SYNC_OFFSET)
-			offset = AMD_MAX_SYNC_OFFSET;
-		if (period == 0 || offset == 0) {
-			offset = 0;
-			period = 0;
-			clockrate = 0;
-		}
-		amdsetsync(amd, amd->cur_target, clockrate, period, offset,
-			   AMD_TRANS_ACTIVE|AMD_TRANS_GOAL);
-
-		/*
-		 * See if we initiated Sync Negotiation
-		 * and didn't have to fall down to async
-		 * transfers.
-		 */
-		if (amdsentmsg(amd, MSG_EXT_SDTR, /*full*/TRUE)) {
-			/* We started it */
-			if (saved_offset != offset) {
-				/* Went too low - force async */
-				reject = TRUE;
-			}
-		} else {
-			/*
-			 * Send our own SDTR in reply
-			 */
-			if (bootverbose)
-				printf("Sending SDTR!\n");
-			amd->msgout_index = 0;
-			amd->msgout_len = 0;
-			amdconstructsdtr(amd, period, offset);
-			amd->msgout_index = 0;
-			response = TRUE;
-		}
-		done = TRUE;
-		break;
-	}
-	case MSG_SAVEDATAPOINTER:
-	case MSG_RESTOREPOINTERS:
-		/* XXX Implement!!! */
-		done = TRUE;
-		break;
-	default:
-		reject = TRUE;
-		break;
-	}
-
-	if (reject) {
-		amd->msgout_index = 0;
-		amd->msgout_len = 1;
-		amd->msgout_buf[0] = MSG_MESSAGE_REJECT;
-		done = TRUE;
-		response = TRUE;
-	}
-
-	if (response)
-		amd_write8(amd, SCSICMDREG, SET_ATN_CMD);
-
-	if (done && !response)
-		/* Clear the outgoing message buffer */
-		amd->msgout_len = 0;
-
-	/* Drop Ack */
-	amd_write8(amd, SCSICMDREG, MSG_ACCEPTED_CMD);
-
-	return (done);
-}
-
-static u_int
-amdfindclockrate(struct amd_softc *amd, u_int *period)
-{
-	u_int i;
-	u_int clockrate;
-
-	for (i = 0; i < sizeof(tinfo_sync_period); i++) {
-		u_int8_t *table_entry;
-
-		table_entry = &tinfo_sync_period[i];
-		if (*period <= *table_entry) {
-			/*
-			 * When responding to a target that requests
-			 * sync, the requested rate may fall between
-			 * two rates that we can output, but still be
-			 * a rate that we can receive.  Because of this,
-			 * we want to respond to the target with
-			 * the same rate that it sent to us even
-			 * if the period we use to send data to it
-			 * is lower.  Only lower the response period
-			 * if we must.
-			 */ 
-			if (i == 0) {
-				*period = *table_entry;
-			}
-			break;
-		}
-	}
-
-	if (i == sizeof(tinfo_sync_period)) {
-		/* Too slow for us.  Use asnyc transfers. */
-		*period = 0;
-		clockrate = 0;
-	} else
-		clockrate = i + 4;
-
-	return (clockrate);
-}
-
-/*
- * See if we sent a particular extended message to the target.
- * If "full" is true, the target saw the full message.
- * If "full" is false, the target saw at least the first
- * byte of the message.
- */
-static int
-amdsentmsg(struct amd_softc *amd, u_int msgtype, int full)
-{
-	int found;
-	int index;
-
-	found = FALSE;
-	index = 0;
-
-	while (index < amd->msgout_len) {
-		if ((amd->msgout_buf[index] & MSG_IDENTIFYFLAG) != 0
-		 || amd->msgout_buf[index] == MSG_MESSAGE_REJECT)
-			index++;
-		else if (amd->msgout_buf[index] >= MSG_SIMPLE_Q_TAG
-		      && amd->msgout_buf[index] < MSG_IGN_WIDE_RESIDUE) {
-			/* Skip tag type and tag id */
-			index += 2;
-		} else if (amd->msgout_buf[index] == MSG_EXTENDED) {
-			/* Found a candidate */
-			if (amd->msgout_buf[index+2] == msgtype) {
-				u_int end_index;
-
-				end_index = index + 1
-					  + amd->msgout_buf[index + 1];
-				if (full) {
-					if (amd->msgout_index > end_index)
-						found = TRUE;
-				} else if (amd->msgout_index > index)
-					found = TRUE;
-			}
-			break;
-		} else {
-			panic("amdsentmsg: Inconsistent msg buffer");
-		}
-	}
-	return (found);
-}
-
-static void
-amdconstructsdtr(struct amd_softc *amd, u_int period, u_int offset)
-{
-	amd->msgout_buf[amd->msgout_index++] = MSG_EXTENDED;
-	amd->msgout_buf[amd->msgout_index++] = MSG_EXT_SDTR_LEN;
-	amd->msgout_buf[amd->msgout_index++] = MSG_EXT_SDTR;
-	amd->msgout_buf[amd->msgout_index++] = period;
-	amd->msgout_buf[amd->msgout_index++] = offset;
-	amd->msgout_len += 5;
-}
-
-static int
-amdhandlemsgreject(struct amd_softc *amd)
-{
-	/*
-	 * If we had an outstanding SDTR for this
-	 * target, this is a signal that the target
-	 * is refusing negotiation.  Also watch out
-	 * for rejected tag messages.
-	 */
-	struct	amd_srb *srb;
-	struct	amd_target_info *targ_info;
-	int	response = FALSE;
-
-	srb = amd->active_srb;
-	targ_info = &amd->tinfo[amd->cur_target];
-	if (amdsentmsg(amd, MSG_EXT_SDTR, /*full*/FALSE)) {
-		/* note asynch xfers and clear flag */
-		amdsetsync(amd, amd->cur_target, /*clockrate*/0,
-			   /*period*/0, /*offset*/0,
-			   AMD_TRANS_ACTIVE|AMD_TRANS_GOAL);
-		printf("amd%d:%d: refuses synchronous negotiation. "
-		       "Using asynchronous transfers\n",
-		       amd->unit, amd->cur_target);
-	} else if ((srb != NULL)
-		&& (srb->pccb->ccb_h.flags & CAM_TAG_ACTION_VALID) != 0) {
-		struct  ccb_trans_settings neg;
-		struct ccb_trans_settings_scsi *scsi = &neg.proto_specific.scsi;
-
-		printf("amd%d:%d: refuses tagged commands.  Performing "
-		       "non-tagged I/O\n", amd->unit, amd->cur_target);
-
-		amdsettags(amd, amd->cur_target, FALSE);
-		memset(&neg, 0, sizeof (neg));
-		scsi->valid = CTS_SCSI_VALID_TQ;
-		xpt_setup_ccb(&neg.ccb_h, srb->pccb->ccb_h.path, /*priority*/1);
-		xpt_async(AC_TRANSFER_NEG, srb->pccb->ccb_h.path, &neg);
-
-		/*
-		 * Resend the identify for this CCB as the target
-		 * may believe that the selection is invalid otherwise.
-		 */
-		if (amd->msgout_len != 0)
-			bcopy(&amd->msgout_buf[0], &amd->msgout_buf[1],
-			      amd->msgout_len);
-		amd->msgout_buf[0] = MSG_IDENTIFYFLAG
-				    | srb->pccb->ccb_h.target_lun;
-		amd->msgout_len++;
-		if ((targ_info->disc_tag & AMD_CUR_DISCENB) != 0
-		  && (srb->pccb->ccb_h.flags & CAM_DIS_DISCONNECT) == 0)
-			amd->msgout_buf[0] |= MSG_IDENTIFY_DISCFLAG;
-
-		srb->pccb->ccb_h.flags &= ~CAM_TAG_ACTION_VALID;
-
-		/*
-		 * Requeue all tagged commands for this target
-		 * currently in our posession so they can be
-		 * converted to untagged commands.
-		 */
-		amdcompletematch(amd, amd->cur_target, amd->cur_lun,
-				 AMD_TAG_WILDCARD, &amd->waiting_srbs,
-				 CAM_DEV_QFRZN|CAM_REQUEUE_REQ);
-	} else {
-		/*
-		 * Otherwise, we ignore it.
-		 */
-		printf("amd%d:%d: Message reject received -- ignored\n",
-		       amd->unit, amd->cur_target);
-	}
-	return (response);
-}
-
-#if 0
-	if (!(pSRB->SRBState & SRB_MSGIN_MULTI)) {
-		if (bval == MSG_DISCONNECT) {
-			pSRB->SRBState = SRB_DISCONNECT;
-		} else if (bval == MSG_SAVEDATAPOINTER) {
-			goto min6;
-		} else if ((bval == MSG_EXTENDED)
-			|| ((bval >= MSG_SIMPLE_Q_TAG)
-			 && (bval <= MSG_ORDERED_Q_TAG))) {
-			pSRB->SRBState |= SRB_MSGIN_MULTI;
-			pSRB->MsgInBuf[0] = bval;
-			pSRB->MsgCnt = 1;
-			pSRB->pMsgPtr = &pSRB->MsgInBuf[1];
-		} else if (bval == MSG_MESSAGE_REJECT) {
-			amd_write8(amd, SCSICMDREG, RESET_ATN_CMD);
-
-			if (pSRB->SRBState & DO_SYNC_NEGO) {
-				goto set_async;
-			}
-		} else if (bval == MSG_RESTOREPOINTERS) {
-			goto min6;
-		} else {
-			goto min6;
-		}
-	} else {		/* minx: */
-		*pSRB->pMsgPtr = bval;
-		pSRB->MsgCnt++;
-		pSRB->pMsgPtr++;
-		if ((pSRB->MsgInBuf[0] >= MSG_SIMPLE_Q_TAG)
-		 && (pSRB->MsgInBuf[0] <= MSG_ORDERED_Q_TAG)) {
-			if (pSRB->MsgCnt == 2) {
-				pSRB->SRBState = 0;
-				pSRB = &amd->SRB_array[pSRB->MsgInBuf[1]];
-				if (pSRB->SRBState & SRB_DISCONNECT) == 0) {
-					pSRB = amd->pTmpSRB;
-					pSRB->SRBState = SRB_UNEXPECT_RESEL;
-					pDCB->pActiveSRB = pSRB;
-					pSRB->MsgOutBuf[0] = MSG_ABORT_TAG;
-					EnableMsgOut2(amd, pSRB);
-				} else {
-					if (pDCB->DCBFlag & ABORT_DEV_) {
-						pSRB->SRBState = SRB_ABORT_SENT;
-						EnableMsgOut1(amd, pSRB);
-					}
-					pDCB->pActiveSRB = pSRB;
-					pSRB->SRBState = SRB_DATA_XFER;
-				}
-			}
-		} else if ((pSRB->MsgInBuf[0] == MSG_EXTENDED)
-			&& (pSRB->MsgCnt == 5)) {
-			pSRB->SRBState &= ~(SRB_MSGIN_MULTI + DO_SYNC_NEGO);
-			if ((pSRB->MsgInBuf[1] != 3)
-			 || (pSRB->MsgInBuf[2] != 1)) {	/* reject_msg: */
-				pSRB->MsgCnt = 1;
-				pSRB->MsgInBuf[0] = MSG_MESSAGE_REJECT;
-				amd_write8(amd, SCSICMDREG, SET_ATN_CMD);
-			} else if (!(pSRB->MsgInBuf[3])
-				|| !(pSRB->MsgInBuf[4])) {
-		set_async:	/* set async */
-
-				pDCB = pSRB->pSRBDCB;
-				/* disable sync & sync nego */
-				pDCB->SyncMode &= ~(SYNC_ENABLE|SYNC_NEGO_DONE);
-				pDCB->SyncPeriod = 0;
-				pDCB->SyncOffset = 0;
-
-				pDCB->tinfo.goal.period = 0;
-				pDCB->tinfo.goal.offset = 0;
-
-				pDCB->tinfo.current.period = 0;
-				pDCB->tinfo.current.offset = 0;
-				pDCB->tinfo.current.width =
-				    MSG_EXT_WDTR_BUS_8_BIT;
-
-				pDCB->CtrlR3 = FAST_CLK; /* non_fast */
-				pDCB->CtrlR4 &= 0x3f;
-				pDCB->CtrlR4 |= EATER_25NS; 
-				goto re_prog;
-			} else {/* set sync */
-
-				pDCB = pSRB->pSRBDCB;
-				/* enable sync & sync nego */
-				pDCB->SyncMode |= SYNC_ENABLE|SYNC_NEGO_DONE;
-
-				/* set sync offset */
-				pDCB->SyncOffset &= 0x0f0;
-				pDCB->SyncOffset |= pSRB->MsgInBuf[4];
-
-				/* set sync period */
-				pDCB->MaxNegoPeriod = pSRB->MsgInBuf[3];
-
-				wval = (u_int16_t) pSRB->MsgInBuf[3];
-				wval = wval << 2;
-				wval--;
-				wval1 = wval / 25;
-				if ((wval1 * 25) != wval) {
-					wval1++;
-				}
-				bval = FAST_CLK|FAST_SCSI;
-				pDCB->CtrlR4 &= 0x3f;
-				if (wval1 >= 8) {
-					/* Fast SCSI */
-					wval1--;
-					bval = FAST_CLK;
-					pDCB->CtrlR4 |= EATER_25NS;
-				}
-				pDCB->CtrlR3 = bval;
-				pDCB->SyncPeriod = (u_int8_t) wval1;
-
-				pDCB->tinfo.goal.period =
-				    tinfo_sync_period[pDCB->SyncPeriod - 4];
-				pDCB->tinfo.goal.offset = pDCB->SyncOffset;
-				pDCB->tinfo.current.period =
-				    tinfo_sync_period[pDCB->SyncPeriod - 4];
-				pDCB->tinfo.current.offset = pDCB->SyncOffset;
-
-				/*
-				 * program SCSI control register
-				 */
-		re_prog:
-				amd_write8(amd, SYNCPERIOREG, pDCB->SyncPeriod);
-				amd_write8(amd, SYNCOFFREG, pDCB->SyncOffset);
-				amd_write8(amd, CNTLREG3, pDCB->CtrlR3);
-				amd_write8(amd, CNTLREG4, pDCB->CtrlR4);
-			}
-		}
-	}
-min6:
-	amd_write8(amd, SCSICMDREG, MSG_ACCEPTED_CMD);
-	return (SCSI_NOP0);
-}
-#endif
-
-static u_int
-amd_DataOutPhase1(struct amd_softc *amd, struct amd_srb *pSRB, u_int scsistat)
-{
-	DataIO_Comm(amd, pSRB, WRITE_DIRECTION);
-	return (scsistat);
-}
-
-static u_int 
-amd_DataInPhase1(struct amd_softc *amd, struct amd_srb *pSRB, u_int scsistat)
-{
-	DataIO_Comm(amd, pSRB, READ_DIRECTION);
-	return (scsistat);
-}
-
-static void
-DataIO_Comm(struct amd_softc *amd, struct amd_srb *pSRB, u_int ioDir)
-{
-	struct amd_sg *    psgl;
-	u_int32_t   lval;
-
-	if (pSRB->SGIndex < pSRB->SGcount) {
-		amd_write8(amd, DMA_Cmd, DMA_IDLE_CMD|ioDir);/* |EN_DMA_INT */
-
-		if (!pSRB->SGToBeXferLen) {
-			psgl = pSRB->pSGlist;
-			pSRB->SGPhysAddr = psgl->SGXPtr;
-			pSRB->SGToBeXferLen = psgl->SGXLen;
-		}
-		lval = pSRB->SGToBeXferLen;
-		amd_write8(amd, CTCREG_LOW, lval);
-		amd_write8(amd, CTCREG_MID, lval >> 8);
-		amd_write8(amd, CURTXTCNTREG, lval >> 16);
-
-		amd_write32(amd, DMA_XferCnt, pSRB->SGToBeXferLen);
-
-		amd_write32(amd, DMA_XferAddr, pSRB->SGPhysAddr);
-
-		pSRB->SRBState = SRB_DATA_XFER;
-
-		amd_write8(amd, SCSICMDREG, DMA_COMMAND|INFO_XFER_CMD);
-
-		amd_write8(amd, DMA_Cmd, DMA_IDLE_CMD|ioDir); /* |EN_DMA_INT */
-
-		amd_write8(amd, DMA_Cmd, DMA_START_CMD|ioDir);/* |EN_DMA_INT */
-	} else {		/* xfer pad */
-		if (pSRB->SGcount) {
-			pSRB->AdaptStatus = H_OVER_UNDER_RUN;
-			pSRB->SRBStatus |= OVER_RUN;
-		}
-		amd_write8(amd, CTCREG_LOW, 0);
-		amd_write8(amd, CTCREG_MID, 0);
-		amd_write8(amd, CURTXTCNTREG, 0);
-
-		pSRB->SRBState |= SRB_XFERPAD;
-		amd_write8(amd, SCSICMDREG, DMA_COMMAND|XFER_PAD_BYTE);
-	}
-}
-
-static u_int
-amd_CommandPhase1(struct amd_softc *amd, struct amd_srb *srb, u_int scsistat)
-{
-	amd_write8(amd, SCSICMDREG, RESET_ATN_CMD);
-	amd_write8(amd, SCSICMDREG, CLEAR_FIFO_CMD);
-
-	amdsetupcommand(amd, srb);
-
-	srb->SRBState = SRB_COMMAND;
-	amd_write8(amd, SCSICMDREG, INFO_XFER_CMD);
-	return (scsistat);
-}
-
-static u_int
-amd_StatusPhase1(struct amd_softc *amd, struct amd_srb *pSRB, u_int scsistat)
-{
-	amd_write8(amd, SCSICMDREG, CLEAR_FIFO_CMD);
-	pSRB->SRBState = SRB_STATUS;
-	amd_write8(amd, SCSICMDREG, INITIATOR_CMD_CMPLTE);
-	return (scsistat);
-}
-
-static u_int
-amd_MsgOutPhase1(struct amd_softc *amd, struct amd_srb *pSRB, u_int scsistat)
-{
-	amd_write8(amd, SCSICMDREG, CLEAR_FIFO_CMD);
-
-	if (amd->msgout_len == 0) {
-		amd->msgout_buf[0] = MSG_NOOP;
-		amd->msgout_len = 1;
-	}
-	amd_write8_multi(amd, SCSIFIFOREG, amd->msgout_buf, amd->msgout_len);
-	amd_write8(amd, SCSICMDREG, INFO_XFER_CMD);
-	return (scsistat);
-}
-
-static u_int
-amd_MsgInPhase1(struct amd_softc *amd, struct amd_srb *pSRB, u_int scsistat)
-{
-	amd_write8(amd, SCSICMDREG, CLEAR_FIFO_CMD);
-	amd_write8(amd, SCSICMDREG, INFO_XFER_CMD);
-	return (scsistat);
-}
-
-static u_int
-amd_NopPhase(struct amd_softc *amd, struct amd_srb *pSRB, u_int scsistat)
-{
-	return (scsistat);
-}
-
-static void
-amd_Disconnect(struct amd_softc * amd)
-{
-	struct	amd_srb *srb;
-	int	target;
-	int	lun;
-
-	srb = amd->active_srb;
-	amd->active_srb = NULL;
-	amd->last_phase = SCSI_BUS_FREE;
-	amd_write8(amd, SCSICMDREG, EN_SEL_RESEL);
-	target = amd->cur_target;
-	lun = amd->cur_lun;
-
-	if (srb == NULL) {
-		/* Invalid reselection */
-		amdrunwaiting(amd);
-	} else if (srb->SRBState & SRB_ABORT_SENT) {
-		/* Clean up and done this srb */
-#if 0
-		while (( = TAILQ_FIRST(&amd->running_srbs)) != NULL) {
-			/* XXX What about "done'ing" these srbs??? */
-			if (pSRB->pSRBDCB == pDCB) {
-				TAILQ_REMOVE(&amd->running_srbs, pSRB, links);
-				TAILQ_INSERT_HEAD(&amd->free_srbs, pSRB, links);
-			}
-		}
-		amdrunwaiting(amd);
-#endif
-	} else {
-		if ((srb->SRBState & (SRB_START | SRB_MSGOUT))
-		 || !(srb->SRBState & (SRB_DISCONNECT | SRB_COMPLETED))) {
-			srb->TargetStatus = AMD_SCSI_STAT_SEL_TIMEOUT;
-			goto disc1;
-		} else if (srb->SRBState & SRB_DISCONNECT) {
-			if (!(srb->pccb->ccb_h.flags & CAM_TAG_ACTION_VALID))
-				amd->untagged_srbs[target][lun] = srb;
-			amdrunwaiting(amd);
-		} else if (srb->SRBState & SRB_COMPLETED) {
-	disc1:
-			srb->SRBState = SRB_FREE;
-			SRBdone(amd, srb);
-		}
-	}
-	return;
-}
-
-static void
-amd_Reselect(struct amd_softc *amd)
-{
-	struct amd_target_info *tinfo;
-	u_int16_t disc_count;
-
-	amd_clear_msg_state(amd);
-	if (amd->active_srb != NULL) {
-		/* Requeue the SRB for our attempted Selection */
-		TAILQ_REMOVE(&amd->running_srbs, amd->active_srb, links);
-		TAILQ_INSERT_HEAD(&amd->waiting_srbs, amd->active_srb, links);
-		amd->active_srb = NULL;
-	}
-	/* get ID */
-	amd->cur_target = amd_read8(amd, SCSIFIFOREG);
-	amd->cur_target ^= amd->HostID_Bit;
-	amd->cur_target = ffs(amd->cur_target) - 1;
-	amd->cur_lun = amd_read8(amd, SCSIFIFOREG) & 7;
-	tinfo = &amd->tinfo[amd->cur_target];
-	amd->active_srb = amd->untagged_srbs[amd->cur_target][amd->cur_lun];
-	disc_count = amd->disc_count[amd->cur_target][amd->cur_lun];
-	if (disc_count == 0) {
-		printf("amd%d: Unexpected reselection for target %d, "
-		       "Issuing Abort\n", amd->unit, amd->cur_target);
-		amd->msgout_buf[0] = MSG_ABORT;
-		amd->msgout_len = 1;
-		amd_write8(amd, SCSICMDREG, SET_ATN_CMD);
-	}
-	if (amd->active_srb != NULL) {
-		amd->disc_count[amd->cur_target][amd->cur_lun]--;
-		amd->untagged_srbs[amd->cur_target][amd->cur_lun] = NULL;
-	}
-	
-	amd_write8(amd, SCSIDESTIDREG, amd->cur_target);
-	amd_write8(amd, SYNCPERIOREG, tinfo->sync_period_reg);
-	amd_write8(amd, SYNCOFFREG, tinfo->sync_offset_reg);
-	amd_write8(amd, CNTLREG1, tinfo->CtrlR1);
-	amd_write8(amd, CNTLREG3, tinfo->CtrlR3);
-	amd_write8(amd, CNTLREG4, tinfo->CtrlR4);
-	amd_write8(amd, SCSICMDREG, MSG_ACCEPTED_CMD);/* drop /ACK */
-	amd->last_phase = SCSI_NOP0;
-}
-
-static void
-SRBdone(struct amd_softc *amd, struct amd_srb *pSRB)
-{
-	u_int8_t   bval, i, status;
-	union ccb *pccb;
-	struct ccb_scsiio *pcsio;
-	int	   intflag;
-	struct amd_sg *ptr2;
-	u_int32_t   swlval;
-
-	pccb = pSRB->pccb;
-	pcsio = &pccb->csio;
-
-	CAM_DEBUG(pccb->ccb_h.path, CAM_DEBUG_TRACE,
-		  ("SRBdone - TagNumber %d\n", pSRB->TagNumber));
-
-	if ((pccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
-		bus_dmasync_op_t op;
-
-		if ((pccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN)
-			op = BUS_DMASYNC_POSTREAD;
-		else
-			op = BUS_DMASYNC_POSTWRITE;
-		bus_dmamap_sync(amd->buffer_dmat, pSRB->dmamap, op);
-		bus_dmamap_unload(amd->buffer_dmat, pSRB->dmamap);
-	}
-
-	status = pSRB->TargetStatus;
-	pccb->ccb_h.status = CAM_REQ_CMP;
-	if (pSRB->SRBFlag & AUTO_REQSENSE) {
-		pSRB->SRBFlag &= ~AUTO_REQSENSE;
-		pSRB->AdaptStatus = 0;
-		pSRB->TargetStatus = SCSI_STATUS_CHECK_COND;
-
-		if (status == SCSI_STATUS_CHECK_COND) {
-			pccb->ccb_h.status = CAM_AUTOSENSE_FAIL;
-			goto ckc_e;
-		}
-		*((u_int32_t *)&(pSRB->CmdBlock[0])) = pSRB->Segment0[0];
-
-		pcsio->sense_resid = pcsio->sense_len
-				   - pSRB->TotalXferredLen;
-		pSRB->TotalXferredLen = pSRB->Segment1[1];
-		if (pSRB->TotalXferredLen) {
-			/* ???? */
-			pcsio->resid = pcsio->dxfer_len
-				     - pSRB->TotalXferredLen;
-			/* The resid field contains valid data	 */
-			/* Flush resid bytes on complete        */
-		} else {
-			pcsio->scsi_status = SCSI_STATUS_CHECK_COND;
-		}
-		bzero(&pcsio->sense_data, pcsio->sense_len);
-		bcopy(amd_get_sense_buf(amd, pSRB), &pcsio->sense_data,
-		      pcsio->sense_len);
-		pccb->ccb_h.status = CAM_AUTOSNS_VALID;
-		goto ckc_e;
-	}
-	if (status) {
-		if (status == SCSI_STATUS_CHECK_COND) {
-
-			if ((pSRB->SGIndex < pSRB->SGcount)
-			 && (pSRB->SGcount) && (pSRB->SGToBeXferLen)) {
-				bval = pSRB->SGcount;
-				swlval = pSRB->SGToBeXferLen;
-				ptr2 = pSRB->pSGlist;
-				ptr2++;
-				for (i = pSRB->SGIndex + 1; i < bval; i++) {
-					swlval += ptr2->SGXLen;
-					ptr2++;
-				}
-				/* ??????? */
-				pcsio->resid = (u_int32_t) swlval;
-
-#ifdef	AMD_DEBUG0
-				printf("XferredLen=%8x,NotYetXferLen=%8x,",
-					pSRB->TotalXferredLen, swlval);
-#endif
-			}
-			if ((pcsio->ccb_h.flags & CAM_DIS_AUTOSENSE) == 0) {
-#ifdef	AMD_DEBUG0
-				printf("RequestSense..................\n");
-#endif
-				RequestSense(amd, pSRB);
-				return;
-			}
-			pcsio->scsi_status = SCSI_STATUS_CHECK_COND;
-			pccb->ccb_h.status = CAM_SCSI_STATUS_ERROR;
-			goto ckc_e;
-		} else if (status == SCSI_STATUS_QUEUE_FULL) {
-			pSRB->AdaptStatus = 0;
-			pSRB->TargetStatus = 0;
-			pcsio->scsi_status = SCSI_STATUS_QUEUE_FULL;
-			pccb->ccb_h.status = CAM_SCSI_STATUS_ERROR;
-			goto ckc_e;
-		} else if (status == AMD_SCSI_STAT_SEL_TIMEOUT) {
-			pSRB->AdaptStatus = H_SEL_TIMEOUT;
-			pSRB->TargetStatus = 0;
-
-			pcsio->scsi_status = AMD_SCSI_STAT_SEL_TIMEOUT;
-			pccb->ccb_h.status = CAM_SEL_TIMEOUT;
-		} else if (status == SCSI_STATUS_BUSY) {
-#ifdef AMD_DEBUG0
-			printf("DC390: target busy at %s %d\n",
-			       __FILE__, __LINE__);
-#endif
-			pcsio->scsi_status = SCSI_STATUS_BUSY;
-			pccb->ccb_h.status = CAM_SCSI_BUSY;
-		} else if (status == SCSI_STATUS_RESERV_CONFLICT) {
-#ifdef AMD_DEBUG0
-			printf("DC390: target reserved at %s %d\n",
-			       __FILE__, __LINE__);
-#endif
-			pcsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
-			pccb->ccb_h.status = CAM_SCSI_STATUS_ERROR; /* XXX */
-		} else {
-			pSRB->AdaptStatus = 0;
-#ifdef AMD_DEBUG0
-			printf("DC390: driver stuffup at %s %d\n",
-			       __FILE__, __LINE__);
-#endif
-			pccb->ccb_h.status = CAM_SCSI_STATUS_ERROR;
-		}
-	} else {
-		status = pSRB->AdaptStatus;
-		if (status & H_OVER_UNDER_RUN) {
-			pSRB->TargetStatus = 0;
-
-			pccb->ccb_h.status = CAM_DATA_RUN_ERR;	
-		} else if (pSRB->SRBStatus & PARITY_ERROR) {
-#ifdef AMD_DEBUG0
-			printf("DC390: driver stuffup %s %d\n",
-			       __FILE__, __LINE__);
-#endif
-			/* Driver failed to perform operation	  */
-			pccb->ccb_h.status = CAM_UNCOR_PARITY;
-		} else {	/* No error */
-			pSRB->AdaptStatus = 0;
-			pSRB->TargetStatus = 0;
-			pcsio->resid = 0;
-			/* there is no error, (sense is invalid)  */
-		}
-	}
-ckc_e:
-	intflag = splcam();
-	if ((pccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
-		/* CAM request not yet complete =>device_Q frozen */
-		xpt_freeze_devq(pccb->ccb_h.path, 1);
-		pccb->ccb_h.status |= CAM_DEV_QFRZN;
-	}
-	TAILQ_REMOVE(&amd->running_srbs, pSRB, links);
-	TAILQ_INSERT_HEAD(&amd->free_srbs, pSRB, links);
-	amdrunwaiting(amd);
-	splx(intflag);
-	xpt_done(pccb);
-
-}
-
-static void
-amd_ResetSCSIBus(struct amd_softc * amd)
-{
-	int     intflag;
-
-	intflag = splcam();
-	amd->ACBFlag |= RESET_DEV;
-	amd_write8(amd, DMA_Cmd, DMA_IDLE_CMD);
-	amd_write8(amd, SCSICMDREG, RST_SCSI_BUS_CMD);
-	splx(intflag);
-	return;
-}
-
-static void
-amd_ScsiRstDetect(struct amd_softc * amd)
-{
-	int     intflag;
-	u_int32_t   wlval;
-
-#ifdef AMD_DEBUG0
-	printf("amd_ScsiRstDetect \n");
-#endif
-
-	wlval = 1000;
-	while (--wlval) {	/* delay 1 sec */
-		DELAY(1000);
-	}
-	intflag = splcam();
-
-	amd_write8(amd, DMA_Cmd, DMA_IDLE_CMD);
-	amd_write8(amd, SCSICMDREG, CLEAR_FIFO_CMD);
-
-	if (amd->ACBFlag & RESET_DEV) {
-		amd->ACBFlag |= RESET_DONE;
-	} else {
-		amd->ACBFlag |= RESET_DETECT;
-		ResetDevParam(amd);
-		amdcompletematch(amd, CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD,
-				 AMD_TAG_WILDCARD, &amd->running_srbs,
-				 CAM_DEV_QFRZN|CAM_SCSI_BUS_RESET);
-		amdcompletematch(amd, CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD,
-				 AMD_TAG_WILDCARD, &amd->waiting_srbs,
-				 CAM_DEV_QFRZN|CAM_SCSI_BUS_RESET);
-		amd->active_srb = NULL;
-		amd->ACBFlag = 0;
-		amdrunwaiting(amd);
-	}
-	splx(intflag);
-	return;
-}
-
-static void
-RequestSense(struct amd_softc *amd, struct amd_srb *pSRB)
-{
-	union ccb *pccb;
-	struct ccb_scsiio *pcsio;
-
-	pccb = pSRB->pccb;
-	pcsio = &pccb->csio;
-
-	pSRB->SRBFlag |= AUTO_REQSENSE;
-	pSRB->Segment0[0] = *((u_int32_t *) & (pSRB->CmdBlock[0]));
-	pSRB->Segment0[1] = *((u_int32_t *) & (pSRB->CmdBlock[4]));
-	pSRB->Segment1[0] = (pSRB->ScsiCmdLen << 8) + pSRB->SGcount;
-	pSRB->Segment1[1] = pSRB->TotalXferredLen;
-
-	pSRB->AdaptStatus = 0;
-	pSRB->TargetStatus = 0;
-
-	pSRB->Segmentx.SGXPtr = amd_get_sense_bufaddr(amd, pSRB);
-	pSRB->Segmentx.SGXLen = amd_get_sense_bufsize(amd, pSRB);
-
-	pSRB->pSGlist = &pSRB->Segmentx;
-	pSRB->SGcount = 1;
-	pSRB->SGIndex = 0;
-
-	pSRB->CmdBlock[0] = REQUEST_SENSE;
-	pSRB->CmdBlock[1] = pSRB->pccb->ccb_h.target_lun << 5;
-	pSRB->CmdBlock[2] = 0;
-	pSRB->CmdBlock[3] = 0;
-	pSRB->CmdBlock[4] = pcsio->sense_len;
-	pSRB->CmdBlock[5] = 0;
-	pSRB->ScsiCmdLen = 6;
-
-	pSRB->TotalXferredLen = 0;
-	pSRB->SGToBeXferLen = 0;
-	if (amdstart(amd, pSRB) != 0) {
-		TAILQ_REMOVE(&amd->running_srbs, pSRB, links);
-		TAILQ_INSERT_HEAD(&amd->waiting_srbs, pSRB, links);
-	}
-}
-
-static void
-amd_InvalidCmd(struct amd_softc * amd)
-{
-	struct amd_srb *srb;
-
-	srb = amd->active_srb;
-	if (srb->SRBState & (SRB_START|SRB_MSGOUT))
-		amd_write8(amd, SCSICMDREG, CLEAR_FIFO_CMD);
-}
-
-void 
-amd_linkSRB(struct amd_softc *amd)
-{
-	u_int16_t  count, i;
-	struct amd_srb *psrb;
-	int error;
-
-	count = amd->SRBCount;
-
-	for (i = 0; i < count; i++) {
-		psrb = (struct amd_srb *)&amd->SRB_array[i];
-		psrb->TagNumber = i;
-
-		/*
-		 * Create the dmamap.  This is no longer optional!
-		 *
-		 * XXX Since there is no detach method in this driver,
-		 * this does not get freed!
-		 */
-		if ((error = bus_dmamap_create(amd->buffer_dmat, 0,
-					       &psrb->dmamap)) != 0) {
-			device_printf(amd->dev, "Error %d creating buffer "
-				      "dmamap!\n", error);
-			return;
-		}
-		TAILQ_INSERT_TAIL(&amd->free_srbs, psrb, links);
-	}
-}
-
-static void
-amd_EnDisableCE(struct amd_softc *amd, int mode, int *regval)
-{
-	if (mode == ENABLE_CE) {
-		*regval = 0xc0;
-	} else {
-		*regval = 0x80;
-	}
-	pci_write_config(amd->dev, *regval, 0, /*bytes*/1);
-	if (mode == DISABLE_CE) {
-		pci_write_config(amd->dev, *regval, 0, /*bytes*/1);
-	}
-	DELAY(160);
-}
-
-static void
-amd_EEpromOutDI(struct amd_softc *amd, int *regval, int Carry)
-{
-	u_int bval;
-
-	bval = 0;
-	if (Carry) {
-		bval = 0x40;
-		*regval = 0x80;
-		pci_write_config(amd->dev, *regval, bval, /*bytes*/1);
-	}
-	DELAY(160);
-	bval |= 0x80;
-	pci_write_config(amd->dev, *regval, bval, /*bytes*/1);
-	DELAY(160);
-	pci_write_config(amd->dev, *regval, 0, /*bytes*/1);
-	DELAY(160);
-}
-
-static int
-amd_EEpromInDO(struct amd_softc *amd)
-{
-	pci_write_config(amd->dev, 0x80, 0x80, /*bytes*/1);
-	DELAY(160);
-	pci_write_config(amd->dev, 0x80, 0x40, /*bytes*/1);
-	DELAY(160);
-	if (pci_read_config(amd->dev, 0, /*bytes*/1) == 0x22)
-		return (1);
-	return (0);
-}
-
-static u_int16_t
-EEpromGetData1(struct amd_softc *amd)
-{
-	u_int	  i;
-	u_int	  carryFlag;
-	u_int16_t wval;
-
-	wval = 0;
-	for (i = 0; i < 16; i++) {
-		wval <<= 1;
-		carryFlag = amd_EEpromInDO(amd);
-		wval |= carryFlag;
-	}
-	return (wval);
-}
-
-static void
-amd_Prepare(struct amd_softc *amd, int *regval, u_int8_t EEpromCmd)
-{
-	u_int i, j;
-	int carryFlag;
-
-	carryFlag = 1;
-	j = 0x80;
-	for (i = 0; i < 9; i++) {
-		amd_EEpromOutDI(amd, regval, carryFlag);
-		carryFlag = (EEpromCmd & j) ? 1 : 0;
-		j >>= 1;
-	}
-}
-
-static void
-amd_ReadEEprom(struct amd_softc *amd)
-{
-	int	   regval;
-	u_int	   i;
-	u_int16_t *ptr;
-	u_int8_t   cmd;
-
-	ptr = (u_int16_t *)&amd->eepromBuf[0];
-	cmd = EEPROM_READ;
-	for (i = 0; i < 0x40; i++) {
-		amd_EnDisableCE(amd, ENABLE_CE, &regval);
-		amd_Prepare(amd, &regval, cmd);
-		*ptr = EEpromGetData1(amd);
-		ptr++;
-		cmd++;
-		amd_EnDisableCE(amd, DISABLE_CE, &regval);
-	}
-}
-
-static void
-amd_load_defaults(struct amd_softc *amd)
-{
-	int target;
-
-	bzero(&amd->eepromBuf, sizeof amd->eepromBuf);
-	for (target = 0; target < MAX_SCSI_ID; target++)
-		amd->eepromBuf[target << 2] =
-		    (TAG_QUEUING|EN_DISCONNECT|SYNC_NEGO|PARITY_CHK);
-	amd->eepromBuf[EE_ADAPT_SCSI_ID] = 7;
-	amd->eepromBuf[EE_MODE2] = ACTIVE_NEGATION|LUN_CHECK|GREATER_1G;
-	amd->eepromBuf[EE_TAG_CMD_NUM] = 4;
-}
-
-static void
-amd_load_eeprom_or_defaults(struct amd_softc *amd)
-{
-	u_int16_t  wval, *ptr;
-	u_int8_t   i;
-
-	amd_ReadEEprom(amd);
-	wval = 0;
-	ptr = (u_int16_t *) & amd->eepromBuf[0];
-	for (i = 0; i < EE_DATA_SIZE; i += 2, ptr++)
-		wval += *ptr;
-
-	if (wval != EE_CHECKSUM) {
-		if (bootverbose)
-			printf("amd%d: SEEPROM data unavailable.  "
-			       "Using default device parameters.\n",
-			       amd->unit);
-		amd_load_defaults(amd);
-	}
-}
-
-/*
- **********************************************************************
- * Function      : static int amd_init (struct Scsi_Host *host)
- * Purpose       : initialize the internal structures for a given SCSI host
- * Inputs        : host - pointer to this host adapter's structure/
- **********************************************************************
- */
-static int
-amd_init(device_t dev)
-{
-	struct amd_softc *amd = device_get_softc(dev);
-	struct resource	*iores;
-	int	i, rid;
-	u_int	bval;
-
-	rid = PCI_BASE_ADDR0;
-	iores = bus_alloc_resource_any(dev, SYS_RES_IOPORT, &rid, RF_ACTIVE);
-	if (iores == NULL) {
-		if (bootverbose)
-			printf("amd_init: bus_alloc_resource failure!\n");
-		return ENXIO;
-	}
-	amd->tag = rman_get_bustag(iores);
-	amd->bsh = rman_get_bushandle(iores);
-
-	/* DMA tag for mapping buffers into device visible space. */
-	if (bus_dma_tag_create(/*parent_dmat*/NULL, /*alignment*/1,
-			       /*boundary*/0,
-			       /*lowaddr*/BUS_SPACE_MAXADDR_32BIT,
-			       /*highaddr*/BUS_SPACE_MAXADDR,
-			       /*filter*/NULL, /*filterarg*/NULL,
-			       /*maxsize*/MAXBSIZE, /*nsegments*/AMD_NSEG,
-			       /*maxsegsz*/AMD_MAXTRANSFER_SIZE,
-			       /*flags*/BUS_DMA_ALLOCNOW,
-			       /*lockfunc*/busdma_lock_mutex,
-			       /*lockarg*/&Giant,
-			       &amd->buffer_dmat) != 0) {
-		if (bootverbose)
-			printf("amd_init: bus_dma_tag_create failure!\n");
-		return ENXIO;
-        }
-
-	/* Create, allocate, and map DMA buffers for autosense data */
-	if (bus_dma_tag_create(/*parent_dmat*/NULL, /*alignment*/1,
-			       /*boundary*/0,
-			       /*lowaddr*/BUS_SPACE_MAXADDR_32BIT,
-			       /*highaddr*/BUS_SPACE_MAXADDR,
-			       /*filter*/NULL, /*filterarg*/NULL,
-			       sizeof(struct scsi_sense_data) * MAX_SRB_CNT,
-			       /*nsegments*/1,
-			       /*maxsegsz*/AMD_MAXTRANSFER_SIZE,
-			       /*flags*/0,
-			       /*lockfunc*/busdma_lock_mutex,
-			       /*lockarg*/&Giant, &amd->sense_dmat) != 0) {
-		if (bootverbose)
-			device_printf(dev, "cannot create sense buffer dmat\n");
-		return (ENXIO);
-	}
-
-	if (bus_dmamem_alloc(amd->sense_dmat, (void **)&amd->sense_buffers,
-			     BUS_DMA_NOWAIT, &amd->sense_dmamap) != 0)
-		return (ENOMEM);
-
-	bus_dmamap_load(amd->sense_dmat, amd->sense_dmamap,
-		       amd->sense_buffers,
-		       sizeof(struct scsi_sense_data) * MAX_SRB_CNT,
-		       amd_dmamap_cb, &amd->sense_busaddr, /*flags*/0);
-
-	TAILQ_INIT(&amd->free_srbs);
-	TAILQ_INIT(&amd->running_srbs);
-	TAILQ_INIT(&amd->waiting_srbs);
-	amd->last_phase = SCSI_BUS_FREE;
-	amd->dev = dev;
-	amd->unit = device_get_unit(dev);
-	amd->SRBCount = MAX_SRB_CNT;
-	amd->status = 0;
-	amd_load_eeprom_or_defaults(amd);
-	amd->max_id = 7;
-	if (amd->eepromBuf[EE_MODE2] & LUN_CHECK) {
-		amd->max_lun = 7;
-	} else {
-		amd->max_lun = 0;
-	}
-	amd->AdaptSCSIID = amd->eepromBuf[EE_ADAPT_SCSI_ID];
-	amd->HostID_Bit = (1 << amd->AdaptSCSIID);
-	amd->AdaptSCSILUN = 0;
-	/* (eepromBuf[EE_TAG_CMD_NUM]) << 2; */
-	amd->ACBFlag = 0;
-	amd->Gmode2 = amd->eepromBuf[EE_MODE2];
-	amd_linkSRB(amd);
-	for (i = 0; i <= amd->max_id; i++) {
-
-		if (amd->AdaptSCSIID != i) {
-			struct amd_target_info *tinfo;
-			PEEprom prom;
-
-			tinfo = &amd->tinfo[i];
-			prom = (PEEprom)&amd->eepromBuf[i << 2];
-			if ((prom->EE_MODE1 & EN_DISCONNECT) != 0) {
-				tinfo->disc_tag |= AMD_USR_DISCENB;
-				if ((prom->EE_MODE1 & TAG_QUEUING) != 0)
-					tinfo->disc_tag |= AMD_USR_TAGENB;
-			}
-			if ((prom->EE_MODE1 & SYNC_NEGO) != 0) {
-				tinfo->user.period =
-				    eeprom_period[prom->EE_SPEED];
-				tinfo->user.offset = AMD_MAX_SYNC_OFFSET;
-			}
-			tinfo->CtrlR1 = amd->AdaptSCSIID;
-			if ((prom->EE_MODE1 & PARITY_CHK) != 0)
-				tinfo->CtrlR1 |= PARITY_ERR_REPO;
-			tinfo->CtrlR3 = FAST_CLK;
-			tinfo->CtrlR4 = EATER_25NS;
-			if ((amd->eepromBuf[EE_MODE2] & ACTIVE_NEGATION) != 0)
-				tinfo->CtrlR4 |= NEGATE_REQACKDATA;
-		}
-	}
-	amd_write8(amd, SCSITIMEOUTREG, 153); /* 250ms selection timeout */
-	/* Conversion factor = 0 , 40MHz clock */
-	amd_write8(amd, CLKFACTREG, CLK_FREQ_40MHZ);
-	/* NOP cmd - clear command register */
-	amd_write8(amd, SCSICMDREG, NOP_CMD);	
-	amd_write8(amd, CNTLREG2, EN_FEATURE|EN_SCSI2_CMD);
-	amd_write8(amd, CNTLREG3, FAST_CLK);
-	bval = EATER_25NS;
-	if (amd->eepromBuf[EE_MODE2] & ACTIVE_NEGATION) {
-		bval |= NEGATE_REQACKDATA;
-	}
-	amd_write8(amd, CNTLREG4, bval);
-
-	/* Disable SCSI bus reset interrupt */
-	amd_write8(amd, CNTLREG1, DIS_INT_ON_SCSI_RST);
-
-	return 0;
-}
-
-/*
- * attach and init a host adapter
- */
-static int
-amd_attach(device_t dev)
-{
-	struct cam_devq	*devq;	/* Device Queue to use for this SIM */
-	u_int8_t	intstat;
-	struct amd_softc *amd = device_get_softc(dev);
-	int		unit = device_get_unit(dev);
-	int		rid;
-	void		*ih;
-	struct resource	*irqres;
-
-	if (amd_init(dev)) {
-		if (bootverbose)
-			printf("amd_attach: amd_init failure!\n");
-		return ENXIO;
-	}
-
-	/* Reset Pending INT */
-	intstat = amd_read8(amd, INTSTATREG);
-
-	/* After setting up the adapter, map our interrupt */
-	rid = 0;
-	irqres = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid,
-					RF_SHAREABLE | RF_ACTIVE);
-	if (irqres == NULL ||
-	    bus_setup_intr(dev, irqres, INTR_TYPE_CAM | INTR_ENTROPY,
-	    NULL, amd_intr, amd, &ih)) {
-		if (bootverbose)
-			printf("amd%d: unable to register interrupt handler!\n",
-			       unit);
-		return ENXIO;
-	}
-
-	/*
-	 * Now let the CAM generic SCSI layer find the SCSI devices on
-	 * the bus *  start queue to reset to the idle loop. *
-	 * Create device queue of SIM(s) *  (MAX_START_JOB - 1) :
-	 * max_sim_transactions
-	 */
-	devq = cam_simq_alloc(MAX_START_JOB);
-	if (devq == NULL) {
-		if (bootverbose)
-			printf("amd_attach: cam_simq_alloc failure!\n");
-		return ENXIO;
-	}
-
-	amd->psim = cam_sim_alloc(amd_action, amd_poll, "amd",
-				  amd, amd->unit, &Giant,
-				  1, MAX_TAGS_CMD_QUEUE, devq);
-	if (amd->psim == NULL) {
-		cam_simq_free(devq);
-		if (bootverbose)
-			printf("amd_attach: cam_sim_alloc failure!\n");
-		return ENXIO;
-	}
-
-	if (xpt_bus_register(amd->psim, dev, 0) != CAM_SUCCESS) {
-		cam_sim_free(amd->psim, /*free_devq*/TRUE);
-		if (bootverbose)
-			printf("amd_attach: xpt_bus_register failure!\n");
-		return ENXIO;
-	}
-
-	if (xpt_create_path(&amd->ppath, /* periph */ NULL,
-			    cam_sim_path(amd->psim), CAM_TARGET_WILDCARD,
-			    CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
-		xpt_bus_deregister(cam_sim_path(amd->psim));
-		cam_sim_free(amd->psim, /* free_simq */ TRUE);
-		if (bootverbose)
-			printf("amd_attach: xpt_create_path failure!\n");
-		return ENXIO;
-	}
-
-	return 0;
-}
-
-static int
-amd_probe(device_t dev)
-{
-	if (pci_get_devid(dev) == PCI_DEVICE_ID_AMD53C974) {
-		device_set_desc(dev,
-			"Tekram DC390(T)/AMD53c974 SCSI Host Adapter");
-		return BUS_PROBE_DEFAULT;
-	}
-	return ENXIO;
-}
-
-static device_method_t amd_methods[] = {
-	/* Device interface */
-	DEVMETHOD(device_probe,		amd_probe),
-	DEVMETHOD(device_attach,	amd_attach),
-	{ 0, 0 }
-};
-
-static driver_t amd_driver = {
-	"amd", amd_methods, sizeof(struct amd_softc)
-};
-
-static devclass_t amd_devclass;
-DRIVER_MODULE(amd, pci, amd_driver, amd_devclass, 0, 0);
-MODULE_DEPEND(amd, pci, 1, 1, 1);
-MODULE_DEPEND(amd, cam, 1, 1, 1);
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/amd/amd.h
--- a/head/sys/dev/amd/amd.h	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,585 +0,0 @@
-/*-
- *********************************************************************
- *	FILE NAME  : amd.h
- *	     BY    : C.L. Huang 	(ching at tekram.com.tw)
- *		     Erich Chen     (erich at tekram.com.tw)
- *	Description: Device Driver for the amd53c974 PCI Bus Master
- *		     SCSI Host adapter found on cards such as
- *		     the Tekram DC-390(T).
- * (C)Copyright 1995-1999 Tekram Technology Co., Ltd.
- *
- * 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$
- */
-
-#ifndef AMD_H
-#define AMD_H
-
-#define AMD_TRANS_CUR		0x01	/* Modify current neogtiation status */
-#define AMD_TRANS_ACTIVE	0x03	/* Assume this is the active target */
-#define AMD_TRANS_GOAL		0x04	/* Modify negotiation goal */
-#define AMD_TRANS_USER		0x08	/* Modify user negotiation settings */
-
-/*
- * Per target transfer parameters.
- */
-struct amd_transinfo {
-	u_int8_t period;
-	u_int8_t offset;
-};
-
-struct amd_target_info {
-	/*
-	 * Records the currently active and user/default settings for
-	 * tagged queueing and disconnection for each target.
-	 */
-	u_int8_t disc_tag;
-#define		AMD_CUR_DISCENB	0x01
-#define		AMD_CUR_TAGENB	0x02
-#define		AMD_USR_DISCENB	0x04
-#define		AMD_USR_TAGENB	0x08
-	u_int8_t   CtrlR1;
-	u_int8_t   CtrlR3;
-	u_int8_t   CtrlR4;
-	u_int8_t   sync_period_reg;
-	u_int8_t   sync_offset_reg;
-
-	/*
-	 * Currently active transfer settings.
-	 */
-	struct amd_transinfo current;
-	/*
-	 * Transfer settings we wish to achieve
-	 * through negotiation.
-	 */
-	struct amd_transinfo goal;
-	/*
-	 * User defined or default transfer settings.
-	 */
-	struct amd_transinfo user;
-};
-
-/*
- * Scatter/Gather Segment entry.
- */
-struct amd_sg {
-	u_int32_t   SGXLen;
-	u_int32_t   SGXPtr;
-};
-
-/*
- * Chipset feature limits
- */
-#define MAX_SCSI_ID		8
-#define AMD_MAX_SYNC_OFFSET	15
-#define AMD_TARGET_MAX	7
-#define AMD_LUN_MAX		7
-#define AMD_MAXPHYS		(128 * 1024) /* legacy MAXPHYS */
-#define AMD_NSEG		(btoc(AMD_MAXPHYS) + 1)
-#define AMD_MAXTRANSFER_SIZE	0xFFFFFF /* restricted by 24 bit counter */
-#define MAX_DEVICES		10
-#define MAX_TAGS_CMD_QUEUE	256
-#define MAX_CMD_PER_LUN		6
-#define MAX_SRB_CNT		256
-#define MAX_START_JOB		256
-
-/*
- * BIT position to integer mapping.
- */
-#define BIT(N) (0x01 << N)
-
-/*
- * EEPROM storage offsets and data structures.
- */
-typedef struct _EEprom {
-	u_int8_t   EE_MODE1;
-	u_int8_t   EE_SPEED;
-	u_int8_t   xx1;
-	u_int8_t   xx2;
-}       EEprom, *PEEprom;
-
-#define EE_ADAPT_SCSI_ID	64
-#define EE_MODE2		65
-#define EE_DELAY		66
-#define EE_TAG_CMD_NUM		67
-#define EE_DATA_SIZE		128
-#define EE_CHECKSUM		0x1234
-
-/*
- * EE_MODE1 bits definition
- */
-#define PARITY_CHK   	  	BIT(0)
-#define SYNC_NEGO      		BIT(1)
-#define EN_DISCONNECT  		BIT(2)
-#define SEND_START     		BIT(3)
-#define TAG_QUEUING    		BIT(4)
-
-/*
- * EE_MODE2 bits definition
- */
-#define MORE2_DRV		BIT(0)
-#define GREATER_1G		BIT(1)
-#define RST_SCSI_BUS		BIT(2)
-#define ACTIVE_NEGATION		BIT(3)
-#define NO_SEEK			BIT(4)
-#define LUN_CHECK		BIT(5)
-
-#define ENABLE_CE		1
-#define DISABLE_CE		0
-#define EEPROM_READ		0x80
-
-#define AMD_TAG_WILDCARD ((u_int)(~0))
-
-/*
- * SCSI Request Block
- */
-struct amd_srb {
-	TAILQ_ENTRY(amd_srb) links;
-	u_int8_t	 CmdBlock[12];
-	union		 ccb *pccb;
-	bus_dmamap_t	 dmamap;
-	struct		 amd_sg *pSGlist;
-
-	u_int32_t	 TotalXferredLen;
-	u_int32_t	 SGPhysAddr;	/* a segment starting address */
-	u_int32_t	 SGToBeXferLen;	/* to be xfer length */
-	u_int32_t	 Segment0[2];
-	u_int32_t	 Segment1[2];
-
-	struct		 amd_sg SGsegment[AMD_NSEG];
-	struct		 amd_sg Segmentx;/* a one entry of S/G list table */
-	u_int8_t	*pMsgPtr;
-	u_int16_t	 SRBState;
-
-	u_int8_t	 AdaptStatus;
-	u_int8_t	 TargetStatus;
-	u_int8_t	 MsgCnt;
-	u_int8_t	 EndMessage;
-	u_int8_t	 TagNumber;
-	u_int8_t	 SGcount;
-	u_int8_t	 SGIndex;
-	u_int8_t	 IORBFlag;	/* ;81h-Reset, 2-retry */
-
-	u_int8_t	 SRBStatus;
-	u_int8_t	 SRBFlag;
-	/* ; b0-AutoReqSense,b6-Read,b7-write */
-	/* ; b4-settimeout,b5-Residual valid */
-	u_int8_t	 ScsiCmdLen;
-};
-
-TAILQ_HEAD(srb_queue, amd_srb);
-
-/*
- * Per-adapter, software configuration.
- */
-struct amd_softc {
-	device_t		dev;
-	bus_space_tag_t		tag;
-	bus_space_handle_t	bsh;
-	bus_dma_tag_t		buffer_dmat;   /* dmat for buffer I/O */  
-	bus_dma_tag_t		sense_dmat;   /* dmat for sense buffer */  
-	bus_dmamap_t		sense_dmamap;
-	struct scsi_sense_data	*sense_buffers;
-	bus_addr_t		sense_busaddr;
-	int			unit;
-
-	int	   last_phase;
-	int	   cur_target;
-	int	   cur_lun;
-	struct	   amd_srb *active_srb;
-	struct	   amd_srb *untagged_srbs[AMD_TARGET_MAX+1][AMD_LUN_MAX+1];
-	struct	   amd_target_info tinfo[AMD_TARGET_MAX+1];
-	u_int16_t  disc_count[AMD_TARGET_MAX+1][AMD_LUN_MAX+1];
-
-	struct	   srb_queue free_srbs;
-	struct	   srb_queue waiting_srbs;
-	struct	   srb_queue running_srbs;
-
-	struct	   amd_srb *pTmpSRB;
-
-	u_int16_t  SRBCount;
-
-	u_int16_t  max_id;
-	u_int16_t  max_lun;
-
-	/* Hooks into the CAM XPT */
-	struct	   cam_sim *psim;
-	struct	   cam_path *ppath;
-
-	u_int8_t   msgin_buf[6];
-	u_int8_t   msgout_buf[6];
-	u_int	   msgin_index;
-	u_int	   msgout_index;
-	u_int	   msgout_len;
-
-	u_int8_t   status;
-	u_int8_t   AdaptSCSIID;		/* ; Adapter SCSI Target ID */
-	u_int8_t   AdaptSCSILUN;	/* ; Adapter SCSI LUN */
-
-	u_int8_t   ACBFlag;
-
-	u_int8_t   Gmode2;
-
-	u_int8_t   HostID_Bit;
-
-	u_int8_t   InitDCB_flag[8][8];	/* flag of initDCB for device */
-	struct	   amd_srb SRB_array[MAX_SRB_CNT]; /* +45Ch, Len=	 */
-	struct	   amd_srb TmpSRB;
-	/* Setup data stored in an 93c46 serial eeprom */
-	u_int8_t   eepromBuf[EE_DATA_SIZE];
-};
-
-/*
- *   ----SRB State machine definition
- */
-#define SRB_FREE        	0
-#define SRB_READY       	BIT(1)
-#define SRB_MSGOUT      	BIT(2)	/* ;arbitration+msg_out 1st byte */
-#define SRB_MSGIN       	BIT(3)
-#define SRB_MSGIN_MULTI		BIT(4)
-#define SRB_COMMAND     	BIT(5)
-#define SRB_START	     	BIT(6)	/* ;arbitration+msg_out+command_out */
-#define SRB_DISCONNECT   	BIT(7)
-#define SRB_DATA_XFER    	BIT(8)
-#define SRB_XFERPAD     	BIT(9)
-#define SRB_STATUS      	BIT(10)
-#define SRB_COMPLETED    	BIT(11)
-#define SRB_ABORT_SENT   	BIT(12)
-#define DO_SYNC_NEGO    	BIT(13)
-#define SRB_UNEXPECT_RESEL	BIT(14)
-
-/*
- *   ---ACB Flag
- */
-#define RESET_DEV       	BIT(0)
-#define RESET_DETECT    	BIT(1)
-#define RESET_DONE      	BIT(2)
-
-/*
- *   ---DCB Flag
- */
-#define ABORT_DEV_      	BIT(0)
-
-/*
- *   ---SRB status
- */
-#define SRB_OK	        	BIT(0)
-#define ABORTION        	BIT(1)
-#define OVER_RUN        	BIT(2)
-#define UNDER_RUN       	BIT(3)
-#define PARITY_ERROR    	BIT(4)
-#define SRB_ERROR       	BIT(5)
-
-/*
- *   ---SRB Flags
- */
-#define DATAOUT         	BIT(7)
-#define DATAIN	        	BIT(6)
-#define RESIDUAL_VALID   	BIT(5)
-#define ENABLE_TIMER    	BIT(4)
-#define RESET_DEV0      	BIT(2)
-#define ABORT_DEV       	BIT(1)
-#define AUTO_REQSENSE    	BIT(0)
-
-/*
- *   ---Adapter status
- */
-#define H_STATUS_GOOD		0
-#define H_SEL_TIMEOUT		0x11
-#define H_OVER_UNDER_RUN	0x12
-#define H_UNEXP_BUS_FREE	0x13
-#define H_TARGET_PHASE_F	0x14
-#define H_INVALID_CCB_OP	0x16
-#define H_LINK_CCB_BAD		0x17
-#define H_BAD_TARGET_DIR	0x18
-#define H_DUPLICATE_CCB		0x19
-#define H_BAD_CCB_OR_SG		0x1A
-#define H_ABORT			0x0FF
-
-/*
- * AMD specific "status" codes returned in the SCSI status byte.
- */
-#define AMD_SCSI_STAT_UNEXP_BUS_F    	0xFD	/* ;  Unexpect Bus Free */
-#define AMD_SCSI_STAT_BUS_RST_DETECT	0xFE	/* ;  Scsi Bus Reset detected */
-#define AMD_SCSI_STAT_SEL_TIMEOUT   	0xFF	/* ;  Selection Time out */
-
-/*
- *   ---Sync_Mode
- */
-#define SYNC_DISABLE	    0
-#define SYNC_ENABLE 	    BIT(0)
-#define SYNC_NEGO_DONE	    BIT(1)
-#define WIDE_ENABLE 	    BIT(2)
-#define WIDE_NEGO_DONE	    BIT(3)
-#define EN_TAG_QUEUING	    BIT(4)
-#define EN_ATN_STOP         BIT(5)
-
-#define SYNC_NEGO_OFFSET    15
-
-/*
- *    ---SCSI bus phase
- */
-#define SCSI_DATA_OUT		0
-#define SCSI_DATA_IN		1
-#define SCSI_COMMAND		2
-#define SCSI_STATUS		3
-#define SCSI_NOP0		4
-#define SCSI_ARBITRATING	5
-#define SCSI_MSG_OUT		6
-#define SCSI_MSG_IN		7
-#define SCSI_BUS_FREE		8
-
-/*
- *==========================================================
- *      	AMD 53C974 Registers bit Definition
- *==========================================================
- */
-
-/*
- *      ------SCSI Register-------
- *      Command Reg.(+0CH)
- */
-#define DMA_COMMAND   	    	BIT(7)
-#define NOP_CMD 	       	0
-#define CLEAR_FIFO_CMD	    	1
-#define RST_DEVICE_CMD	    	2
-#define RST_SCSI_BUS_CMD    	3
-#define INFO_XFER_CMD	    	0x10
-#define INITIATOR_CMD_CMPLTE	0x11
-#define MSG_ACCEPTED_CMD    	0x12
-#define XFER_PAD_BYTE	     	0x18
-#define SET_ATN_CMD	       	0x1A
-#define RESET_ATN_CMD    	0x1B
-#define SEL_W_ATN		0x42
-#define SEL_W_ATN_STOP	    	0x43
-#define EN_SEL_RESEL	    	0x44
-#define SEL_W_ATN2	       	0x46
-#define DATA_XFER_CMD	    	INFO_XFER_CMD
-
-
-/*
- *     ------SCSI Register-------
- *     SCSI Status Reg.(+10H)
- */
-#define INTERRUPT	    	BIT(7)
-#define ILLEGAL_OP_ERR		BIT(6)
-#define PARITY_ERR	    	BIT(5)
-#define COUNT_2_ZERO		BIT(4)
-#define GROUP_CODE_VALID	BIT(3)
-#define SCSI_PHASE_MASK 	(BIT(2)+BIT(1)+BIT(0))
-
-/*
- *     ------SCSI Register-------
- *     Interrupt Status Reg.(+14H)
- */
-#define SCSI_RESET_	    	BIT(7)
-#define INVALID_CMD	    	BIT(6)
-#define DISCONNECTED		BIT(5)
-#define SERVICE_REQUEST 	BIT(4)
-#define SUCCESSFUL_OP		BIT(3)
-#define RESELECTED	    	BIT(2)
-#define SEL_ATTENTION		BIT(1)
-#define SELECTED	    	BIT(0)
-
-/*
- *     ------SCSI Register-------
- *    Internal State Reg.(+18H)
- */
-#define SYNC_OFFSET_FLAG	BIT(3)
-#define INTRN_STATE_MASK	(BIT(2)+BIT(1)+BIT(0))
-
-/*
- *     ------SCSI Register-------
- *     Clock Factor Reg.(+24H)
- */
-#define CLK_FREQ_40MHZ		0
-#define CLK_FREQ_35MHZ		(BIT(2)+BIT(1)+BIT(0))
-#define CLK_FREQ_30MHZ		(BIT(2)+BIT(1))
-#define CLK_FREQ_25MHZ		(BIT(2)+BIT(0))
-#define CLK_FREQ_20MHZ		BIT(2)
-#define CLK_FREQ_15MHZ		(BIT(1)+BIT(0))
-#define CLK_FREQ_10MHZ		BIT(1)
-
-/*
- *     ------SCSI Register-------
- *     Control Reg. 1(+20H)
- */
-#define EXTENDED_TIMING 	BIT(7)
-#define DIS_INT_ON_SCSI_RST	BIT(6)
-#define PARITY_ERR_REPO 	BIT(4)
-#define SCSI_ID_ON_BUS		(BIT(2)+BIT(1)+BIT(0))
-
-/*
- *     ------SCSI Register-------
- *     Control Reg. 2(+2CH)
- */
-#define EN_FEATURE	    	BIT(6)
-#define EN_SCSI2_CMD		BIT(3)
-
-/*
- *     ------SCSI Register-------
- *     Control Reg. 3(+30H)
- */
-#define ID_MSG_CHECK		BIT(7)
-#define EN_QTAG_MSG	    	BIT(6)
-#define EN_GRP2_CMD	    	BIT(5)
-#define FAST_SCSI	    	BIT(4)	/* ;10MB/SEC */
-#define FAST_CLK	    	BIT(3)	/* ;25 - 40 MHZ */
-
-/*
- *     ------SCSI Register-------
- *     Control Reg. 4(+34H)
- */
-#define EATER_12NS	    	0
-#define EATER_25NS	    	BIT(7)
-#define EATER_35NS	    	BIT(6)
-#define EATER_0NS	    	(BIT(7)+BIT(6))
-#define NEGATE_REQACKDATA	BIT(2)
-#define NEGATE_REQACK		BIT(3)
-
-/*
- *========================================
- *             DMA Register
- *========================================
- */
-
-/*
- *        -------DMA Register--------
- *        DMA Command Reg.(+40H)
- */
-#define READ_DIRECTION		BIT(7)
-#define WRITE_DIRECTION 	0
-#define EN_DMA_INT	    	BIT(6)
-#define MAP_TO_MDL	    	BIT(5)
-#define DMA_DIAGNOSTIC		BIT(4)
-#define DMA_IDLE_CMD		0
-#define DMA_BLAST_CMD		BIT(0)
-#define DMA_ABORT_CMD		BIT(1)
-#define DMA_START_CMD		(BIT(1)|BIT(0))
-
-/*
- *        -------DMA Register--------
- *         DMA Status Reg.(+54H)
- */
-#define PCI_MS_ABORT		BIT(6)
-#define BLAST_COMPLETE		BIT(5)
-#define SCSI_INTERRUPT		BIT(4)
-#define DMA_XFER_DONE		BIT(3)
-#define DMA_XFER_ABORT		BIT(2)
-#define DMA_XFER_ERROR		BIT(1)
-#define POWER_DOWN	    	BIT(0)
-
-/*
- *        -------DMA Register--------
- *        DMA SCSI Bus and Ctrl.(+70H)
- *        EN_INT_ON_PCI_ABORT
- */
-
-/*
- *==========================================================
- *           SCSI Chip register address offset
- *==========================================================
- */
-#define CTCREG_LOW   	0x00	/* (R)   current transfer count register low */
-#define STCREG_LOW   	0x00	/* (W)   start transfer count register low */
-
-#define CTCREG_MID   	0x04	/* (R)   current transfer count register
-				 * middle */
-#define STCREG_MID   	0x04	/* (W)   start transfer count register middle */
-
-#define SCSIFIFOREG    	0x08	/* (R/W) SCSI FIFO register */
-
-#define SCSICMDREG     	0x0C	/* (R/W) SCSI command register */
-
-#define SCSISTATREG  	0x10	/* (R)   SCSI status register */
-#define SCSIDESTIDREG  	0x10	/* (W)   SCSI destination ID register */
-
-#define INTSTATREG   	0x14	/* (R)   interrupt status register */
-#define SCSITIMEOUTREG 	0x14	/* (W)   SCSI timeout register */
-
-
-#define INTERNSTATREG  	0x18	/* (R)   internal state register */
-#define SYNCPERIOREG  	0x18	/* (W)   synchronous transfer period register */
-
-#define CURRENTFIFOREG  0x1C	/* (R)   current FIFO/internal state register */
-#define SYNCOFFREG 	    0x1C/* (W)   synchronous transfer period register */
-
-#define CNTLREG1    	0x20	/* (R/W) control register 1 */
-#define CLKFACTREG  	0x24	/* (W)   clock factor register */
-#define CNTLREG2    	0x2C	/* (R/W) control register 2 */
-#define CNTLREG3    	0x30	/* (R/W) control register 3 */
-#define CNTLREG4    	0x34	/* (R/W) control register 4 */
-
-#define CURTXTCNTREG  	0x38	/* (R)   current transfer count register
-				 * high/part-unique ID code */
-#define STCREG_HIGH  	0x38	/* (W)   Start current transfer count register
-				 * high */
-
-/*
- *********************************************************
- *
- *                 SCSI DMA register
- *
- *********************************************************
- */
-#define DMA_Cmd     	0x40	/* (R/W) command register */
-#define DMA_XferCnt  	0x44	/* (R/W) starting transfer count */
-#define DMA_XferAddr	0x48	/* (R/W) starting Physical address */
-#define DMA_Wk_ByteCntr 0x4C	/* ( R ) working byte counter */
-#define DMA_Wk_AddrCntr 0x50	/* ( R ) working address counter */
-#define DMA_Status   	0x54	/* ( R ) status register */
-#define DMA_MDL_Addr	0x58	/* (R/W) starting memory descriptor list (MDL)
-				 * address */
-#define DMA_Wk_MDL_Cntr 0x5C	/* ( R ) working MDL counter */
-#define DMA_ScsiBusCtrl 0x70	/* (bits R/W) SCSI BUS and control */
-
-/* ******************************************************* */
-#define am_target    	SCSISTATREG
-#define am_timeout   	INTSTATREG
-#define am_seq_step 	SYNCPERIOREG
-#define am_fifo_count	SYNCOFFREG
-
-
-#define amd_read8(amd, port)				\
-	bus_space_read_1((amd)->tag, (amd)->bsh, port)
-
-#define amd_read16(amd, port)				\
-	bus_space_read_2((amd)->tag, (amd)->bsh, port)
-
-#define amd_read32(amd, port)				\
-	bus_space_read_4((amd)->tag, (amd)->bsh, port)
-
-#define amd_write8(amd, port, value)			\
-	bus_space_write_1((amd)->tag, (amd)->bsh, port, value)
-
-#define amd_write8_multi(amd, port, ptr, len)		\
-	bus_space_write_multi_1((amd)->tag, (amd)->bsh, port, ptr, len)
-
-#define amd_write16(amd, port, value)			\
-	bus_space_write_2((amd)->tag, (amd)->bsh, port, value)
-
-#define amd_write32(amd, port, value)			\
-	bus_space_write_4((amd)->tag, (amd)->bsh, port, value)
-
-#endif /* AMD_H */
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/arcmsr/arcmsr.c
--- a/head/sys/dev/arcmsr/arcmsr.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/arcmsr/arcmsr.c	Tue Dec 06 20:26:16 2011 +0200
@@ -73,7 +73,7 @@
 */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/arcmsr/arcmsr.c 227843 2011-11-22 21:28:20Z marius $");
+__FBSDID("$FreeBSD: head/sys/dev/arcmsr/arcmsr.c 227912 2011-11-23 21:43:51Z marius $");
 
 #if 0
 #define ARCMSR_DEBUG1			1
@@ -2714,16 +2714,20 @@
 			xpt_done(pccb);
 			break;
 		}
-	case XPT_CALC_GEOMETRY: {
-			struct ccb_calc_geometry *ccg;
-			u_int32_t size_mb;
-			u_int32_t secs_per_cylinder;
-	
+	case XPT_CALC_GEOMETRY:
 			if(pccb->ccb_h.target_id == 16) {
 				pccb->ccb_h.status |= CAM_FUNC_NOTAVAIL;
 				xpt_done(pccb);
 				break;
 			}
+#if __FreeBSD_version >= 500000
+			cam_calc_geometry(&pccb->ccg, 1);
+#else
+			{
+			struct ccb_calc_geometry *ccg;
+			u_int32_t size_mb;
+			u_int32_t secs_per_cylinder;
+
 			ccg= &pccb->ccg;
 			if (ccg->block_size == 0) {
 				pccb->ccb_h.status = CAM_REQ_INVALID;
@@ -2746,9 +2750,10 @@
 			secs_per_cylinder=ccg->heads * ccg->secs_per_track;
 			ccg->cylinders=ccg->volume_size / secs_per_cylinder;
 			pccb->ccb_h.status |= CAM_REQ_CMP;
+			}
+#endif
 			xpt_done(pccb);
 			break;
-		}
 	default:
 		pccb->ccb_h.status |= CAM_REQ_INVALID;
 		xpt_done(pccb);
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/ata/chipsets/ata-ati.c
--- a/head/sys/dev/ata/chipsets/ata-ati.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/ata/chipsets/ata-ati.c	Tue Dec 06 20:26:16 2011 +0200
@@ -25,7 +25,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/ata/chipsets/ata-ati.c 201993 2010-01-10 11:02:10Z mav $");
+__FBSDID("$FreeBSD: head/sys/dev/ata/chipsets/ata-ati.c 228200 2011-12-02 12:52:33Z mav $");
 
 #include "opt_ata.h"
 #include <sys/param.h>
@@ -53,6 +53,7 @@
 
 /* local prototypes */
 static int ata_ati_chipinit(device_t dev);
+static int ata_ati_dumb_ch_attach(device_t dev);
 static int ata_ati_ixp700_ch_attach(device_t dev);
 static int ata_ati_setmode(device_t dev, int target, int mode);
 
@@ -63,6 +64,8 @@
 #define SII_MEMIO       1
 #define SII_BUG         0x04
 
+static int force_ahci = 1;
+TUNABLE_INT("hw.ahci.force", &force_ahci);
 
 /*
  * ATI chipset support functions
@@ -111,7 +114,10 @@
 	ctlr->chipinit = ata_sii_chipinit;
 	break;
     case ATI_AHCI:
-	ctlr->chipinit = ata_ahci_chipinit;
+	if (force_ahci == 1 || pci_get_subclass(dev) != PCIS_STORAGE_IDE)
+		ctlr->chipinit = ata_ahci_chipinit;
+	else
+		ctlr->chipinit = ata_ati_chipinit;
 	break;
     }
     return (BUS_PROBE_DEFAULT);
@@ -127,6 +133,11 @@
     if (ata_setup_interrupt(dev, ata_generic_intr))
 	return ENXIO;
 
+    if (ctlr->chip->cfg1 == ATI_AHCI) {
+	ctlr->ch_attach = ata_ati_dumb_ch_attach;
+	ctlr->setmode = ata_sata_setmode;
+	return (0);
+    }
     switch (ctlr->chip->chipid) {
     case ATA_ATI_IXP600:
 	/* IXP600 only has 1 PATA channel */
@@ -165,6 +176,17 @@
 }
 
 static int
+ata_ati_dumb_ch_attach(device_t dev)
+{
+	struct ata_channel *ch = device_get_softc(dev);
+
+	if (ata_pci_ch_attach(dev))
+		return ENXIO;
+	ch->flags |= ATA_SATA;
+	return (0);
+}
+
+static int
 ata_ati_ixp700_ch_attach(device_t dev)
 {
 	struct ata_pci_controller *ctlr = device_get_softc(device_get_parent(dev));
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/ata/chipsets/ata-nvidia.c
--- a/head/sys/dev/ata/chipsets/ata-nvidia.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/ata/chipsets/ata-nvidia.c	Tue Dec 06 20:26:16 2011 +0200
@@ -25,7 +25,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/ata/chipsets/ata-nvidia.c 224603 2011-08-02 11:07:47Z mav $");
+__FBSDID("$FreeBSD: head/sys/dev/ata/chipsets/ata-nvidia.c 228200 2011-12-02 12:52:33Z mav $");
 
 #include "opt_ata.h"
 #include <sys/param.h>
@@ -65,6 +65,8 @@
 #define NVAHCI          0x04
 #define NVNOFORCE       0x08
 
+static int force_ahci = 1;
+TUNABLE_INT("hw.ahci.force", &force_ahci);
 
 /*
  * nVidia chipset support functions
@@ -181,7 +183,7 @@
 
     ata_set_desc(dev);
     if ((ctlr->chip->cfg1 & NVAHCI) &&
-	((ctlr->chip->cfg1 & NVNOFORCE) == 0 ||
+	((force_ahci == 1 && (ctlr->chip->cfg1 & NVNOFORCE) == 0) ||
 	 pci_get_subclass(dev) != PCIS_STORAGE_IDE))
 	ctlr->chipinit = ata_ahci_chipinit;
     else
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/dc/dcphy.c
--- a/head/sys/dev/dc/dcphy.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/dc/dcphy.c	Tue Dec 06 20:26:16 2011 +0200
@@ -31,7 +31,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/dc/dcphy.c 227686 2011-11-18 21:23:13Z marius $");
+__FBSDID("$FreeBSD: head/sys/dev/dc/dcphy.c 227908 2011-11-23 20:27:26Z marius $");
 
 /*
  * Pseudo-driver for internal NWAY support on DEC 21143 and workalike
@@ -95,7 +95,7 @@
 	DEVMETHOD(device_attach,	dcphy_attach),
 	DEVMETHOD(device_detach,	mii_phy_detach),
 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
-	{ 0, 0 }
+	DEVMETHOD_END
 };
 
 static devclass_t dcphy_devclass;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/dc/pnphy.c
--- a/head/sys/dev/dc/pnphy.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/dc/pnphy.c	Tue Dec 06 20:26:16 2011 +0200
@@ -31,7 +31,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/dc/pnphy.c 223624 2011-06-28 08:36:48Z kevlo $");
+__FBSDID("$FreeBSD: head/sys/dev/dc/pnphy.c 227908 2011-11-23 20:27:26Z marius $");
 
 /*
  * Pseudo-driver for media selection on the Lite-On PNIC 82c168
@@ -74,7 +74,7 @@
 	DEVMETHOD(device_attach,	pnphy_attach),
 	DEVMETHOD(device_detach,	mii_phy_detach),
 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
-	{ 0, 0 }
+	DEVMETHOD_END
 };
 
 static devclass_t pnphy_devclass;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/e1000/if_em.c
--- a/head/sys/dev/e1000/if_em.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/e1000/if_em.c	Tue Dec 06 20:26:16 2011 +0200
@@ -30,7 +30,7 @@
   POSSIBILITY OF SUCH DAMAGE.
 
 ******************************************************************************/
-/*$FreeBSD: head/sys/dev/e1000/if_em.c 227309 2011-11-07 15:43:11Z ed $*/
+/*$FreeBSD: head/sys/dev/e1000/if_em.c 228281 2011-12-05 15:33:13Z luigi $*/
 
 #ifdef HAVE_KERNEL_OPTION_HEADERS
 #include "opt_device_polling.h"
@@ -399,6 +399,10 @@
 /* Global used in WOL setup with multiport cards */
 static int global_quad_port_a = 0;
 
+#ifdef DEV_NETMAP	/* see ixgbe.c for details */
+#include <dev/netmap/if_em_netmap.h>
+#endif /* DEV_NETMAP */
+
 /*********************************************************************
  *  Device identification routine
  *
@@ -714,6 +718,9 @@
 
 	adapter->led_dev = led_create(em_led_func, adapter,
 	    device_get_nameunit(dev));
+#ifdef DEV_NETMAP
+	em_netmap_attach(adapter);
+#endif /* DEV_NETMAP */
 
 	INIT_DEBUGOUT("em_attach: end");
 
@@ -785,6 +792,10 @@
 	ether_ifdetach(adapter->ifp);
 	callout_drain(&adapter->timer);
 
+#ifdef DEV_NETMAP
+	netmap_detach(ifp);
+#endif /* DEV_NETMAP */
+
 	em_free_pci_resources(adapter);
 	bus_generic_detach(dev);
 	if_free(ifp);
@@ -3213,9 +3224,17 @@
 	struct adapter *adapter = txr->adapter;
 	struct em_buffer *txbuf;
 	int i;
+#ifdef DEV_NETMAP
+	struct netmap_adapter *na = NA(adapter->ifp);
+	struct netmap_slot *slot;
+#endif /* DEV_NETMAP */
 
 	/* Clear the old descriptor contents */
 	EM_TX_LOCK(txr);
+#ifdef DEV_NETMAP
+	slot = netmap_reset(na, NR_TX, txr->me, 0);
+#endif /* DEV_NETMAP */
+
 	bzero((void *)txr->tx_base,
 	      (sizeof(struct e1000_tx_desc)) * adapter->num_tx_desc);
 	/* Reset indices */
@@ -3232,6 +3251,22 @@
 			m_freem(txbuf->m_head);
 			txbuf->m_head = NULL;
 		}
+#ifdef DEV_NETMAP
+		if (slot) {
+			int si = i + na->tx_rings[txr->me].nkr_hwofs;
+			void *addr;
+
+			if (si >= na->num_tx_desc)
+				si -= na->num_tx_desc;
+			addr = NMB(slot + si);
+			txr->tx_base[i].buffer_addr =
+			    htole64(vtophys(addr));
+			/* reload the map for netmap mode */
+			netmap_load_map(txr->txtag,
+			    txbuf->map, addr, na->buff_size);
+		}
+#endif /* DEV_NETMAP */
+
 		/* clear the watch index */
 		txbuf->next_eop = -1;
         }
@@ -3682,6 +3717,19 @@
 	struct ifnet   *ifp = adapter->ifp;
 
 	EM_TX_LOCK_ASSERT(txr);
+#ifdef DEV_NETMAP
+	if (ifp->if_capenable & IFCAP_NETMAP) {
+		struct netmap_adapter *na = NA(ifp);
+
+		selwakeuppri(&na->tx_rings[txr->me].si, PI_NET);
+		EM_TX_UNLOCK(txr);
+		EM_CORE_LOCK(adapter);
+		selwakeuppri(&na->tx_rings[na->num_queues + 1].si, PI_NET);
+		EM_CORE_UNLOCK(adapter);
+		EM_TX_LOCK(txr);
+		return (FALSE);
+	}
+#endif /* DEV_NETMAP */
 
 	/* No work, make sure watchdog is off */
         if (txr->tx_avail == adapter->num_tx_desc) {
@@ -3978,6 +4026,57 @@
 		if (++j == adapter->num_rx_desc)
 			j = 0;
 	}
+#ifdef DEV_NETMAP
+    {
+	/*
+	 * This driver is slightly different from the standard:
+	 * it refills the rings in blocks of 8, so the while()
+	 * above completes any leftover work. Also, after if_init()
+	 * the ring starts at rxr->next_to_check instead of 0.
+	 *
+	 * Currently: we leave the mbufs allocated even in netmap
+	 * mode, and simply make the NIC ring point to the
+	 * correct buffer (netmap_buf or mbuf) depending on
+	 * the mode. To avoid mbuf leaks, when in netmap mode we
+	 * must make sure that next_to_refresh == next_to_check - 1
+	 * so that the above while() loop is never run on init.
+	 *
+	 * A better way would be to free the mbufs when entering
+	 * netmap mode, and set next_to_refresh/check in
+	 * a way that the mbufs are completely reallocated
+	 * when going back to standard mode.
+	 */
+	struct netmap_adapter *na = NA(adapter->ifp);
+	struct netmap_slot *slot = netmap_reset(na,
+		NR_RX, rxr->me, rxr->next_to_check);
+	int sj = slot ? na->rx_rings[rxr->me].nkr_hwofs : 0;
+
+	/* slot sj corresponds to entry j in the NIC ring */
+	if (sj < 0)
+		sj += adapter->num_rx_desc;
+
+	for (j = 0; j != adapter->num_rx_desc; j++, sj++) {
+		void *addr;
+		int sz;
+
+		rxbuf = &rxr->rx_buffers[j];
+		/* no mbuf and regular mode -> skip this entry */
+		if (rxbuf->m_head == NULL && !slot)
+			continue;
+		/* Handle wrap. Cannot use "na" here, could be NULL */
+		if (sj >= adapter->num_rx_desc)
+			sj -= adapter->num_rx_desc;
+		/* see comment, set slot addr and map */
+		addr = slot ? NMB(slot + sj) : rxbuf->m_head->m_data;
+		sz = slot ? na->buff_size : adapter->rx_mbuf_sz;
+		// XXX load or reload ?
+		netmap_load_map(rxr->rxtag, rxbuf->map, addr, sz);
+		/* Update descriptor */
+		rxr->rx_base[j].buffer_addr = htole64(vtophys(addr));
+		bus_dmamap_sync(rxr->rxtag, rxbuf->map, BUS_DMASYNC_PREREAD);
+	}
+    }
+#endif /* DEV_NETMAP */
 
 fail:
 	rxr->next_to_refresh = i;
@@ -4170,6 +4269,23 @@
 		E1000_WRITE_REG(hw, E1000_RDBAL(i), (u32)bus_addr);
 		/* Setup the Head and Tail Descriptor Pointers */
 		E1000_WRITE_REG(hw, E1000_RDH(i), rxr->next_to_check);
+#ifdef DEV_NETMAP
+		/*
+		 * an init() while a netmap client is active must
+		 * preserve the rx buffers passed to userspace.
+		 * In this driver it means we adjust RDT to
+		 * something different from next_to_refresh.
+		 */
+		if (ifp->if_capenable & IFCAP_NETMAP) {
+			struct netmap_adapter *na = NA(adapter->ifp);
+			struct netmap_kring *kring = &na->rx_rings[i];
+			int t = rxr->next_to_refresh - kring->nr_hwavail;
+
+			if (t < 0)
+				t += na->num_rx_desc;
+			E1000_WRITE_REG(hw, E1000_RDT(i), t);
+		} else
+#endif /* DEV_NETMAP */
 		E1000_WRITE_REG(hw, E1000_RDT(i), rxr->next_to_refresh);
 	}
 
@@ -4247,6 +4363,19 @@
 
 	EM_RX_LOCK(rxr);
 
+#ifdef DEV_NETMAP
+	if (ifp->if_capenable & IFCAP_NETMAP) {
+		struct netmap_adapter *na = NA(ifp);
+
+		selwakeuppri(&na->rx_rings[rxr->me].si, PI_NET);
+		EM_RX_UNLOCK(rxr);
+		EM_CORE_LOCK(adapter);
+		selwakeuppri(&na->rx_rings[na->num_queues + 1].si, PI_NET);
+		EM_CORE_UNLOCK(adapter);
+		return (0);
+	}
+#endif /* DEV_NETMAP */
+
 	for (i = rxr->next_to_check, processed = 0; count != 0;) {
 
 		if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0)
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/e1000/if_igb.c
--- a/head/sys/dev/e1000/if_igb.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/e1000/if_igb.c	Tue Dec 06 20:26:16 2011 +0200
@@ -30,7 +30,7 @@
   POSSIBILITY OF SUCH DAMAGE.
 
 ******************************************************************************/
-/*$FreeBSD: head/sys/dev/e1000/if_igb.c 227309 2011-11-07 15:43:11Z ed $*/
+/*$FreeBSD: head/sys/dev/e1000/if_igb.c 228281 2011-12-05 15:33:13Z luigi $*/
 
 
 #ifdef HAVE_KERNEL_OPTION_HEADERS
@@ -369,6 +369,9 @@
     &igb_rx_process_limit, 0,
     "Maximum number of received packets to process at a time, -1 means unlimited");
 
+#ifdef DEV_NETMAP	/* see ixgbe.c for details */
+#include <dev/netmap/if_igb_netmap.h>
+#endif /* DEV_NETMAP */
 /*********************************************************************
  *  Device identification routine
  *
@@ -664,6 +667,9 @@
 	adapter->led_dev = led_create(igb_led_func, adapter,
 	    device_get_nameunit(dev));
 
+#ifdef DEV_NETMAP
+	igb_netmap_attach(adapter);
+#endif /* DEV_NETMAP */
 	INIT_DEBUGOUT("igb_attach: end");
 
 	return (0);
@@ -742,6 +748,9 @@
 
 	callout_drain(&adapter->timer);
 
+#ifdef DEV_NETMAP
+	netmap_detach(adapter->ifp);
+#endif /* DEV_NETMAP */
 	igb_free_pci_resources(adapter);
 	bus_generic_detach(dev);
 	if_free(ifp);
@@ -3212,9 +3221,16 @@
 	struct adapter *adapter = txr->adapter;
 	struct igb_tx_buffer *txbuf;
 	int i;
+#ifdef DEV_NETMAP
+	struct netmap_adapter *na = NA(adapter->ifp);
+	struct netmap_slot *slot;
+#endif /* DEV_NETMAP */
 
 	/* Clear the old descriptor contents */
 	IGB_TX_LOCK(txr);
+#ifdef DEV_NETMAP
+	slot = netmap_reset(na, NR_TX, txr->me, 0);
+#endif /* DEV_NETMAP */
 	bzero((void *)txr->tx_base,
 	      (sizeof(union e1000_adv_tx_desc)) * adapter->num_tx_desc);
 	/* Reset indices */
@@ -3231,6 +3247,17 @@
 			m_freem(txbuf->m_head);
 			txbuf->m_head = NULL;
 		}
+#ifdef DEV_NETMAP
+		if (slot) {
+			/* slot si is mapped to the i-th NIC-ring entry */
+			int si = i + na->tx_rings[txr->me].nkr_hwofs;
+
+			if (si < 0)
+				si += na->num_tx_desc;
+			netmap_load_map(txr->txtag, txbuf->map,
+				NMB(slot + si), na->buff_size);
+		}
+#endif /* DEV_NETMAP */
 		/* clear the watch index */
 		txbuf->next_eop = -1;
         }
@@ -3626,6 +3653,19 @@
 
 	IGB_TX_LOCK_ASSERT(txr);
 
+#ifdef DEV_NETMAP
+	if (ifp->if_capenable & IFCAP_NETMAP) {
+		struct netmap_adapter *na = NA(ifp);
+
+		selwakeuppri(&na->tx_rings[txr->me].si, PI_NET);
+		IGB_TX_UNLOCK(txr);
+		IGB_CORE_LOCK(adapter);
+		selwakeuppri(&na->tx_rings[na->num_queues + 1].si, PI_NET);
+		IGB_CORE_UNLOCK(adapter);
+		IGB_TX_LOCK(txr);
+		return FALSE;
+	}
+#endif /* DEV_NETMAP */
         if (txr->tx_avail == adapter->num_tx_desc) {
 		txr->queue_status = IGB_QUEUE_IDLE;
                 return FALSE;
@@ -3949,6 +3989,10 @@
 	bus_dma_segment_t	pseg[1], hseg[1];
 	struct lro_ctrl		*lro = &rxr->lro;
 	int			rsize, nsegs, error = 0;
+#ifdef DEV_NETMAP
+	struct netmap_adapter *na = NA(rxr->adapter->ifp);
+	struct netmap_slot *slot;
+#endif /* DEV_NETMAP */
 
 	adapter = rxr->adapter;
 	dev = adapter->dev;
@@ -3956,6 +4000,9 @@
 
 	/* Clear the ring contents */
 	IGB_RX_LOCK(rxr);
+#ifdef DEV_NETMAP
+	slot = netmap_reset(na, NR_RX, rxr->me, 0);
+#endif /* DEV_NETMAP */
 	rsize = roundup2(adapter->num_rx_desc *
 	    sizeof(union e1000_adv_rx_desc), IGB_DBA_ALIGN);
 	bzero((void *)rxr->rx_base, rsize);
@@ -3974,6 +4021,22 @@
 		struct mbuf	*mh, *mp;
 
 		rxbuf = &rxr->rx_buffers[j];
+#ifdef DEV_NETMAP
+		if (slot) {
+			/* slot sj is mapped to the i-th NIC-ring entry */
+			int sj = j + na->rx_rings[rxr->me].nkr_hwofs;
+			void *addr;
+
+			if (sj < 0)
+				sj += na->num_rx_desc;
+			addr = NMB(slot + sj);
+			netmap_load_map(rxr->ptag,
+			    rxbuf->pmap, addr, na->buff_size);
+			/* Update descriptor */
+			rxr->rx_base[j].read.pkt_addr = htole64(vtophys(addr));
+			continue;
+		}
+#endif /* DEV_NETMAP */
 		if (rxr->hdr_split == FALSE)
 			goto skip_head;
 
@@ -4258,6 +4321,26 @@
 	for (int i = 0; i < adapter->num_queues; i++) {
 		rxr = &adapter->rx_rings[i];
 		E1000_WRITE_REG(hw, E1000_RDH(i), rxr->next_to_check);
+#ifdef DEV_NETMAP
+		/*
+		 * an init() while a netmap client is active must
+		 * preserve the rx buffers passed to userspace.
+		 * In this driver it means we adjust RDT to
+		 * somthing different from next_to_refresh
+		 * (which is not used in netmap mode).
+		 */
+		if (ifp->if_capenable & IFCAP_NETMAP) {
+			struct netmap_adapter *na = NA(adapter->ifp);
+			struct netmap_kring *kring = &na->rx_rings[i];
+			int t = rxr->next_to_refresh - kring->nr_hwavail;
+
+			if (t >= adapter->num_rx_desc)
+				t -= adapter->num_rx_desc;
+			else if (t < 0)
+				t += adapter->num_rx_desc;
+			E1000_WRITE_REG(hw, E1000_RDT(i), t);
+		} else
+#endif /* DEV_NETMAP */
 		E1000_WRITE_REG(hw, E1000_RDT(i), rxr->next_to_refresh);
 	}
 	return;
@@ -4436,6 +4519,19 @@
 	bus_dmamap_sync(rxr->rxdma.dma_tag, rxr->rxdma.dma_map,
 	    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
 
+#ifdef DEV_NETMAP
+	if (ifp->if_capenable & IFCAP_NETMAP) {
+		struct netmap_adapter *na = NA(ifp);
+
+		selwakeuppri(&na->rx_rings[rxr->me].si, PI_NET);
+		IGB_RX_UNLOCK(rxr);
+		IGB_CORE_LOCK(adapter);
+		selwakeuppri(&na->rx_rings[na->num_queues + 1].si, PI_NET);
+		IGB_CORE_UNLOCK(adapter);
+		return (0);
+	}
+#endif /* DEV_NETMAP */
+
 	/* Main clean loop */
 	for (i = rxr->next_to_check; count != 0;) {
 		struct mbuf		*sendmp, *mh, *mp;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/e1000/if_lem.c
--- a/head/sys/dev/e1000/if_lem.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/e1000/if_lem.c	Tue Dec 06 20:26:16 2011 +0200
@@ -30,7 +30,7 @@
   POSSIBILITY OF SUCH DAMAGE.
 
 ******************************************************************************/
-/*$FreeBSD: head/sys/dev/e1000/if_lem.c 225640 2011-09-17 13:48:09Z rstone $*/
+/*$FreeBSD: head/sys/dev/e1000/if_lem.c 228281 2011-12-05 15:33:13Z luigi $*/
 
 #ifdef HAVE_KERNEL_OPTION_HEADERS
 #include "opt_device_polling.h"
@@ -316,6 +316,10 @@
 /* Global used in WOL setup with multiport cards */
 static int global_quad_port_a = 0;
 
+#ifdef DEV_NETMAP	/* see ixgbe.c for details */
+#include <dev/netmap/if_lem_netmap.h>
+#endif /* DEV_NETMAP */
+
 /*********************************************************************
  *  Device identification routine
  *
@@ -646,6 +650,9 @@
 	adapter->led_dev = led_create(lem_led_func, adapter,
 	    device_get_nameunit(dev));
 
+#ifdef DEV_NETMAP
+	lem_netmap_attach(adapter);
+#endif /* DEV_NETMAP */
 	INIT_DEBUGOUT("lem_attach: end");
 
 	return (0);
@@ -724,6 +731,9 @@
 	callout_drain(&adapter->timer);
 	callout_drain(&adapter->tx_fifo_timer);
 
+#ifdef DEV_NETMAP
+	netmap_detach(ifp);
+#endif /* DEV_NETMAP */
 	lem_free_pci_resources(adapter);
 	bus_generic_detach(dev);
 	if_free(ifp);
@@ -2637,6 +2647,11 @@
 lem_setup_transmit_structures(struct adapter *adapter)
 {
 	struct em_buffer *tx_buffer;
+#ifdef DEV_NETMAP
+	/* we are already locked */
+	struct netmap_adapter *na = NA(adapter->ifp);
+	struct netmap_slot *slot = netmap_reset(na, NR_TX, 0, 0);
+#endif /* DEV_NETMAP */
 
 	/* Clear the old ring contents */
 	bzero(adapter->tx_desc_base,
@@ -2650,6 +2665,22 @@
 		bus_dmamap_unload(adapter->txtag, tx_buffer->map);
 		m_freem(tx_buffer->m_head);
 		tx_buffer->m_head = NULL;
+#ifdef DEV_NETMAP
+		if (slot) {
+			/* slot si is mapped to the i-th NIC-ring entry */
+			int si = i + na->tx_rings[0].nkr_hwofs;
+			void *addr;
+
+			if (si > na->num_tx_desc)
+				si -= na->num_tx_desc;
+			addr = NMB(slot + si);
+			adapter->tx_desc_base[si].buffer_addr =
+			    htole64(vtophys(addr));
+			/* reload the map for netmap mode */
+			netmap_load_map(adapter->txtag,
+			    tx_buffer->map, addr, na->buff_size);
+		}
+#endif /* DEV_NETMAP */
 		tx_buffer->next_eop = -1;
 	}
 
@@ -2951,6 +2982,12 @@
 
 	EM_TX_LOCK_ASSERT(adapter);
 
+#ifdef DEV_NETMAP
+	if (ifp->if_capenable & IFCAP_NETMAP) {
+		selwakeuppri(&NA(ifp)->tx_rings[0].si, PI_NET);
+		return;
+	}
+#endif /* DEV_NETMAP */
         if (adapter->num_tx_desc_avail == adapter->num_tx_desc)
                 return;
 
@@ -3181,6 +3218,11 @@
 {
 	struct em_buffer *rx_buffer;
 	int i, error;
+#ifdef DEV_NETMAP
+	/* we are already under lock */
+	struct netmap_adapter *na = NA(adapter->ifp);
+	struct netmap_slot *slot = netmap_reset(na, NR_RX, 0, 0);
+#endif
 
 	/* Reset descriptor ring */
 	bzero(adapter->rx_desc_base,
@@ -3200,6 +3242,23 @@
 
 	/* Allocate new ones. */
 	for (i = 0; i < adapter->num_rx_desc; i++) {
+#ifdef DEV_NETMAP
+		if (slot) {
+			/* slot si is mapped to the i-th NIC-ring entry */
+			int si = i + na->rx_rings[0].nkr_hwofs;
+			void *addr;
+
+			if (si > na->num_rx_desc)
+				si -= na->num_rx_desc;
+			addr = NMB(slot + si);
+			netmap_load_map(adapter->rxtag,
+			    rx_buffer->map, addr, na->buff_size);
+			/* Update descriptor */
+			adapter->rx_desc_base[i].buffer_addr =
+			    htole64(vtophys(addr));
+			continue;
+		}
+#endif /* DEV_NETMAP */
 		error = lem_get_buf(adapter, i);
 		if (error)
                         return (error);
@@ -3324,6 +3383,18 @@
 	 * Tail Descriptor Pointers
 	 */
 	E1000_WRITE_REG(&adapter->hw, E1000_RDH(0), 0);
+#ifdef DEV_NETMAP
+	/* preserve buffers already made available to clients */
+	if (ifp->if_capenable & IFCAP_NETMAP) {
+		struct netmap_adapter *na = NA(adapter->ifp);
+		struct netmap_kring *kring = &na->rx_rings[0];
+		int t = na->num_rx_desc - 1 - kring->nr_hwavail;
+
+		if (t >= na->num_rx_desc)
+			t -= na->num_rx_desc;
+		E1000_WRITE_REG(&adapter->hw, E1000_RDT(0), t);
+	} else
+#endif /* DEV_NETMAP */
 	E1000_WRITE_REG(&adapter->hw, E1000_RDT(0), adapter->num_rx_desc - 1);
 
 	return;
@@ -3407,6 +3478,14 @@
 	bus_dmamap_sync(adapter->rxdma.dma_tag, adapter->rxdma.dma_map,
 	    BUS_DMASYNC_POSTREAD);
 
+#ifdef DEV_NETMAP
+	if (ifp->if_capenable & IFCAP_NETMAP) {
+		selwakeuppri(&NA(ifp)->rx_rings[0].si, PI_NET);
+		EM_RX_UNLOCK(adapter);
+		return (0);
+	}
+#endif /* DEV_NETMAP */
+
 	if (!((current_desc->status) & E1000_RXD_STAT_DD)) {
 		if (done != NULL)
 			*done = rx_sent;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/ed/if_ed.c
--- a/head/sys/dev/ed/if_ed.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/ed/if_ed.c	Tue Dec 06 20:26:16 2011 +0200
@@ -26,7 +26,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/sys/dev/ed/if_ed.c 228286 2011-12-05 18:10:43Z yongari $");
 
 /*
  * Device driver for National Semiconductor DS8390/WD83C690 based ethernet
@@ -1709,12 +1709,19 @@
 			break;
 		}
 	}
-	for (len = 0; m != 0; m = m->m_next) {
-		if (sc->isa16bit)
-			bus_space_write_region_2(sc->mem_bst,
-			    sc->mem_bsh, dst,
-			    mtod(m, uint16_t *), (m->m_len + 1)/ 2);
-		else
+	for (len = 0; m != NULL; m = m->m_next) {
+		if (m->m_len == 0)
+			continue;
+		if (sc->isa16bit) {
+			if (m->m_len > 1)
+				bus_space_write_region_2(sc->mem_bst,
+				    sc->mem_bsh, dst,
+				    mtod(m, uint16_t *), m->m_len / 2);
+			if ((m->m_len & 1) != 0)
+				bus_space_write_1(sc->mem_bst, sc->mem_bsh,
+				    dst + m->m_len - 1,
+				    *(mtod(m, uint8_t *) + m->m_len - 1));
+		} else
 			bus_space_write_region_1(sc->mem_bst,
 			    sc->mem_bsh, dst,
 			    mtod(m, uint8_t *), m->m_len);
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/et/if_et.c
--- a/head/sys/dev/et/if_et.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/et/if_et.c	Tue Dec 06 20:26:16 2011 +0200
@@ -35,7 +35,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/et/if_et.c 227843 2011-11-22 21:28:20Z marius $");
+__FBSDID("$FreeBSD: head/sys/dev/et/if_et.c 228298 2011-12-06 00:58:42Z yongari $");
 
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -87,6 +87,8 @@
 static int	et_attach(device_t);
 static int	et_detach(device_t);
 static int	et_shutdown(device_t);
+static int	et_suspend(device_t);
+static int	et_resume(device_t);
 
 static int	et_miibus_readreg(device_t, int, int);
 static int	et_miibus_writereg(device_t, int, int, int);
@@ -169,6 +171,8 @@
 	DEVMETHOD(device_attach,	et_attach),
 	DEVMETHOD(device_detach,	et_detach),
 	DEVMETHOD(device_shutdown,	et_shutdown),
+	DEVMETHOD(device_suspend,	et_suspend),
+	DEVMETHOD(device_resume,	et_resume),
 
 	DEVMETHOD(miibus_readreg,	et_miibus_readreg),
 	DEVMETHOD(miibus_writereg,	et_miibus_writereg),
@@ -222,7 +226,7 @@
 	for (d = et_devices; d->desc != NULL; ++d) {
 		if (vid == d->vid && did == d->did) {
 			device_set_desc(dev, d->desc);
-			return (0);
+			return (BUS_PROBE_DEFAULT);
 		}
 	}
 	return (ENXIO);
@@ -240,6 +244,7 @@
 	sc->dev = dev;
 	mtx_init(&sc->sc_mtx, device_get_nameunit(dev), MTX_NETWORK_LOCK,
 	    MTX_DEF);
+	callout_init_mtx(&sc->sc_tick, &sc->sc_mtx, 0);
 
 	ifp = sc->ifp = if_alloc(IFT_ETHER);
 	if (ifp == NULL) {
@@ -331,10 +336,10 @@
 	ifp->if_init = et_init;
 	ifp->if_ioctl = et_ioctl;
 	ifp->if_start = et_start;
-	ifp->if_mtu = ETHERMTU;
 	ifp->if_capabilities = IFCAP_TXCSUM | IFCAP_VLAN_MTU;
 	ifp->if_capenable = ifp->if_capabilities;
-	IFQ_SET_MAXLEN(&ifp->if_snd, ET_TX_NDESC);
+	ifp->if_snd.ifq_drv_maxlen = ET_TX_NDESC - 1;
+	IFQ_SET_MAXLEN(&ifp->if_snd, ET_TX_NDESC - 1);
 	IFQ_SET_READY(&ifp->if_snd);
 
 	et_chip_attach(sc);
@@ -347,7 +352,9 @@
 	}
 
 	ether_ifattach(ifp, eaddr);
-	callout_init_mtx(&sc->sc_tick, &sc->sc_mtx, 0);
+
+	/* Tell the upper layer(s) we support long frames. */
+	ifp->if_hdrlen = sizeof(struct ether_vlan_header);
 
 	error = bus_setup_intr(dev, sc->sc_irq_res, INTR_TYPE_NET | INTR_MPSAFE,
 	    NULL, et_intr, sc, &sc->sc_irq_handle);
@@ -371,31 +378,27 @@
 	struct et_softc *sc = device_get_softc(dev);
 
 	if (device_is_attached(dev)) {
-		struct ifnet *ifp = sc->ifp;
-
+		ether_ifdetach(sc->ifp);
 		ET_LOCK(sc);
 		et_stop(sc);
-		bus_teardown_intr(dev, sc->sc_irq_res, sc->sc_irq_handle);
 		ET_UNLOCK(sc);
-
-		ether_ifdetach(ifp);
+		callout_drain(&sc->sc_tick);
 	}
 
 	if (sc->sc_miibus != NULL)
 		device_delete_child(dev, sc->sc_miibus);
 	bus_generic_detach(dev);
 
-	if (sc->sc_irq_res != NULL) {
-		bus_release_resource(dev, SYS_RES_IRQ, sc->sc_irq_rid,
-				     sc->sc_irq_res);
-	}
+	if (sc->sc_irq_handle != NULL)
+		bus_teardown_intr(dev, sc->sc_irq_res, sc->sc_irq_handle);
+	if (sc->sc_irq_res != NULL)
+		bus_release_resource(dev, SYS_RES_IRQ,
+		    rman_get_rid(sc->sc_irq_res), sc->sc_irq_res);
 	if ((sc->sc_flags & ET_FLAG_MSI) != 0)
 		pci_release_msi(dev);
-
-	if (sc->sc_mem_res != NULL) {
-		bus_release_resource(dev, SYS_RES_MEMORY, sc->sc_mem_rid,
-				     sc->sc_mem_res);
-	}
+	if (sc->sc_mem_res != NULL)
+		bus_release_resource(dev, SYS_RES_MEMORY,
+		    rman_get_rid(sc->sc_mem_res), sc->sc_mem_res);
 
 	if (sc->ifp != NULL)
 		if_free(sc->ifp);
@@ -1253,12 +1256,13 @@
 static void
 et_start_locked(struct ifnet *ifp)
 {
-	struct et_softc *sc = ifp->if_softc;
+	struct et_softc *sc;
+	struct mbuf *m_head = NULL;
 	struct et_txbuf_data *tbd;
-	int trans;
+	int enq;
 
+	sc = ifp->if_softc;
 	ET_LOCK_ASSERT(sc);
-	tbd = &sc->sc_tx_data;
 
 	if ((sc->sc_flags & ET_FLAG_TXRX_ENABLED) == 0)
 		return;
@@ -1266,30 +1270,32 @@
 	if ((ifp->if_drv_flags & (IFF_DRV_RUNNING | IFF_DRV_OACTIVE)) != IFF_DRV_RUNNING)
 		return;
 
-	trans = 0;
-	for (;;) {
-		struct mbuf *m;
-
-		if ((tbd->tbd_used + ET_NSEG_SPARE) > ET_TX_NDESC) {
+	tbd = &sc->sc_tx_data;
+	for (enq = 0; !IFQ_DRV_IS_EMPTY(&ifp->if_snd); ) {
+		if (tbd->tbd_used + ET_NSEG_SPARE >= ET_TX_NDESC) {
 			ifp->if_drv_flags |= IFF_DRV_OACTIVE;
 			break;
 		}
 
-		IFQ_DEQUEUE(&ifp->if_snd, m);
-		if (m == NULL)
+		IFQ_DRV_DEQUEUE(&ifp->if_snd, m_head);
+		if (m_head == NULL)
 			break;
 
-		if (et_encap(sc, &m)) {
-			ifp->if_oerrors++;
-			ifp->if_drv_flags |= IFF_DRV_OACTIVE;
+		if (et_encap(sc, &m_head)) {
+			if (m_head == NULL) {
+				ifp->if_oerrors++;
+				break;
+			}
+			IFQ_DRV_PREPEND(&ifp->if_snd, m_head);
+			if (tbd->tbd_used > 0)
+				ifp->if_drv_flags |= IFF_DRV_OACTIVE;
 			break;
 		}
-		trans = 1;
-
-		BPF_MTAP(ifp, m);
+		enq++;
+		ETHER_BPF_MTAP(ifp, m_head);
 	}
 
-	if (trans)
+	if (enq > 0)
 		sc->watchdog_timer = 5;
 }
 
@@ -2451,3 +2457,29 @@
 	bus_dmamap_sync(rx_ring->rr_dtag, rx_ring->rr_dmap,
 			BUS_DMASYNC_PREWRITE);
 }
+
+static int
+et_suspend(device_t dev)
+{
+	struct et_softc *sc;
+
+	sc = device_get_softc(dev);
+	ET_LOCK(sc);
+	if ((sc->ifp->if_drv_flags & IFF_DRV_RUNNING) != 0)
+		et_stop(sc);
+	ET_UNLOCK(sc);
+	return (0);
+}
+
+static int
+et_resume(device_t dev)
+{
+	struct et_softc *sc;
+
+	sc = device_get_softc(dev);
+	ET_LOCK(sc);
+	if ((sc->ifp->if_flags & IFF_UP) != 0)
+		et_init_locked(sc);
+	ET_UNLOCK(sc);
+	return (0);
+}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/et/if_etreg.h
--- a/head/sys/dev/et/if_etreg.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/et/if_etreg.h	Tue Dec 06 20:26:16 2011 +0200
@@ -32,42 +32,7 @@
  * SUCH DAMAGE.
  *
  * $DragonFly: src/sys/dev/netif/et/if_etreg.h,v 1.3 2007/10/23 14:28:42 sephe Exp $
- * $FreeBSD$
- */
-/*-
- * Portions of this code is derived from NetBSD which is covered by
- * the following license:
- *
- * Copyright (c) 2004, 2005 David Young.  All rights reserved.
- *
- * Programmed for NetBSD by David Young.
- *
- * 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 David Young may not be used to endorse or promote
- *    products derived from this software without specific prior
- *    written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY David Young ``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 David
- * Young 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.
- *
- * $DragonFly: src/sys/sys/bitops.h,v 1.1 2007/10/14 04:15:17 sephe Exp $
+ * $FreeBSD: head/sys/dev/et/if_etreg.h 228291 2011-12-05 22:09:07Z yongari $
  */
 
 #ifndef _IF_ETREG_H
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/fdt/fdt_common.c
--- a/head/sys/dev/fdt/fdt_common.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/fdt/fdt_common.c	Tue Dec 06 20:26:16 2011 +0200
@@ -28,7 +28,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/sys/dev/fdt/fdt_common.c 228201 2011-12-02 15:24:39Z jchandra $");
 
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -74,13 +74,13 @@
 	/*
 	 * Try to access the SOC node directly i.e. through /aliases/.
 	 */
-	if ((node = OF_finddevice("soc")) != 0)
+	if ((node = OF_finddevice("soc")) != -1)
 		if (fdt_is_compatible_strict(node, "simple-bus"))
 			goto moveon;
 	/*
 	 * Find the node the long way.
 	 */
-	if ((node = OF_finddevice("/")) == 0)
+	if ((node = OF_finddevice("/")) == -1)
 		return (ENXIO);
 
 	if ((node = fdt_find_compatible(node, "simple-bus", 1)) == 0)
@@ -576,7 +576,7 @@
 
 	max_size = sizeof(reg);
 	memory = OF_finddevice("/memory");
-	if (memory <= 0) {
+	if (memory == -1) {
 		rv = ENXIO;
 		goto out;
 	}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/fdt/fdt_powerpc.c
--- a/head/sys/dev/fdt/fdt_powerpc.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/fdt/fdt_powerpc.c	Tue Dec 06 20:26:16 2011 +0200
@@ -28,7 +28,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/sys/dev/fdt/fdt_powerpc.c 228201 2011-12-02 15:24:39Z jchandra $");
 
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -62,7 +62,7 @@
 	 * This fixup uses /cpus/ bus-frequency prop value to set simple-bus
 	 * bus-frequency property.
 	 */
-	if ((cpus = OF_finddevice("/cpus")) == 0)
+	if ((cpus = OF_finddevice("/cpus")) == -1)
 		return;
 
 	if ((child = OF_child(cpus)) == 0)
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/fdt/fdtbus.c
--- a/head/sys/dev/fdt/fdtbus.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/fdt/fdtbus.c	Tue Dec 06 20:26:16 2011 +0200
@@ -28,7 +28,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/fdt/fdtbus.c 226496 2011-10-18 07:29:21Z jchandra $");
+__FBSDID("$FreeBSD: head/sys/dev/fdt/fdtbus.c 228201 2011-12-02 15:24:39Z jchandra $");
 
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -177,7 +177,7 @@
 	u_long start, end;
 	int error;
 
-	if ((root = OF_peer(0)) == 0)
+	if ((root = OF_finddevice("/")) == -1)
 		panic("fdtbus_attach: no root node.");
 
 	sc = device_get_softc(dev);
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/gpio/gpioiic.c
--- a/head/sys/dev/gpio/gpioiic.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/gpio/gpioiic.c	Tue Dec 06 20:26:16 2011 +0200
@@ -26,7 +26,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/sys/dev/gpio/gpioiic.c 228258 2011-12-04 12:10:24Z adrian $");
 
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -48,8 +48,8 @@
 
 #include "iicbb_if.h"
 
-#define	SCL_PIN		0	/* gpiobus mapped pin 6 */
-#define	SDA_PIN		1	/* gpiobus mapped pin 7 */
+#define	SCL_PIN_DEFAULT	0	/* default index of SCL pin on gpiobus */
+#define	SDA_PIN_DEFAULT	1
 
 struct gpioiic_softc 
 {
@@ -57,6 +57,8 @@
 	device_t	sc_busdev;
 	struct mtx	sc_mtx;
 	struct cdev	*sc_leddev;
+	int		scl_pin;
+	int		sda_pin;
 };
 
 static int gpioiic_probe(device_t);
@@ -88,6 +90,12 @@
 
 	sc->sc_dev = dev;
 	sc->sc_busdev = device_get_parent(dev);
+	if (resource_int_value(device_get_name(dev),
+		device_get_unit(dev), "scl", &sc->scl_pin))
+		sc->scl_pin = SCL_PIN_DEFAULT;
+	if (resource_int_value(device_get_name(dev),
+		device_get_unit(dev), "sda", &sc->sda_pin))
+		sc->sda_pin = SDA_PIN_DEFAULT;
 
 	/* add generic bit-banging code */
 	bitbang = device_add_child(dev, "iicbb", -1);
@@ -105,9 +113,9 @@
 {
 	struct gpioiic_softc		*sc = device_get_softc(dev);
 
-	GPIOBUS_PIN_SETFLAGS(sc->sc_busdev, sc->sc_dev, SDA_PIN,
+	GPIOBUS_PIN_SETFLAGS(sc->sc_busdev, sc->sc_dev, sc->sda_pin,
 	    GPIO_PIN_INPUT);
-	GPIOBUS_PIN_SETFLAGS(sc->sc_busdev, sc->sc_dev, SCL_PIN,
+	GPIOBUS_PIN_SETFLAGS(sc->sc_busdev, sc->sc_dev, sc->scl_pin,
 	    GPIO_PIN_INPUT);
 }
 
@@ -142,15 +150,14 @@
 
 	GPIOBUS_LOCK_BUS(sc->sc_busdev);
 	if (val == 0) {
-		GPIOBUS_PIN_SETFLAGS(sc->sc_busdev, sc->sc_dev, SDA_PIN,
+		GPIOBUS_PIN_SET(sc->sc_busdev, sc->sc_dev, sc->sda_pin, 0);
+		GPIOBUS_PIN_SETFLAGS(sc->sc_busdev, sc->sc_dev, sc->sda_pin,
 		    GPIO_PIN_OUTPUT);
-		GPIOBUS_PIN_SET(sc->sc_busdev, sc->sc_dev, SDA_PIN, 0);
 	} else {
-		GPIOBUS_PIN_SETFLAGS(sc->sc_busdev, sc->sc_dev, SDA_PIN,
+		GPIOBUS_PIN_SETFLAGS(sc->sc_busdev, sc->sc_dev, sc->sda_pin,
 		    GPIO_PIN_INPUT);
 	}
 	GPIOBUS_UNLOCK_BUS(sc->sc_busdev);
-	DELAY(10);
 }
 
 static void
@@ -160,15 +167,14 @@
 
 	GPIOBUS_LOCK_BUS(sc->sc_busdev);
 	if (val == 0) {
-		GPIOBUS_PIN_SETFLAGS(sc->sc_busdev, sc->sc_dev, SCL_PIN,
+		GPIOBUS_PIN_SET(sc->sc_busdev, sc->sc_dev, sc->scl_pin, 0);
+		GPIOBUS_PIN_SETFLAGS(sc->sc_busdev, sc->sc_dev, sc->scl_pin,
 		    GPIO_PIN_OUTPUT);
-		GPIOBUS_PIN_SET(sc->sc_busdev, sc->sc_dev, SCL_PIN, 0);
 	} else {
-		GPIOBUS_PIN_SETFLAGS(sc->sc_busdev, sc->sc_dev, SCL_PIN,
+		GPIOBUS_PIN_SETFLAGS(sc->sc_busdev, sc->sc_dev, sc->scl_pin,
 		    GPIO_PIN_INPUT);
 	}
 	GPIOBUS_UNLOCK_BUS(sc->sc_busdev);
-	DELAY(10);
 }
 
 static int
@@ -178,9 +184,9 @@
 	unsigned int			val;
 
 	GPIOBUS_LOCK_BUS(sc->sc_busdev);
-	GPIOBUS_PIN_SETFLAGS(sc->sc_busdev, sc->sc_dev, SCL_PIN,
+	GPIOBUS_PIN_SETFLAGS(sc->sc_busdev, sc->sc_dev, sc->scl_pin,
 	    GPIO_PIN_INPUT);
-	GPIOBUS_PIN_GET(sc->sc_busdev, sc->sc_dev, SCL_PIN, &val);
+	GPIOBUS_PIN_GET(sc->sc_busdev, sc->sc_dev, sc->scl_pin, &val);
 	GPIOBUS_UNLOCK_BUS(sc->sc_busdev);
 
 	return ((int)val);
@@ -193,9 +199,9 @@
 	unsigned int			val;
 
 	GPIOBUS_LOCK_BUS(sc->sc_busdev);
-	GPIOBUS_PIN_SETFLAGS(sc->sc_busdev, sc->sc_dev, SDA_PIN,
+	GPIOBUS_PIN_SETFLAGS(sc->sc_busdev, sc->sc_dev, sc->sda_pin,
 	    GPIO_PIN_INPUT);
-	GPIOBUS_PIN_GET(sc->sc_busdev, sc->sc_dev, SDA_PIN, &val);
+	GPIOBUS_PIN_GET(sc->sc_busdev, sc->sc_dev, sc->sda_pin, &val);
 	GPIOBUS_UNLOCK_BUS(sc->sc_busdev);
 
 	return ((int)val);
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/hptiop/hptiop.c
--- a/head/sys/dev/hptiop/hptiop.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/hptiop/hptiop.c	Tue Dec 06 20:26:16 2011 +0200
@@ -25,7 +25,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/hptiop/hptiop.c 226350 2011-10-13 20:06:19Z marius $");
+__FBSDID("$FreeBSD: head/sys/dev/hptiop/hptiop.c 227912 2011-11-23 21:43:51Z marius $");
 
 #include <sys/param.h>
 #include <sys/types.h>
@@ -1813,11 +1813,15 @@
 		break;
 
 	case XPT_CALC_GEOMETRY:
+#if __FreeBSD_version >= 500000
+		cam_calc_geometry(&ccb->ccg, 1);
+#else
 		ccb->ccg.heads = 255;
 		ccb->ccg.secs_per_track = 63;
 		ccb->ccg.cylinders = ccb->ccg.volume_size /
 				(ccb->ccg.heads * ccb->ccg.secs_per_track);
 		ccb->ccb_h.status = CAM_REQ_CMP;
+#endif
 		break;
 
 	case XPT_PATH_INQ:
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/hptmv/entry.c
--- a/head/sys/dev/hptmv/entry.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/hptmv/entry.c	Tue Dec 06 20:26:16 2011 +0200
@@ -22,9 +22,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.
- *
- * $FreeBSD$
  */
+
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD: head/sys/dev/hptmv/entry.c 227912 2011-11-23 21:43:51Z marius $");
  
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -94,7 +95,7 @@
 	DEVMETHOD(device_detach,	hpt_detach),
 
 	DEVMETHOD(device_shutdown,	hpt_shutdown),
-	{ 0, 0 }
+	DEVMETHOD_END
 };
 
 static driver_t hpt_pci_driver = {
@@ -2371,7 +2372,10 @@
 			break;
 
 		case XPT_CALC_GEOMETRY:
-		{
+#if __FreeBSD_version >= 500000
+			cam_calc_geometry(&ccb->ccg, 1);
+#else
+			{
 			struct	  ccb_calc_geometry *ccg;
 			u_int32_t size_mb;
 			u_int32_t secs_per_cylinder;
@@ -2389,9 +2393,10 @@
 			secs_per_cylinder = ccg->heads * ccg->secs_per_track;
 			ccg->cylinders = ccg->volume_size / secs_per_cylinder;
 			ccb->ccb_h.status = CAM_REQ_CMP;
+			}
+#endif
 			xpt_done(ccb);
 			break;
-		}
 
 		case XPT_PATH_INQ:		/* Path routing inquiry */
 		{
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/hptrr/hptrr_osm_bsd.c
--- a/head/sys/dev/hptrr/hptrr_osm_bsd.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/hptrr/hptrr_osm_bsd.c	Tue Dec 06 20:26:16 2011 +0200
@@ -22,9 +22,11 @@
  * 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 <sys/cdefs.h>
+__FBSDID("$FreeBSD: head/sys/dev/hptrr/hptrr_osm_bsd.c 227912 2011-11-23 21:43:51Z marius $");
+
 #include <dev/hptrr/hptrr_config.h>
 /* $Id: osm_bsd.c,v 1.27 2007/11/22 07:35:49 gmm Exp $
  *
@@ -795,10 +797,14 @@
 		break;
 
 	case XPT_CALC_GEOMETRY:
+#if __FreeBSD_version >= 500000
+		cam_calc_geometry(&ccb->ccg, 1);
+#else
 		ccb->ccg.heads = 255;
 		ccb->ccg.secs_per_track = 63;
 		ccb->ccg.cylinders = ccb->ccg.volume_size / (ccb->ccg.heads * ccb->ccg.secs_per_track);
 		ccb->ccb_h.status = CAM_REQ_CMP;
+#endif
 		break;
 
 	case XPT_PATH_INQ:
@@ -1250,7 +1256,7 @@
 	DEVMETHOD(device_attach,	hpt_attach),
 	DEVMETHOD(device_detach,	hpt_detach),
 	DEVMETHOD(device_shutdown,	hpt_shutdown),
-	{ 0, 0 }
+	DEVMETHOD_END
 };
 
 static driver_t hpt_pci_driver = {
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/hwpmc/hwpmc_core.c
--- a/head/sys/dev/hwpmc/hwpmc_core.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/hwpmc/hwpmc_core.c	Tue Dec 06 20:26:16 2011 +0200
@@ -29,7 +29,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/sys/dev/hwpmc/hwpmc_core.c 228198 2011-12-02 10:02:49Z fabient $");
 
 #include <sys/param.h>
 #include <sys/bus.h>
@@ -1479,6 +1479,10 @@
 		/*
 		 * Events valid only on counter 0.
 		 */
+	case PMC_EV_IAP_EVENT_60H_01H:
+	case PMC_EV_IAP_EVENT_60H_02H:
+	case PMC_EV_IAP_EVENT_60H_04H:
+	case PMC_EV_IAP_EVENT_60H_08H:	
 	case PMC_EV_IAP_EVENT_B3H_01H:
 	case PMC_EV_IAP_EVENT_B3H_02H:
 	case PMC_EV_IAP_EVENT_B3H_04H:
@@ -1488,6 +1492,10 @@
 		/*
 		 * Events valid only on counter 0, 1.
 		 */
+	case PMC_EV_IAP_EVENT_4CH_01H:
+	case PMC_EV_IAP_EVENT_4EH_01H:
+	case PMC_EV_IAP_EVENT_4EH_02H:
+	case PMC_EV_IAP_EVENT_4EH_04H:
 	case PMC_EV_IAP_EVENT_51H_01H:
 	case PMC_EV_IAP_EVENT_51H_02H:
 	case PMC_EV_IAP_EVENT_51H_04H:
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/iicbus/iicbus.c
--- a/head/sys/dev/iicbus/iicbus.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/iicbus/iicbus.c	Tue Dec 06 20:26:16 2011 +0200
@@ -25,7 +25,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/iicbus/iicbus.c 227843 2011-11-22 21:28:20Z marius $");
+__FBSDID("$FreeBSD: head/sys/dev/iicbus/iicbus.c 228257 2011-12-04 11:55:33Z adrian $");
 
 /*
  * Autoconfiguration and support routines for the Philips serial I2C bus
@@ -92,10 +92,16 @@
 	unsigned char addr;
 #endif
 	struct iicbus_softc *sc = IICBUS_SOFTC(dev);
+	int strict;
 
 	sc->dev = dev;
 	mtx_init(&sc->lock, "iicbus", NULL, MTX_DEF);
 	iicbus_reset(dev, IIC_FASTEST, 0, NULL);
+	if (resource_int_value(device_get_name(dev),
+		device_get_unit(dev), "strict", &strict) == 0)
+		sc->strict = strict;
+	else
+		sc->strict = 1;
 
 	/* device probing is meaningless since the bus is supposed to be
 	 * hot-plug. Moreover, some I2C chips do not appreciate random
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/iicbus/iicbus.h
--- a/head/sys/dev/iicbus/iicbus.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/iicbus/iicbus.h	Tue Dec 06 20:26:16 2011 +0200
@@ -23,7 +23,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD$
+ * $FreeBSD: head/sys/dev/iicbus/iicbus.h 228257 2011-12-04 11:55:33Z adrian $
  *
  */
 #ifndef __IICBUS_H
@@ -41,6 +41,8 @@
 	device_t owner;		/* iicbus owner device structure */
 	u_char started;		/* address of the 'started' slave
 				 * 0 if no start condition succeeded */
+	u_char strict;		/* deny operations that violate the
+				 * I2C protocol */
 	struct mtx lock;
 };
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/iicbus/iiconf.c
--- a/head/sys/dev/iicbus/iiconf.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/iicbus/iiconf.c	Tue Dec 06 20:26:16 2011 +0200
@@ -25,7 +25,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/sys/dev/iicbus/iiconf.c 228257 2011-12-04 11:55:33Z adrian $");
 
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -243,8 +243,8 @@
 {
 	struct iicbus_softc *sc = (struct iicbus_softc *)device_get_softc(bus);
 	
-	/* a slave must have been started with the appropriate address */
-	if (!sc->started || (sc->started & LSB))
+	/* a slave must have been started for writing */
+	if (sc->started == 0 || (sc->strict != 0 && (sc->started & LSB) != 0))
 		return (EINVAL);
 
 	return (IICBUS_WRITE(device_get_parent(bus), buf, len, sent, timeout));
@@ -261,8 +261,8 @@
 {
 	struct iicbus_softc *sc = (struct iicbus_softc *)device_get_softc(bus);
 	
-	/* a slave must have been started with the appropriate address */
-	if (!sc->started || !(sc->started & LSB))
+	/* a slave must have been started for reading */
+	if (sc->started == 0 || (sc->strict != 0 && (sc->started & LSB) == 0))
 		return (EINVAL);
 
 	return (IICBUS_READ(device_get_parent(bus), buf, len, read, last, delay));
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/ixgbe/ixgbe.c
--- a/head/sys/dev/ixgbe/ixgbe.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/ixgbe/ixgbe.c	Tue Dec 06 20:26:16 2011 +0200
@@ -30,7 +30,7 @@
   POSSIBILITY OF SUCH DAMAGE.
 
 ******************************************************************************/
-/*$FreeBSD: head/sys/dev/ixgbe/ixgbe.c 225405 2011-09-05 17:54:19Z qingli $*/
+/*$FreeBSD: head/sys/dev/ixgbe/ixgbe.c 228276 2011-12-05 12:06:53Z luigi $*/
 
 #ifdef HAVE_KERNEL_OPTION_HEADERS
 #include "opt_inet.h"
@@ -313,6 +313,18 @@
 static int fdir_pballoc = 1;
 #endif
 
+#ifdef DEV_NETMAP
+/*
+ * The #ifdef DEV_NETMAP / #endif blocks in this file are meant to
+ * be a reference on how to implement netmap support in a driver.
+ * Additional comments are in ixgbe_netmap.h .
+ *
+ * <dev/netma/ixgbe_netmap.h> contains functions for netmap support
+ * that extend the standard driver.
+ */
+#include <dev/netmap/ixgbe_netmap.h>
+#endif /* DEV_NETMAP */
+
 /*********************************************************************
  *  Device identification routine
  *
@@ -578,6 +590,9 @@
 
 	ixgbe_add_hw_stats(adapter);
 
+#ifdef DEV_NETMAP
+	ixgbe_netmap_attach(adapter);
+#endif /* DEV_NETMAP */
 	INIT_DEBUGOUT("ixgbe_attach: end");
 	return (0);
 err_late:
@@ -652,6 +667,9 @@
 
 	ether_ifdetach(adapter->ifp);
 	callout_drain(&adapter->timer);
+#ifdef DEV_NETMAP
+	netmap_detach(adapter->ifp);
+#endif /* DEV_NETMAP */
 	ixgbe_free_pci_resources(adapter);
 	bus_generic_detach(dev);
 	if_free(adapter->ifp);
@@ -2813,9 +2831,20 @@
 	struct adapter *adapter = txr->adapter;
 	struct ixgbe_tx_buf *txbuf;
 	int i;
+#ifdef DEV_NETMAP
+	struct netmap_adapter *na = NA(adapter->ifp);
+	struct netmap_slot *slot;
+#endif /* DEV_NETMAP */
 
 	/* Clear the old ring contents */
 	IXGBE_TX_LOCK(txr);
+#ifdef DEV_NETMAP
+	/*
+	 * (under lock): if in netmap mode, do some consistency
+	 * checks and set slot to entry 0 of the netmap ring.
+	 */
+	slot = netmap_reset(na, NR_TX, txr->me, 0);
+#endif /* DEV_NETMAP */
 	bzero((void *)txr->tx_base,
 	      (sizeof(union ixgbe_adv_tx_desc)) * adapter->num_tx_desc);
 	/* Reset indices */
@@ -2832,6 +2861,26 @@
 			m_freem(txbuf->m_head);
 			txbuf->m_head = NULL;
 		}
+#ifdef DEV_NETMAP
+		/*
+		 * In netmap mode, set the map for the packet buffer.
+		 * NOTE: Some drivers (not this one) also need to set
+		 * the physical buffer address in the NIC ring.
+		 * Slots in the netmap ring (indexed by "si") are
+		 * kring->nkr_hwofs positions "ahead" wrt the
+		 * corresponding slot in the NIC ring. In some drivers
+		 * (not here) nkr_hwofs can be negative. When computing
+		 * si = i + kring->nkr_hwofs make sure to handle wraparounds.
+		 */
+		if (slot) {
+			int si = i + na->tx_rings[txr->me].nkr_hwofs;
+
+			if (si >= na->num_tx_desc)
+				si -= na->num_tx_desc;
+			netmap_load_map(txr->txtag, txbuf->map,
+			    NMB(slot + si), na->buff_size);
+		}
+#endif /* DEV_NETMAP */
 		/* Clear the EOP index */
 		txbuf->eop_index = -1;
         }
@@ -3310,6 +3359,29 @@
 
 	mtx_assert(&txr->tx_mtx, MA_OWNED);
 
+#ifdef DEV_NETMAP
+	if (ifp->if_capenable & IFCAP_NETMAP) {
+		struct netmap_adapter *na = NA(ifp);
+
+		/*
+		 * In netmap mode, all the work is done in the context
+		 * of the client thread. Interrupt handlers only wake up
+		 * clients, which may be sleeping on individual rings
+		 * or on a global resource for all rings.
+		 * When the driver has separate locks, we need to
+		 * release and re-acquire txlock to avoid deadlocks.
+		 * XXX see if we can find a better way.
+		 */
+		selwakeuppri(&na->tx_rings[txr->me].si, PI_NET);
+		IXGBE_TX_UNLOCK(txr);
+		IXGBE_CORE_LOCK(adapter);
+		selwakeuppri(&na->tx_rings[na->num_queues + 1].si, PI_NET);
+		IXGBE_CORE_UNLOCK(adapter);
+		IXGBE_TX_LOCK(txr);
+		return FALSE;
+	}
+#endif /* DEV_NETMAP */
+
 	if (txr->tx_avail == adapter->num_tx_desc) {
 		txr->queue_status = IXGBE_QUEUE_IDLE;
 		return FALSE;
@@ -3698,6 +3770,10 @@
 	bus_dma_segment_t	pseg[1], hseg[1];
 	struct lro_ctrl		*lro = &rxr->lro;
 	int			rsize, nsegs, error = 0;
+#ifdef DEV_NETMAP
+	struct netmap_adapter *na = NA(rxr->adapter->ifp);
+	struct netmap_slot *slot;
+#endif /* DEV_NETMAP */
 
 	adapter = rxr->adapter;
 	ifp = adapter->ifp;
@@ -3705,6 +3781,10 @@
 
 	/* Clear the ring contents */
 	IXGBE_RX_LOCK(rxr);
+#ifdef DEV_NETMAP
+	/* same as in ixgbe_setup_transmit_ring() */
+	slot = netmap_reset(na, NR_RX, rxr->me, 0);
+#endif /* DEV_NETMAP */
 	rsize = roundup2(adapter->num_rx_desc *
 	    sizeof(union ixgbe_adv_rx_desc), DBA_ALIGN);
 	bzero((void *)rxr->rx_base, rsize);
@@ -3721,6 +3801,29 @@
 		struct mbuf	*mh, *mp;
 
 		rxbuf = &rxr->rx_buffers[j];
+#ifdef DEV_NETMAP
+		/*
+		 * In netmap mode, fill the map and set the buffer
+		 * address in the NIC ring, considering the offset
+		 * between the netmap and NIC rings (see comment in
+		 * ixgbe_setup_transmit_ring() ). No need to allocate
+		 * an mbuf, so end the block with a continue;
+		 */
+		if (slot) {
+			int sj = j + na->rx_rings[rxr->me].nkr_hwofs;
+			void *addr;
+
+			if (sj >= na->num_rx_desc)
+				sj -= na->num_rx_desc;
+			addr = NMB(slot + sj);
+			netmap_load_map(rxr->ptag,
+			    rxbuf->pmap, addr, na->buff_size);
+			/* Update descriptor */
+			rxr->rx_base[j].read.pkt_addr =
+			    htole64(vtophys(addr));
+			continue;
+		}
+#endif /* DEV_NETMAP */
 		/*
 		** Don't allocate mbufs if not
 		** doing header split, its wasteful
@@ -3913,6 +4016,35 @@
 
 		/* Setup the HW Rx Head and Tail Descriptor Pointers */
 		IXGBE_WRITE_REG(hw, IXGBE_RDH(i), 0);
+#ifdef DEV_NETMAP
+		/*
+		 * In netmap mode, we must preserve the buffers made
+		 * available to userspace before the if_init()
+		 * (this is true by default on the TX side, because
+		 * init makes all buffers available to userspace).
+		 *
+		 * netmap_reset() and the device specific routines
+		 * (e.g. ixgbe_setup_receive_rings()) map these
+		 * buffers at the end of the NIC ring, so here we
+		 * must set the RDT (tail) register to make sure
+		 * they are not overwritten.
+		 *
+		 * In this driver the NIC ring starts at RDH = 0,
+		 * RDT points to the first 'busy' slot, so RDT = 0
+		 * means the whole ring is available, and
+		 * RDT = (num_rx_desc - X) means X slots are available.
+		 * Computations are done modulo the ring size.
+		 */
+		if (ifp->if_capenable & IFCAP_NETMAP) {
+			struct netmap_adapter *na = NA(adapter->ifp);
+			struct netmap_kring *kring = &na->rx_rings[i];
+			int t = na->num_rx_desc - kring->nr_hwavail;
+
+			if (t >= na->num_rx_desc)
+				t -= adapter->num_rx_desc;
+			IXGBE_WRITE_REG(hw, IXGBE_RDT(i), t);
+		} else
+#endif /* DEV_NETMAP */
 		IXGBE_WRITE_REG(hw, IXGBE_RDT(i), 0);
 	}
 
@@ -4148,6 +4280,22 @@
 
 	IXGBE_RX_LOCK(rxr);
 
+#ifdef DEV_NETMAP
+	if (ifp->if_capenable & IFCAP_NETMAP) {
+		/*
+		 * Same as the txeof routine, only wakeup clients
+		 * and make sure there are no deadlocks.
+		 */
+		struct netmap_adapter *na = NA(ifp);
+
+		selwakeuppri(&na->rx_rings[rxr->me].si, PI_NET);
+		IXGBE_RX_UNLOCK(rxr);
+		IXGBE_CORE_LOCK(adapter);
+		selwakeuppri(&na->rx_rings[na->num_queues + 1].si, PI_NET);
+		IXGBE_CORE_UNLOCK(adapter);
+		return (FALSE);
+	}
+#endif /* DEV_NETMAP */
 	for (i = rxr->next_to_check; count != 0;) {
 		struct mbuf	*sendmp, *mh, *mp;
 		u32		rsc, ptype;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/mii/acphy.c
--- a/head/sys/dev/mii/acphy.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/mii/acphy.c	Tue Dec 06 20:26:16 2011 +0200
@@ -53,7 +53,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/mii/acphy.c 221407 2011-05-03 19:51:29Z marius $");
+__FBSDID("$FreeBSD: head/sys/dev/mii/acphy.c 227908 2011-11-23 20:27:26Z marius $");
 
 /*
  * Driver for Altima AC101 10/100 PHY
@@ -87,7 +87,7 @@
 	DEVMETHOD(device_attach,	acphy_attach),
 	DEVMETHOD(device_detach,	mii_phy_detach),
 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
-	{ 0, 0 }
+	DEVMETHOD_END
 };
 
 static devclass_t acphy_devclass;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/mii/amphy.c
--- a/head/sys/dev/mii/amphy.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/mii/amphy.c	Tue Dec 06 20:26:16 2011 +0200
@@ -31,7 +31,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/mii/amphy.c 221407 2011-05-03 19:51:29Z marius $");
+__FBSDID("$FreeBSD: head/sys/dev/mii/amphy.c 227908 2011-11-23 20:27:26Z marius $");
 
 /*
  * driver for AMD AM79c873 PHYs
@@ -66,7 +66,7 @@
 	DEVMETHOD(device_attach,	amphy_attach),
 	DEVMETHOD(device_detach,	mii_phy_detach),
 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
-	{ 0, 0 }
+	DEVMETHOD_END
 };
 
 static devclass_t amphy_devclass;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/mii/atphy.c
--- a/head/sys/dev/mii/atphy.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/mii/atphy.c	Tue Dec 06 20:26:16 2011 +0200
@@ -26,7 +26,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/mii/atphy.c 221817 2011-05-12 17:11:31Z yongari $");
+__FBSDID("$FreeBSD: head/sys/dev/mii/atphy.c 227908 2011-11-23 20:27:26Z marius $");
 
 /*
  * Driver for the Attansic/Atheros F1 10/100/1000 PHY.
@@ -59,7 +59,7 @@
 	DEVMETHOD(device_attach,	atphy_attach),
 	DEVMETHOD(device_detach,	mii_phy_detach),
 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
-	{ NULL, NULL }
+	DEVMETHOD_END
 };
 
 static devclass_t atphy_devclass;
@@ -81,6 +81,7 @@
 	MII_PHY_DESC(xxATHEROS, F1),
 	MII_PHY_DESC(xxATHEROS, F1_7),
 	MII_PHY_DESC(xxATHEROS, F2),
+	MII_PHY_DESC(xxATHEROS, F4),
 	MII_PHY_END
 };
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/mii/axphy.c
--- a/head/sys/dev/mii/axphy.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/mii/axphy.c	Tue Dec 06 20:26:16 2011 +0200
@@ -25,7 +25,7 @@
  * SUCH DAMAGE.
  */
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/mii/axphy.c 221407 2011-05-03 19:51:29Z marius $");
+__FBSDID("$FreeBSD: head/sys/dev/mii/axphy.c 227908 2011-11-23 20:27:26Z marius $");
 
 /*
  * driver for internal phy in the AX88x9x chips.
@@ -56,7 +56,7 @@
 	DEVMETHOD(device_attach,	axphy_attach),
 	DEVMETHOD(device_detach,	mii_phy_detach),
 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
-	{ 0, 0 }
+	DEVMETHOD_END
 };
 
 static devclass_t axphy_devclass;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/mii/bmtphy.c
--- a/head/sys/dev/mii/bmtphy.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/mii/bmtphy.c	Tue Dec 06 20:26:16 2011 +0200
@@ -56,7 +56,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/mii/bmtphy.c 221407 2011-05-03 19:51:29Z marius $");
+__FBSDID("$FreeBSD: head/sys/dev/mii/bmtphy.c 227908 2011-11-23 20:27:26Z marius $");
 
 /*
  * Driver for the Broadcom BCM5201/BCM5202 "Mini-Theta" PHYs.  This also
@@ -91,8 +91,7 @@
 	DEVMETHOD(device_attach,	bmtphy_attach),
 	DEVMETHOD(device_detach,	mii_phy_detach),
 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
-
-	{ 0, 0 }
+	DEVMETHOD_END
 };
 
 static devclass_t	bmtphy_devclass;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/mii/brgphy.c
--- a/head/sys/dev/mii/brgphy.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/mii/brgphy.c	Tue Dec 06 20:26:16 2011 +0200
@@ -31,7 +31,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/mii/brgphy.c 226870 2011-10-28 00:40:19Z yongari $");
+__FBSDID("$FreeBSD: head/sys/dev/mii/brgphy.c 227913 2011-11-23 22:05:44Z marius $");
 
 /*
  * Driver for the Broadcom BCM54xx/57xx 1000baseTX PHY.
@@ -82,7 +82,7 @@
 	DEVMETHOD(device_attach,	brgphy_attach),
 	DEVMETHOD(device_detach,	mii_phy_detach),
 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
-	{ 0, 0 }
+	DEVMETHOD_END
 };
 
 static devclass_t brgphy_devclass;
@@ -129,6 +129,7 @@
 	MII_PHY_DESC(BROADCOM, BCM5752),
 	MII_PHY_DESC(BROADCOM, BCM5780),
 	MII_PHY_DESC(BROADCOM, BCM5708C),
+	MII_PHY_DESC(BROADCOM2, BCM5481), /* XXX ? */
 	MII_PHY_DESC(BROADCOM2, BCM5482),
 	MII_PHY_DESC(BROADCOM2, BCM5708S),
 	MII_PHY_DESC(BROADCOM2, BCM5709C),
@@ -139,6 +140,9 @@
 	MII_PHY_DESC(BROADCOM2, BCM5754),
 	MII_PHY_DESC(BROADCOM2, BCM5761),
 	MII_PHY_DESC(BROADCOM2, BCM5784),
+#ifdef notyet	/* better handled by ukphy(4) until WARs are implemented */
+	MII_PHY_DESC(BROADCOM2, BCM5785),
+#endif
 	MII_PHY_DESC(BROADCOM3, BCM5717C),
 	MII_PHY_DESC(BROADCOM3, BCM5719C),
 	MII_PHY_DESC(BROADCOM3, BCM5720C),
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/mii/ciphy.c
--- a/head/sys/dev/mii/ciphy.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/mii/ciphy.c	Tue Dec 06 20:26:16 2011 +0200
@@ -31,7 +31,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/mii/ciphy.c 221407 2011-05-03 19:51:29Z marius $");
+__FBSDID("$FreeBSD: head/sys/dev/mii/ciphy.c 227908 2011-11-23 20:27:26Z marius $");
 
 /*
  * Driver for the Cicada/Vitesse CS/VSC8xxx 10/100/1000 copper PHY.
@@ -67,7 +67,7 @@
 	DEVMETHOD(device_attach,	ciphy_attach),
 	DEVMETHOD(device_detach,	mii_phy_detach),
 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
-	{ 0, 0 }
+	DEVMETHOD_END
 };
 
 static devclass_t ciphy_devclass;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/mii/e1000phy.c
--- a/head/sys/dev/mii/e1000phy.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/mii/e1000phy.c	Tue Dec 06 20:26:16 2011 +0200
@@ -30,7 +30,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/mii/e1000phy.c 223688 2011-06-30 05:20:02Z imp $");
+__FBSDID("$FreeBSD: head/sys/dev/mii/e1000phy.c 227908 2011-11-23 20:27:26Z marius $");
 
 /*
  * driver for the Marvell 88E1000 series external 1000/100/10-BT PHY.
@@ -71,7 +71,7 @@
 	DEVMETHOD(device_attach,	e1000phy_attach),
 	DEVMETHOD(device_detach,	mii_phy_detach),
 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
-	{ 0, 0 }
+	DEVMETHOD_END
 };
 
 static devclass_t e1000phy_devclass;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/mii/gentbi.c
--- a/head/sys/dev/mii/gentbi.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/mii/gentbi.c	Tue Dec 06 20:26:16 2011 +0200
@@ -62,7 +62,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/mii/gentbi.c 221407 2011-05-03 19:51:29Z marius $");
+__FBSDID("$FreeBSD: head/sys/dev/mii/gentbi.c 227908 2011-11-23 20:27:26Z marius $");
 
 /*
  * Driver for generic unknown ten-bit interfaces(1000BASE-{LX,SX}
@@ -95,7 +95,7 @@
 	DEVMETHOD(device_attach,	gentbi_attach),
 	DEVMETHOD(device_detach,	mii_phy_detach),
 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
-	{0, 0}
+	DEVMETHOD_END
 };
 
 static devclass_t gentbi_devclass;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/mii/icsphy.c
--- a/head/sys/dev/mii/icsphy.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/mii/icsphy.c	Tue Dec 06 20:26:16 2011 +0200
@@ -55,7 +55,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/mii/icsphy.c 221407 2011-05-03 19:51:29Z marius $");
+__FBSDID("$FreeBSD: head/sys/dev/mii/icsphy.c 227908 2011-11-23 20:27:26Z marius $");
 
 /*
  * driver for Integrated Circuit Systems' ICS1889-1893 ethernet 10/100 PHY
@@ -89,7 +89,7 @@
 	DEVMETHOD(device_attach,	icsphy_attach),
 	DEVMETHOD(device_detach,	mii_phy_detach),
 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
-	{ 0, 0 }
+	DEVMETHOD_END
 };
 
 static devclass_t icsphy_devclass;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/mii/ip1000phy.c
--- a/head/sys/dev/mii/ip1000phy.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/mii/ip1000phy.c	Tue Dec 06 20:26:16 2011 +0200
@@ -27,7 +27,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/mii/ip1000phy.c 227842 2011-11-22 21:22:06Z yongari $");
+__FBSDID("$FreeBSD: head/sys/dev/mii/ip1000phy.c 227908 2011-11-23 20:27:26Z marius $");
 
 /*
  * Driver for the IC Plus IP1000A/IP1001 10/100/1000 PHY.
@@ -63,7 +63,7 @@
 	DEVMETHOD(device_attach,	ip1000phy_attach),
 	DEVMETHOD(device_detach,	mii_phy_detach),
 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
-	{ 0, 0 }
+	DEVMETHOD_END
 };
 
 static devclass_t ip1000phy_devclass;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/mii/jmphy.c
--- a/head/sys/dev/mii/jmphy.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/mii/jmphy.c	Tue Dec 06 20:26:16 2011 +0200
@@ -26,7 +26,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/mii/jmphy.c 221407 2011-05-03 19:51:29Z marius $");
+__FBSDID("$FreeBSD: head/sys/dev/mii/jmphy.c 227908 2011-11-23 20:27:26Z marius $");
 
 /*
  * Driver for the JMicron JMP211 10/100/1000, JMP202 10/100 PHY.
@@ -62,7 +62,7 @@
 	DEVMETHOD(device_attach,	jmphy_attach),
 	DEVMETHOD(device_detach,	mii_phy_detach),
 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
-	{ NULL, NULL }
+	DEVMETHOD_END
 };
 
 static devclass_t jmphy_devclass;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/mii/lxtphy.c
--- a/head/sys/dev/mii/lxtphy.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/mii/lxtphy.c	Tue Dec 06 20:26:16 2011 +0200
@@ -56,7 +56,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/mii/lxtphy.c 221407 2011-05-03 19:51:29Z marius $");
+__FBSDID("$FreeBSD: head/sys/dev/mii/lxtphy.c 227908 2011-11-23 20:27:26Z marius $");
 
 /*
  * driver for Level One's LXT-970 ethernet 10/100 PHY
@@ -91,7 +91,7 @@
 	DEVMETHOD(device_attach,	lxtphy_attach),
 	DEVMETHOD(device_detach,	mii_phy_detach),
 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
-	{ 0, 0 }
+	DEVMETHOD_END
 };
 
 static devclass_t lxtphy_devclass;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/mii/mii.c
--- a/head/sys/dev/mii/mii.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/mii/mii.c	Tue Dec 06 20:26:16 2011 +0200
@@ -31,7 +31,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/mii/mii.c 227843 2011-11-22 21:28:20Z marius $");
+__FBSDID("$FreeBSD: head/sys/dev/mii/mii.c 228290 2011-12-05 21:38:45Z marius $");
 
 /*
  * MII bus layer, glues MII-capable network interface drivers to sharable
@@ -499,7 +499,7 @@
 	free(children, M_TEMP);
 
 	if (first != 0) {
-		rv = device_probe(*miibus);
+		rv = device_set_driver(*miibus, &miibus_driver);
 		if (rv != 0)
 			goto fail;
 		bus_enumerate_hinted_children(*miibus);
@@ -511,7 +511,7 @@
 			rv = ENXIO;
 			goto fail;
 		}
-		rv = device_attach(*miibus);
+		rv = bus_generic_attach(dev);
 		if (rv != 0)
 			goto fail;
 
@@ -626,7 +626,7 @@
 static unsigned char
 mii_bitreverse(unsigned char x)
 {
-	unsigned const char const nibbletab[16] = {
+	static unsigned const char const nibbletab[16] = {
 		0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15
 	};
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/mii/miidevs
--- a/head/sys/dev/mii/miidevs	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/mii/miidevs	Tue Dec 06 20:26:16 2011 +0200
@@ -1,5 +1,5 @@
-$FreeBSD: head/sys/dev/mii/miidevs 226870 2011-10-28 00:40:19Z yongari $
-/*$NetBSD: miidevs,v 1.99 2011/01/26 18:39:04 bouyer Exp $*/
+$FreeBSD: head/sys/dev/mii/miidevs 227906 2011-11-23 20:08:56Z marius $
+/*$NetBSD: miidevs,v 1.104 2011/11/12 11:10:49 sekiya Exp $*/
 
 /*-
  * Copyright (c) 1998, 1999 The NetBSD Foundation, Inc.
@@ -65,6 +65,7 @@
 oui NATSEMI			0x080017	National Semiconductor
 oui PMCSIERRA			0x00e004	PMC-Sierra
 oui QUALSEMI			0x006051	Quality Semiconductor
+oui RALINK			0x000c43	Ralink Technology Corporation
 oui RDC				0x00d02d	RDC Semiconductor
 oui REALTEK			0x00e04c	RealTek Semicondctor
 oui SEEQ			0x00a07d	Seeq Technology
@@ -108,6 +109,11 @@
 oui yyREALTEK			0x000004	RealTek Semicondctor
 
 /*
+ * Ethernet switch framwork pseudo ID.
+ * equal to just set register ID1 to 0xffff.
+ */
+oui SWITCHFW			0xfcff03	Switch Framework
+/*
  * List of known models.  Grouped by oui.
  */
 
@@ -133,6 +139,7 @@
 /* Atheros Communications/Attansic PHYs */
 model xxATHEROS F1		0x0001 Atheros F1 10/100/1000 PHY
 model xxATHEROS F2		0x0002 Atheros F2 10/100 PHY
+model xxATHEROS F4		0x0004 Atheros F2 10/100/1000 PHY
 model xxATHEROS F1_7		0x0007 Atheros F1 10/100/1000 PHY
 
 /* Asix semiconductor PHYs */
@@ -146,6 +153,7 @@
 model xxBROADCOM BCM5221	0x001e BCM5221 10/100 media interface
 model xxBROADCOM BCM5222	0x0032 BCM5222 Dual 10/100 media interface
 model xxBROADCOM BCM4401	0x0036 BCM4401 10/100 media interface
+model xxBROADCOM BCM5365	0x0037 BCM5365 10/100 5-port PHY switch
 model BROADCOM BCM5325		0x0025 BCM5325 10/100baseTX Switch PHY
 model BROADCOM BCM5400		0x0004 BCM5400 1000BASE-T media interface
 model BROADCOM BCM5401		0x0005 BCM5401 1000BASE-T media interface
@@ -165,12 +173,14 @@
 model BROADCOM BCM5714		0x0034 BCM5714 1000BASE-T media interface
 model BROADCOM BCM5780		0x0035 BCM5780 1000BASE-T media interface
 model BROADCOM BCM5708C		0x0036 BCM5708C 1000BASE-T media interface
+model BROADCOM2 BCM5325		0x0003 BCM5325 10/100 5-port PHY switch
 model BROADCOM2 BCM5906		0x0004 BCM5906 10/100baseTX media interface
 model BROADCOM2 BCM5481		0x000a BCM5481 1000BASE-T media interface
 model BROADCOM2 BCM5482		0x000b BCM5482 1000BASE-T media interface
 model BROADCOM2 BCM5755		0x000c BCM5755 1000BASE-T media interface
 model BROADCOM2 BCM5754		0x000e BCM5754/5787 1000BASE-T media interface
 model BROADCOM2 BCM5708S	0x0015 BCM5708S 1000/2500baseSX PHY
+model BROADCOM2 BCM5785		0x0016 BCM5785 1000BASE-T media interface
 model BROADCOM2 BCM5709CAX	0x002c BCM5709CAX 10/100/1000baseT PHY
 model BROADCOM2 BCM5722		0x002d BCM5722 1000BASE-T media interface
 model BROADCOM2 BCM5325		0x0030 BCM5325 10/100baseT Switch
@@ -220,6 +230,10 @@
 model yyINTEL I82553		0x0035 i82553 10/100 media interface
 model yyINTEL I82566		0x0039 i82566 10/100/1000 media interface
 model INTEL I82577		0x0005 i82577 10/100/1000 media interface
+model INTEL I82579		0x0009 i82579 10/100/1000 media interface
+model xxMARVELL I82563		0x000a i82563 10/100/1000 media interface
+
+model yyINTEL IGP01E1000	0x0038 Intel IGP01E1000 Gigabit PHY
 
 /* Jato Technologies PHYs */
 model xxJATO BASEX		0x0000 Jato 1000baseX media interface
@@ -248,18 +262,24 @@
 model xxMARVELL E1112		0x0009 Marvell 88E1112 Gigabit PHY
 model xxMARVELL E1149		0x000b Marvell 88E1149 Gigabit PHY
 model xxMARVELL E1111		0x000c Marvell 88E1111 Gigabit PHY
+model xxMARVELL E1145		0x000d Marvell 88E1145 Quad Gigabit PHY
 model xxMARVELL E1116		0x0021 Marvell 88E1116 Gigabit PHY
 model xxMARVELL E1116R		0x0024 Marvell 88E1116R Gigabit PHY
 model xxMARVELL E1118		0x0022 Marvell 88E1118 Gigabit PHY
 model xxMARVELL E1149R		0x0025 Marvell 88E1149R Quad Gigabit PHY
 model xxMARVELL E3016		0x0026 Marvell 88E3016 10/100 Fast Ethernet PHY
 model xxMARVELL PHYG65G		0x0027 Marvell PHYG65G Gigabit PHY
+model xxMARVELL E1116R_29	0x0029 Marvell 88E1116R Gigabit PHY
 model MARVELL E1000		0x0005 Marvell 88E1000 Gigabit PHY
 model MARVELL E1011		0x0002 Marvell 88E1011 Gigabit PHY
 model MARVELL E1000_3		0x0003 Marvell 88E1000 Gigabit PHY
 model MARVELL E1000_5		0x0005 Marvell 88E1000 Gigabit PHY
 model MARVELL E1111		0x000c Marvell 88E1111 Gigabit PHY
 
+/* Myson Technology PHYs */
+model xxMYSON MTD972		0x0000 MTD972 10/100 media interface
+model MYSON MTD803		0x0000 MTD803 3-in-1 media interface
+
 /* National Semiconductor PHYs */
 model xxNATSEMI DP83840		0x0000 DP83840 10/100 media interface
 model xxNATSEMI DP83843		0x0001 DP83843 10/100 media interface
@@ -278,6 +298,9 @@
 /* Quality Semiconductor PHYs */
 model xxQUALSEMI QS6612		0x0000 QS6612 10/100 media interface
 
+/* Ralink Technology Corporation PHYs */
+model RALINK RT305X		0x0000 RT305XF 10/100 media interface
+
 /* RDC Semiconductor PHYs */
 model RDC R6040			0x0003 R6040 10/100 media interface
 
@@ -296,6 +319,20 @@
 /* Silicon Integrated Systems PHYs */
 model SIS 900			0x0000 SiS 900 10/100 media interface
 
+/*
+ * Ethernet switch framwork pseudo IDs.
+ * Reserve space for new models of manufacturers.
+ */
+model SWITCHFW AR8X16		0x0101 Atheros AR8x16 switch family
+model SWITCHFW BCM5325		0x0201 Broadcom BCM5325 switch family (5354, 53115, etc)
+/* IC+ 0x0300 */
+/* Infineon-ADMtek 0x0400 */
+/* Marvel 0x0500 */
+model SWITCHFW RT305X		0x0601 Ralink RT3050F/RT3052F internal switch
+model SWITCHFW RTL830x		0x0701 Realtek RTL8306/RTL8309
+model SWITCHFW RTL8366		0x0702 Realtek RTL8366 switch family
+model SWITCHFW RTL8370		0x0703 Realtek RTL8367/RTL8370 switch family
+
 /* Texas Instruments PHYs */
 model TI TLAN10T		0x0001 ThunderLAN 10BASE-T media interface
 model TI 100VGPMI		0x0002 ThunderLAN 100VG-AnyLan media interface
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/mii/mlphy.c
--- a/head/sys/dev/mii/mlphy.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/mii/mlphy.c	Tue Dec 06 20:26:16 2011 +0200
@@ -32,7 +32,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/mii/mlphy.c 221407 2011-05-03 19:51:29Z marius $");
+__FBSDID("$FreeBSD: head/sys/dev/mii/mlphy.c 227908 2011-11-23 20:27:26Z marius $");
 
 /*
  * driver for Micro Linear 6692 PHYs
@@ -84,7 +84,7 @@
 	DEVMETHOD(device_attach,	mlphy_attach),
 	DEVMETHOD(device_detach,	mii_phy_detach),
 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
-	{ 0, 0 }
+	DEVMETHOD_END
 };
 
 static devclass_t mlphy_devclass;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/mii/nsgphy.c
--- a/head/sys/dev/mii/nsgphy.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/mii/nsgphy.c	Tue Dec 06 20:26:16 2011 +0200
@@ -38,7 +38,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/mii/nsgphy.c 221407 2011-05-03 19:51:29Z marius $");
+__FBSDID("$FreeBSD: head/sys/dev/mii/nsgphy.c 227908 2011-11-23 20:27:26Z marius $");
 
 /*
  * Driver for the National Semiconductor DP83861, DP83865 and DP83891
@@ -83,7 +83,7 @@
 	DEVMETHOD(device_attach,	nsgphy_attach),
 	DEVMETHOD(device_detach,	mii_phy_detach),
 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
-	{ 0, 0 }
+	DEVMETHOD_END
 };
 
 static devclass_t nsgphy_devclass;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/mii/nsphy.c
--- a/head/sys/dev/mii/nsphy.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/mii/nsphy.c	Tue Dec 06 20:26:16 2011 +0200
@@ -55,7 +55,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/mii/nsphy.c 221407 2011-05-03 19:51:29Z marius $");
+__FBSDID("$FreeBSD: head/sys/dev/mii/nsphy.c 227908 2011-11-23 20:27:26Z marius $");
 
 /*
  * driver for National Semiconductor's DP83840A ethernet 10/100 PHY
@@ -90,7 +90,7 @@
 	DEVMETHOD(device_attach,	nsphy_attach),
 	DEVMETHOD(device_detach,	mii_phy_detach),
 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
-	{ 0, 0 }
+	DEVMETHOD_END
 };
 
 static devclass_t nsphy_devclass;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/mii/nsphyter.c
--- a/head/sys/dev/mii/nsphyter.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/mii/nsphyter.c	Tue Dec 06 20:26:16 2011 +0200
@@ -55,7 +55,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/mii/nsphyter.c 221407 2011-05-03 19:51:29Z marius $");
+__FBSDID("$FreeBSD: head/sys/dev/mii/nsphyter.c 227908 2011-11-23 20:27:26Z marius $");
 
 /*
  * driver for National Semiconductor's DP83843 `PHYTER' ethernet 10/100 PHY
@@ -93,7 +93,7 @@
 	DEVMETHOD(device_attach,	nsphyter_attach),
 	DEVMETHOD(device_detach,	mii_phy_detach),
 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
-	{ 0, 0 }
+	DEVMETHOD_END
 };
 
 static devclass_t nsphyter_devclass;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/mii/pnaphy.c
--- a/head/sys/dev/mii/pnaphy.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/mii/pnaphy.c	Tue Dec 06 20:26:16 2011 +0200
@@ -32,7 +32,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/mii/pnaphy.c 221407 2011-05-03 19:51:29Z marius $");
+__FBSDID("$FreeBSD: head/sys/dev/mii/pnaphy.c 227908 2011-11-23 20:27:26Z marius $");
 
 /*
  * driver for homePNA PHYs
@@ -69,7 +69,7 @@
 	DEVMETHOD(device_attach,	pnaphy_attach),
 	DEVMETHOD(device_detach,	mii_phy_detach),
 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
-	{ 0, 0 }
+	DEVMETHOD_END
 };
 
 static devclass_t pnaphy_devclass;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/mii/qsphy.c
--- a/head/sys/dev/mii/qsphy.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/mii/qsphy.c	Tue Dec 06 20:26:16 2011 +0200
@@ -56,7 +56,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/mii/qsphy.c 221407 2011-05-03 19:51:29Z marius $");
+__FBSDID("$FreeBSD: head/sys/dev/mii/qsphy.c 227908 2011-11-23 20:27:26Z marius $");
 
 /*
  * driver for Quality Semiconductor's QS6612 ethernet 10/100 PHY
@@ -91,7 +91,7 @@
 	DEVMETHOD(device_attach,	qsphy_attach),
 	DEVMETHOD(device_detach,	mii_phy_detach),
 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
-	{ 0, 0 }
+	DEVMETHOD_END
 };
 
 static devclass_t qsphy_devclass;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/mii/rgephy.c
--- a/head/sys/dev/mii/rgephy.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/mii/rgephy.c	Tue Dec 06 20:26:16 2011 +0200
@@ -31,7 +31,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/mii/rgephy.c 221407 2011-05-03 19:51:29Z marius $");
+__FBSDID("$FreeBSD: head/sys/dev/mii/rgephy.c 227908 2011-11-23 20:27:26Z marius $");
 
 /*
  * Driver for the RealTek 8169S/8110S/8211B/8211C internal 10/100/1000 PHY.
@@ -68,7 +68,7 @@
 	DEVMETHOD(device_attach,	rgephy_attach),
 	DEVMETHOD(device_detach,	mii_phy_detach),
 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
-	{ 0, 0 }
+	DEVMETHOD_END
 };
 
 static devclass_t rgephy_devclass;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/mii/rlphy.c
--- a/head/sys/dev/mii/rlphy.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/mii/rlphy.c	Tue Dec 06 20:26:16 2011 +0200
@@ -31,7 +31,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/mii/rlphy.c 221407 2011-05-03 19:51:29Z marius $");
+__FBSDID("$FreeBSD: head/sys/dev/mii/rlphy.c 227908 2011-11-23 20:27:26Z marius $");
 
 /*
  * driver for RealTek 8139 internal PHYs
@@ -66,7 +66,7 @@
 	DEVMETHOD(device_attach,	rlphy_attach),
 	DEVMETHOD(device_detach,	mii_phy_detach),
 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
-	{ 0, 0 }
+	DEVMETHOD_END
 };
 
 static devclass_t rlphy_devclass;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/mii/rlswitch.c
--- a/head/sys/dev/mii/rlswitch.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/mii/rlswitch.c	Tue Dec 06 20:26:16 2011 +0200
@@ -32,7 +32,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/sys/dev/mii/rlswitch.c 227908 2011-11-23 20:27:26Z marius $");
 
 /*
  * driver for RealTek 8305 pseudo PHYs
@@ -72,7 +72,7 @@
 	DEVMETHOD(device_attach,	rlswitch_attach),
 	DEVMETHOD(device_detach,	mii_phy_detach),
 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
-	{ 0, 0 }
+	DEVMETHOD_END
 };
 
 static devclass_t rlswitch_devclass;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/mii/smcphy.c
--- a/head/sys/dev/mii/smcphy.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/mii/smcphy.c	Tue Dec 06 20:26:16 2011 +0200
@@ -23,7 +23,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/mii/smcphy.c 221407 2011-05-03 19:51:29Z marius $");
+__FBSDID("$FreeBSD: head/sys/dev/mii/smcphy.c 227908 2011-11-23 20:27:26Z marius $");
 
 /*
  * Driver for the internal PHY on the SMSC LAN91C111.
@@ -62,8 +62,7 @@
 	DEVMETHOD(device_attach,	smcphy_attach),
 	DEVMETHOD(device_detach,	mii_phy_detach),
 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
-
-	{ 0, 0 }
+	DEVMETHOD_END
 };
 
 static devclass_t smcphy_devclass;
@@ -207,8 +206,7 @@
 {
 	uint16_t	anar;
 
-	anar = BMSR_MEDIA_TO_ANAR(sc->mii_capabilities) |
-	    ANAR_CSMA;
+	anar = BMSR_MEDIA_TO_ANAR(sc->mii_capabilities) | ANAR_CSMA;
 	if ((media & IFM_FLOW) != 0 || (sc->mii_flags & MIIF_FORCEPAUSE) != 0)
 		anar |= ANAR_FC;
 	PHY_WRITE(sc, MII_ANAR, anar);
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/mii/tdkphy.c
--- a/head/sys/dev/mii/tdkphy.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/mii/tdkphy.c	Tue Dec 06 20:26:16 2011 +0200
@@ -27,7 +27,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/mii/tdkphy.c 221407 2011-05-03 19:51:29Z marius $");
+__FBSDID("$FreeBSD: head/sys/dev/mii/tdkphy.c 227908 2011-11-23 20:27:26Z marius $");
 
 /*
  * Driver for the TDK 78Q2120 MII
@@ -71,7 +71,7 @@
 	DEVMETHOD(device_attach,	tdkphy_attach),
 	DEVMETHOD(device_detach,	mii_phy_detach),
 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
-	{ 0, 0 }
+	DEVMETHOD_END
 };
 
 static devclass_t tdkphy_devclass;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/mii/tlphy.c
--- a/head/sys/dev/mii/tlphy.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/mii/tlphy.c	Tue Dec 06 20:26:16 2011 +0200
@@ -55,7 +55,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/mii/tlphy.c 221407 2011-05-03 19:51:29Z marius $");
+__FBSDID("$FreeBSD: head/sys/dev/mii/tlphy.c 227908 2011-11-23 20:27:26Z marius $");
 
 /*
  * Driver for Texas Instruments's ThunderLAN PHYs
@@ -97,7 +97,7 @@
 	DEVMETHOD(device_attach,	tlphy_attach),
 	DEVMETHOD(device_detach,	mii_phy_detach),
 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
-	{ 0, 0 }
+	DEVMETHOD_END
 };
 
 static devclass_t tlphy_devclass;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/mii/truephy.c
--- a/head/sys/dev/mii/truephy.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/mii/truephy.c	Tue Dec 06 20:26:16 2011 +0200
@@ -32,7 +32,7 @@
  * SUCH DAMAGE.
  * 
  * $DragonFly: src/sys/dev/netif/mii_layer/truephy.c,v 1.3 2008/02/10 07:29:27 sephe Exp $
- * $FreeBSD: head/sys/dev/mii/truephy.c 221407 2011-05-03 19:51:29Z marius $
+ * $FreeBSD: head/sys/dev/mii/truephy.c 227908 2011-11-23 20:27:26Z marius $
  */
 
 #include <sys/param.h>
@@ -72,7 +72,7 @@
 	DEVMETHOD(device_attach,	truephy_attach),
 	DEVMETHOD(device_detach,	mii_phy_detach),
 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
-	{ 0, 0 }
+	DEVMETHOD_END
 };
 
 static const struct mii_phydesc truephys[] = {
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/mii/ukphy.c
--- a/head/sys/dev/mii/ukphy.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/mii/ukphy.c	Tue Dec 06 20:26:16 2011 +0200
@@ -55,7 +55,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/mii/ukphy.c 221407 2011-05-03 19:51:29Z marius $");
+__FBSDID("$FreeBSD: head/sys/dev/mii/ukphy.c 227908 2011-11-23 20:27:26Z marius $");
 
 /*
  * driver for generic unknown PHYs
@@ -86,7 +86,7 @@
 	DEVMETHOD(device_attach,	ukphy_attach),
 	DEVMETHOD(device_detach,	mii_phy_detach),
 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
-	{ 0, 0 }
+	DEVMETHOD_END
 };
 
 static devclass_t ukphy_devclass;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/mii/xmphy.c
--- a/head/sys/dev/mii/xmphy.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/mii/xmphy.c	Tue Dec 06 20:26:16 2011 +0200
@@ -31,7 +31,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/mii/xmphy.c 221407 2011-05-03 19:51:29Z marius $");
+__FBSDID("$FreeBSD: head/sys/dev/mii/xmphy.c 227908 2011-11-23 20:27:26Z marius $");
 
 /*
  * driver for the XaQti XMAC II's internal PHY. This is sort of
@@ -66,7 +66,7 @@
 	DEVMETHOD(device_attach,	xmphy_attach),
 	DEVMETHOD(device_detach,	mii_phy_detach),
 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
-	{ 0, 0 }
+	DEVMETHOD_END
 };
 
 static devclass_t xmphy_devclass;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/netmap/if_em_netmap.h
--- a/head/sys/dev/netmap/if_em_netmap.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/netmap/if_em_netmap.h	Tue Dec 06 20:26:16 2011 +0200
@@ -9,7 +9,7 @@
  * 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
@@ -24,10 +24,13 @@
  */
 
 /*
- * $FreeBSD: head/sys/dev/netmap/if_em_netmap.h 227614 2011-11-17 12:17:39Z luigi $
- * $Id: if_em_netmap.h 9662 2011-11-16 13:18:06Z luigi $
+ * $FreeBSD: head/sys/dev/netmap/if_em_netmap.h 228276 2011-12-05 12:06:53Z luigi $
+ * $Id: if_em_netmap.h 9802 2011-12-02 18:42:37Z luigi $
  *
  * netmap changes for if_em.
+ *
+ * For structure and details on the individual functions please see
+ * ixgbe_netmap.h
  */
 
 #include <net/netmap.h>
@@ -58,12 +61,7 @@
 	na.nm_rxsync = em_netmap_rxsync;
 	na.nm_lock = em_netmap_lock_wrapper;
 	na.nm_register = em_netmap_reg;
-	/*
-	 * adapter->rx_mbuf_sz is set by SIOCSETMTU, but in netmap mode
-	 * we allocate the buffers on the first register. So we must
-	 * disallow a SIOCSETMTU when if_capenable & IFCAP_NETMAP is set.
-	 */
-	na.buff_size = MCLBYTES;
+	na.buff_size = NETMAP_BUF_SIZE;
 	netmap_attach(&na, adapter->num_queues);
 }
 
@@ -100,6 +98,7 @@
 }
 
 
+// XXX do we need to block/unblock the tasks ?
 static void
 em_netmap_block_tasks(struct adapter *adapter)
 {
@@ -162,9 +161,6 @@
 	if (onoff) {
 		ifp->if_capenable |= IFCAP_NETMAP;
 
-		/* save if_transmit for later restore.
-		 * XXX also if_start and if_qflush ?
-		 */
 		na->if_transmit = ifp->if_transmit;
 		ifp->if_transmit = netmap_start;
 
@@ -179,15 +175,13 @@
 		ifp->if_transmit = na->if_transmit;
 		ifp->if_capenable &= ~IFCAP_NETMAP;
 		em_init_locked(adapter);	/* also enable intr */
-
 	}
 	em_netmap_unblock_tasks(adapter);
 	return (error);
 }
 
 /*
- * Reconcile hardware and user view of the transmit ring, see
- * ixgbe.c for details.
+ * Reconcile hardware and user view of the transmit ring.
  */
 static int
 em_netmap_txsync(void *a, u_int ring_nr, int do_lock)
@@ -197,13 +191,13 @@
 	struct netmap_adapter *na = NA(adapter->ifp);
 	struct netmap_kring *kring = &na->tx_rings[ring_nr];
 	struct netmap_ring *ring = kring->ring;
-	int j, k, n, lim = kring->nkr_num_slots - 1;
+	int j, k, l, n = 0, lim = kring->nkr_num_slots - 1;
 
 	/* generate an interrupt approximately every half ring */
 	int report_frequency = kring->nkr_num_slots >> 1;
 
 	k = ring->cur;
-	if ( (kring->nr_kflags & NR_REINIT) || k > lim)
+	if (k > lim)
 		return netmap_ring_reinit(kring);
 
 	if (do_lock)
@@ -211,35 +205,20 @@
 	bus_dmamap_sync(txr->txdma.dma_tag, txr->txdma.dma_map,
 			BUS_DMASYNC_POSTREAD);
 
-	/* record completed transmissions TODO
-	 *
-	 * instead of using TDH, we could read the transmitted status bit.
+	/* check for new packets to send.
+	 * j indexes the netmap ring, l indexes the nic ring, and
+	 *	j = kring->nr_hwcur, l = E1000_TDT (not tracked),
+	 *	j == (l + kring->nkr_hwofs) % ring_size
 	 */
-	j = E1000_READ_REG(&adapter->hw, E1000_TDH(ring_nr));
-	if (j >= kring->nkr_num_slots) { /* XXX can happen */
-		D("TDH wrap %d", j);
-		j -= kring->nkr_num_slots;
-	}
-	int delta = j - txr->next_to_clean;
-	if (delta) {
-		/* new transmissions were completed, increment
-		   ring->nr_hwavail. */
-		if (delta < 0)
-			delta += kring->nkr_num_slots;
-		txr->next_to_clean = j;
-		kring->nr_hwavail += delta;
-	}
-
-	/* update avail to what the hardware knows */
-	ring->avail = kring->nr_hwavail;
-
 	j = kring->nr_hwcur;
 	if (j != k) {	/* we have packets to send */
-		n = 0;
+		l = j - kring->nkr_hwofs;
+		if (l < 0)
+			l += lim + 1;
 		while (j != k) {
 			struct netmap_slot *slot = &ring->slot[j];
-			struct e1000_tx_desc *curr = &txr->tx_base[j];
-			struct em_buffer *txbuf = &txr->tx_buffers[j];
+			struct e1000_tx_desc *curr = &txr->tx_base[l];
+			struct em_buffer *txbuf = &txr->tx_buffers[l];
 			int flags = ((slot->flags & NS_REPORT) ||
 				j == 0 || j == report_frequency) ?
 					E1000_TXD_CMD_RS : 0;
@@ -254,42 +233,61 @@
 			slot->flags &= ~NS_REPORT;
 			curr->upper.data = 0;
 			curr->lower.data = 
-			    htole32(
-				adapter->txd_cmd |
-				(E1000_TXD_CMD_EOP | flags) |
-				slot->len);
+			    htole32(adapter->txd_cmd | len |
+				(E1000_TXD_CMD_EOP | flags) );
 			if (slot->flags & NS_BUF_CHANGED) {
 				curr->buffer_addr = htole64(vtophys(addr));
-				/* buffer has changed, unload and reload map */
+				/* buffer has changed, reload map */
 				netmap_reload_map(txr->txtag, txbuf->map,
-					addr, na->buff_size);
+				    addr, na->buff_size);
 				slot->flags &= ~NS_BUF_CHANGED;
 			}
 
 			bus_dmamap_sync(txr->txtag, txbuf->map,
 				BUS_DMASYNC_PREWRITE);
 			j = (j == lim) ? 0 : j + 1;
+			l = (l == lim) ? 0 : l + 1;
 			n++;
 		}
-		kring->nr_hwcur = ring->cur;
+		kring->nr_hwcur = k;
 
 		/* decrease avail by number of sent packets */
-		ring->avail -= n;
-		kring->nr_hwavail = ring->avail;
+		kring->nr_hwavail -= n;
 
 		bus_dmamap_sync(txr->txdma.dma_tag, txr->txdma.dma_map,
-			BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
+		    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
 
-		E1000_WRITE_REG(&adapter->hw, E1000_TDT(txr->me),
-			ring->cur);
+		E1000_WRITE_REG(&adapter->hw, E1000_TDT(txr->me), l);
 	}
+
+	if (n == 0 || kring->nr_hwavail < 1) {
+		int delta;
+
+		/* record completed transmissions using THD. */
+		l = E1000_READ_REG(&adapter->hw, E1000_TDH(ring_nr));
+		if (l >= kring->nkr_num_slots) { /* XXX can happen */
+			D("TDH wrap %d", l);
+			l -= kring->nkr_num_slots;
+		}
+		delta = l - txr->next_to_clean;
+		if (delta) {
+			/* some completed, increment hwavail. */
+			if (delta < 0)
+				delta += kring->nkr_num_slots;
+			txr->next_to_clean = l;
+			kring->nr_hwavail += delta;
+		}
+	}
+	/* update avail to what the hardware knows */
+	ring->avail = kring->nr_hwavail;
+
 	if (do_lock)
 		EM_TX_UNLOCK(txr);
 	return 0;
 }
 
 /*
- * Reconcile kernel and user view of the receive ring, see ixgbe.c
+ * Reconcile kernel and user view of the receive ring.
  */
 static int
 em_netmap_rxsync(void *a, u_int ring_nr, int do_lock)
@@ -299,10 +297,10 @@
 	struct netmap_adapter *na = NA(adapter->ifp);
 	struct netmap_kring *kring = &na->rx_rings[ring_nr];
 	struct netmap_ring *ring = kring->ring;
-	int j, k, n, lim = kring->nkr_num_slots - 1;
+	int j, k, l, n, lim = kring->nkr_num_slots - 1;
 
 	k = ring->cur;
-	if ( (kring->nr_kflags & NR_REINIT) || k > lim)
+	if (k > lim)
 		return netmap_ring_reinit(kring);
  
 	if (do_lock)
@@ -311,36 +309,52 @@
 	bus_dmamap_sync(rxr->rxdma.dma_tag, rxr->rxdma.dma_map,
 			BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
 
-	/* acknowledge all the received packets. */
-	j = rxr->next_to_check;
+	/* import newly received packets into the netmap ring.
+	 * j is an index in the netmap ring, l in the NIC ring, and
+	 *	j = (kring->nr_hwcur + kring->nr_hwavail) % ring_size
+	 *	l = rxr->next_to_check;
+	 * and
+	 *	j == (l + kring->nkr_hwofs) % ring_size
+	 */
+	l = rxr->next_to_check;
+	j = l + kring->nkr_hwofs;
+	/* here nkr_hwofs can be negative so must check for j < 0 */
+	if (j < 0)
+		j += lim + 1;
+	else if (j > lim)
+		j -= lim + 1;
 	for (n = 0; ; n++) {
-		struct e1000_rx_desc *curr = &rxr->rx_base[j];
+		struct e1000_rx_desc *curr = &rxr->rx_base[l];
 
 		if ((curr->status & E1000_RXD_STAT_DD) == 0)
 			break;
 		ring->slot[j].len = le16toh(curr->length);
-		bus_dmamap_sync(rxr->tag, rxr->rx_buffers[j].map,
+		bus_dmamap_sync(rxr->tag, rxr->rx_buffers[l].map,
 			BUS_DMASYNC_POSTREAD);
 		j = (j == lim) ? 0 : j + 1;
+		/* make sure next_to_refresh follows next_to_check */
+		rxr->next_to_refresh = l;	// XXX
+		l = (l == lim) ? 0 : l + 1;
 	}
 	if (n) {
-		rxr->next_to_check = j;
+		rxr->next_to_check = l;
 		kring->nr_hwavail += n;
 	}
 
-	/* skip past packets that userspace has already processed:
-	 * making them available for reception.
-	 * advance nr_hwcur and issue a bus_dmamap_sync on the
-	 * buffers so it is safe to write to them.
-	 * Also increase nr_hwavail
-         */
+	/* skip past packets that userspace has already processed */
 	j = kring->nr_hwcur;
 	if (j != k) { /* userspace has read some packets. */
 		n = 0;
+		l = j - kring->nkr_hwofs; /* NIC ring index */
+		/* here nkr_hwofs can be negative so check for l > lim */
+		if (l < 0)
+			l += lim + 1;
+		else if (l > lim)
+			l -= lim + 1;
 		while (j != k) {
 			struct netmap_slot *slot = &ring->slot[j];
-			struct e1000_rx_desc *curr = &rxr->rx_base[j];
-			struct em_buffer *rxbuf = &rxr->rx_buffers[j];
+			struct e1000_rx_desc *curr = &rxr->rx_base[l];
+			struct em_buffer *rxbuf = &rxr->rx_buffers[l];
 			void *addr = NMB(slot);
 
 			if (addr == netmap_buffer_base) { /* bad buf */
@@ -352,28 +366,29 @@
 			curr->status = 0;
 			if (slot->flags & NS_BUF_CHANGED) {
 				curr->buffer_addr = htole64(vtophys(addr));
-				/* buffer has changed, unload and reload map */
+				/* buffer has changed, reload map */
 				netmap_reload_map(rxr->rxtag, rxbuf->map,
-					addr, na->buff_size);
+				    addr, na->buff_size);
 				slot->flags &= ~NS_BUF_CHANGED;
 			}
 
 			bus_dmamap_sync(rxr->rxtag, rxbuf->map,
-				BUS_DMASYNC_PREREAD);
+			    BUS_DMASYNC_PREREAD);
 
 			j = (j == lim) ? 0 : j + 1;
+			l = (l == lim) ? 0 : l + 1;
 			n++;
 		}
 		kring->nr_hwavail -= n;
-		kring->nr_hwcur = ring->cur;
+		kring->nr_hwcur = k;
 		bus_dmamap_sync(rxr->rxdma.dma_tag, rxr->rxdma.dma_map,
-			BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
+		    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
 		/*
 		 * IMPORTANT: we must leave one free slot in the ring,
-		 * so move j back by one unit
+		 * so move l back by one unit
 		 */
-		j = (j == 0) ? lim : j - 1;
-		E1000_WRITE_REG(&adapter->hw, E1000_RDT(rxr->me), j);
+		l = (l == 0) ? lim : l - 1;
+		E1000_WRITE_REG(&adapter->hw, E1000_RDT(rxr->me), l);
 	}
 	/* tell userspace that there are new packets */
 	ring->avail = kring->nr_hwavail ;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/netmap/if_igb_netmap.h
--- a/head/sys/dev/netmap/if_igb_netmap.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/netmap/if_igb_netmap.h	Tue Dec 06 20:26:16 2011 +0200
@@ -24,8 +24,8 @@
  */
 
 /*
- * $FreeBSD: head/sys/dev/netmap/if_igb_netmap.h 227614 2011-11-17 12:17:39Z luigi $
- * $Id: if_igb_netmap.h 9662 2011-11-16 13:18:06Z luigi $
+ * $FreeBSD: head/sys/dev/netmap/if_igb_netmap.h 228276 2011-12-05 12:06:53Z luigi $
+ * $Id: if_igb_netmap.h 9802 2011-12-02 18:42:37Z luigi $
  *
  * netmap modifications for igb
  * contribured by Ahmed Kooli
@@ -58,12 +58,7 @@
 	na.nm_rxsync = igb_netmap_rxsync;
 	na.nm_lock = igb_netmap_lock_wrapper;
 	na.nm_register = igb_netmap_reg;
-	/*
-	 * adapter->rx_mbuf_sz is set by SIOCSETMTU, but in netmap mode
-	 * we allocate the buffers on the first register. So we must
-	 * disallow a SIOCSETMTU when if_capenable & IFCAP_NETMAP is set.
-	 */
-	na.buff_size = MCLBYTES;
+	na.buff_size = NETMAP_BUF_SIZE;
 	netmap_attach(&na, adapter->num_queues);
 }	
 
@@ -111,7 +106,7 @@
 	struct netmap_adapter *na = NA(ifp);
 	int error = 0;
 
-	if (!na)
+	if (na == NULL)
 		return EINVAL;
 
 	igb_disable_intr(adapter);
@@ -144,21 +139,6 @@
 
 /*
  * Reconcile kernel and user view of the transmit ring.
- *
- * Userspace has filled tx slots up to cur (excluded).
- * The last unused slot previously known to the kernel was nr_hwcur,
- * and the last interrupt reported nr_hwavail slots available
- * (using the special value -1 to indicate idle transmit ring).
- * The function must first update avail to what the kernel
- * knows, subtract the newly used slots (cur - nr_hwcur)
- * from both avail and nr_hwavail, and set nr_hwcur = cur
- * issuing a dmamap_sync on all slots.
- *
- * Check parameters in the struct netmap_ring.
- * We don't use avail, only check for bogus values.
- * Make sure cur is valid, and same goes for buffer indexes and lengths.
- * To avoid races, read the values once, and never use those from
- * the ring afterwards.
  */
 static int
 igb_netmap_txsync(void *a, u_int ring_nr, int do_lock)
@@ -168,54 +148,40 @@
 	struct netmap_adapter *na = NA(adapter->ifp);
 	struct netmap_kring *kring = &na->tx_rings[ring_nr];
 	struct netmap_ring *ring = kring->ring;
-	int j, k, n, lim = kring->nkr_num_slots - 1;
+	int j, k, l, n = 0, lim = kring->nkr_num_slots - 1;
 
 	/* generate an interrupt approximately every half ring */
 	int report_frequency = kring->nkr_num_slots >> 1;
 
-	k = ring->cur;	/* ring is not protected by any lock */
-	if ( (kring->nr_kflags & NR_REINIT) || k > lim)
+	k = ring->cur;
+	if (k > lim)
 		return netmap_ring_reinit(kring);
 
 	if (do_lock)
 		IGB_TX_LOCK(txr);
 	bus_dmamap_sync(txr->txdma.dma_tag, txr->txdma.dma_map,
-			BUS_DMASYNC_POSTREAD);
-
-	/* record completed transmissions. TODO
-	 *
-	 * Instead of reading from the TDH register, we could and try to check
-	 * the status bit of descriptor packets.
-	 */
-	j = E1000_READ_REG(&adapter->hw, E1000_TDH(ring_nr));
-	if (j >= kring->nkr_num_slots) /* XXX can it happen ? */
-		j -= kring->nkr_num_slots;
-	int delta = j - txr->next_to_clean;
-	if (delta) {
-		/* new tx were completed */
-		if (delta < 0)
-			delta += kring->nkr_num_slots;
-		txr->next_to_clean = j;
-		kring->nr_hwavail += delta;
-	}
+	    BUS_DMASYNC_POSTREAD);
 
 	/* update avail to what the hardware knows */
 	ring->avail = kring->nr_hwavail;
 
-	j = kring->nr_hwcur;
+	j = kring->nr_hwcur; /* netmap ring index */
 	if (j != k) {	/* we have new packets to send */
 		u32 olinfo_status = 0;
-		n = 0;
+		int n = 0;
 
+		l = j - kring->nkr_hwofs; /* NIC ring index */
+		if (l < 0)
+			l += lim + 1;
 		/* 82575 needs the queue index added */
 		if (adapter->hw.mac.type == e1000_82575)
 			olinfo_status |= txr->me << 4;
 
 		while (j != k) {
 			struct netmap_slot *slot = &ring->slot[j];
-			struct igb_tx_buffer *txbuf = &txr->tx_buffers[j];
+			struct igb_tx_buffer *txbuf = &txr->tx_buffers[l];
 			union e1000_adv_tx_desc *curr =
-				(union e1000_adv_tx_desc *)&txr->tx_base[j];
+			    (union e1000_adv_tx_desc *)&txr->tx_base[l];
 			void *addr = NMB(slot);
 			int flags = ((slot->flags & NS_REPORT) ||
 				j == 0 || j == report_frequency) ?
@@ -229,6 +195,7 @@
 			}
 
 			slot->flags &= ~NS_REPORT;
+			// XXX do we need to set the address ?
 			curr->read.buffer_addr = htole64(vtophys(addr));
 			curr->read.olinfo_status =
 			    htole32(olinfo_status |
@@ -239,7 +206,7 @@
 				    E1000_ADVTXD_DCMD_DEXT |
 				    E1000_ADVTXD_DCMD_EOP | flags);
 			if (slot->flags & NS_BUF_CHANGED) {
-				/* buffer has changed, unload and reload map */
+				/* buffer has changed, reload map */
 				netmap_reload_map(txr->txtag, txbuf->map,
 					addr, na->buff_size);
 				slot->flags &= ~NS_BUF_CHANGED;
@@ -248,22 +215,40 @@
 			bus_dmamap_sync(txr->txtag, txbuf->map,
 				BUS_DMASYNC_PREWRITE);
 			j = (j == lim) ? 0 : j + 1;
+			l = (l == lim) ? 0 : l + 1;
 			n++;
 		}
 		kring->nr_hwcur = k;
 
 		/* decrease avail by number of sent packets */
-		ring->avail -= n;
-		kring->nr_hwavail = ring->avail;
+		kring->nr_hwavail -= n;
+		ring->avail = kring->nr_hwavail;
 
-		/* Set the watchdog */
+		/* Set the watchdog XXX ? */
 		txr->queue_status = IGB_QUEUE_WORKING;
 		txr->watchdog_time = ticks;
 
 		bus_dmamap_sync(txr->txdma.dma_tag, txr->txdma.dma_map,
-			BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
+		    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
 
-		E1000_WRITE_REG(&adapter->hw, E1000_TDT(txr->me), k);
+		E1000_WRITE_REG(&adapter->hw, E1000_TDT(txr->me), l);
+	}
+	if (n == 0 || kring->nr_hwavail < 1) {
+		int delta;
+
+		/* record completed transmission using TDH */
+		l = E1000_READ_REG(&adapter->hw, E1000_TDH(ring_nr));
+		if (l >= kring->nkr_num_slots) /* XXX can it happen ? */
+			l -= kring->nkr_num_slots;
+		delta = l - txr->next_to_clean;
+		if (delta) {
+			/* new tx were completed */
+			if (delta < 0)
+				delta += kring->nkr_num_slots;
+			txr->next_to_clean = l;
+			kring->nr_hwavail += delta;
+			ring->avail = kring->nr_hwavail;
+		}
 	}
 	if (do_lock)
 		IGB_TX_UNLOCK(txr);
@@ -273,15 +258,6 @@
 
 /*
  * Reconcile kernel and user view of the receive ring.
- *
- * Userspace has read rx slots up to cur (excluded).
- * The last unread slot previously known to the kernel was nr_hwcur,
- * and the last interrupt reported nr_hwavail slots available.
- * We must subtract the newly consumed slots (cur - nr_hwcur)
- * from nr_hwavail, clearing the descriptors for the next
- * read, tell the hardware that they are available,
- * and set nr_hwcur = cur and avail = nr_hwavail.
- * issuing a dmamap_sync on all slots.
  */
 static int
 igb_netmap_rxsync(void *a, u_int ring_nr, int do_lock)
@@ -291,10 +267,10 @@
 	struct netmap_adapter *na = NA(adapter->ifp);
 	struct netmap_kring *kring = &na->rx_rings[ring_nr];
 	struct netmap_ring *ring = kring->ring;
-	int j, k, n, lim = kring->nkr_num_slots - 1;
+	int j, k, l, n, lim = kring->nkr_num_slots - 1;
 
-	k = ring->cur;	/* ring is not protected by any lock */
-	if ( (kring->nr_kflags & NR_REINIT) || k > lim)
+	k = ring->cur;
+	if (k > lim)
 		return netmap_ring_reinit(kring);
 
 	if (do_lock)
@@ -304,9 +280,12 @@
 	bus_dmamap_sync(rxr->rxdma.dma_tag, rxr->rxdma.dma_map,
 	    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
 
-	j = rxr->next_to_check;
+	l = rxr->next_to_check;
+	j = l + kring->nkr_hwofs;
+	if (j > lim)
+		j -= lim + 1;
 	for (n = 0; ; n++) {
-		union e1000_adv_rx_desc *curr = &rxr->rx_base[j];
+		union e1000_adv_rx_desc *curr = &rxr->rx_base[l];
 		uint32_t staterr = le32toh(curr->wb.upper.status_error);
 
 		if ((staterr & E1000_RXD_STAT_DD) == 0)
@@ -314,15 +293,13 @@
 		ring->slot[j].len = le16toh(curr->wb.upper.length);
 		
 		bus_dmamap_sync(rxr->ptag,
-			rxr->rx_buffers[j].pmap, BUS_DMASYNC_POSTREAD);
+			rxr->rx_buffers[l].pmap, BUS_DMASYNC_POSTREAD);
 		j = (j == lim) ? 0 : j + 1;
+		l = (l == lim) ? 0 : l + 1;
 	}
 	if (n) {
-		rxr->next_to_check = j;
+		rxr->next_to_check = l;
 		kring->nr_hwavail += n;
-		if (kring->nr_hwavail >= lim - 10) {
-			ND("rx ring %d almost full %d", ring_nr, kring->nr_hwavail);
-		}
 	}
 
 	/* skip past packets that userspace has already processed,
@@ -332,12 +309,15 @@
 	 * Also increase nr_hwavail
 	 */
 	j = kring->nr_hwcur;
+	l = kring->nr_hwcur - kring->nkr_hwofs;
+	if (l < 0)
+		l += lim + 1;
 	if (j != k) {	/* userspace has read some packets. */
 		n = 0;
 		while (j != k) {
 			struct netmap_slot *slot = ring->slot + j;
-			union e1000_adv_rx_desc *curr = &rxr->rx_base[j];
-			struct igb_rx_buf *rxbuf = rxr->rx_buffers + j;
+			union e1000_adv_rx_desc *curr = &rxr->rx_base[l];
+			struct igb_rx_buf *rxbuf = rxr->rx_buffers + l;
 			void *addr = NMB(slot);
 
 			if (addr == netmap_buffer_base) { /* bad buf */
@@ -358,6 +338,7 @@
 				BUS_DMASYNC_PREREAD);
 
 			j = (j == lim) ? 0 : j + 1;
+			l = (l == lim) ? 0 : l + 1;
 			n++;
 		}
 		kring->nr_hwavail -= n;
@@ -365,10 +346,10 @@
 		bus_dmamap_sync(rxr->rxdma.dma_tag, rxr->rxdma.dma_map,
 			BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
 		/* IMPORTANT: we must leave one free slot in the ring,
-		 * so move j back by one unit
+		 * so move l back by one unit
 		 */
-		j = (j == 0) ? lim : j - 1;
-		E1000_WRITE_REG(&adapter->hw, E1000_RDT(rxr->me), j);
+		l = (l == 0) ? lim : l - 1;
+		E1000_WRITE_REG(&adapter->hw, E1000_RDT(rxr->me), l);
 	}
 	/* tell userspace that there are new packets */
 	ring->avail = kring->nr_hwavail ;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/netmap/if_lem_netmap.h
--- a/head/sys/dev/netmap/if_lem_netmap.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/netmap/if_lem_netmap.h	Tue Dec 06 20:26:16 2011 +0200
@@ -24,10 +24,13 @@
  */
 
 /*
- * $FreeBSD: head/sys/dev/netmap/if_lem_netmap.h 227614 2011-11-17 12:17:39Z luigi $
- * $Id: if_lem_netmap.h 9662 2011-11-16 13:18:06Z luigi $
+ * $FreeBSD: head/sys/dev/netmap/if_lem_netmap.h 228276 2011-12-05 12:06:53Z luigi $
+ * $Id: if_lem_netmap.h 9802 2011-12-02 18:42:37Z luigi $
  *
  * netmap support for if_lem.c
+ *
+ * For structure and details on the individual functions please see
+ * ixgbe_netmap.h
  */
 
 #include <net/netmap.h>
@@ -59,7 +62,7 @@
 	na.nm_rxsync = lem_netmap_rxsync;
 	na.nm_lock = lem_netmap_lock_wrapper;
 	na.nm_register = lem_netmap_reg;
-	na.buff_size = MCLBYTES;
+	na.buff_size = NETMAP_BUF_SIZE;
 	netmap_attach(&na, 1);
 }
 
@@ -94,203 +97,6 @@
 
 
 /*
- * Reconcile kernel and user view of the transmit ring. see ixgbe.c
- */
-static int
-lem_netmap_txsync(void *a, u_int ring_nr, int do_lock)
-{
-	struct adapter *adapter = a;
-	struct netmap_adapter *na = NA(adapter->ifp);
-	struct netmap_kring *kring = &na->tx_rings[0];
-	struct netmap_ring *ring = kring->ring;
-	int j, k, n, lim = kring->nkr_num_slots - 1;
-
-	/* generate an interrupt approximately every half ring */
-	int report_frequency = kring->nkr_num_slots >> 1;
-
-	k = ring->cur;
-	if ( (kring->nr_kflags & NR_REINIT) || k > lim)
-		return netmap_ring_reinit(kring);
-
-	if (do_lock)
-		EM_TX_LOCK(adapter);
-	bus_dmamap_sync(adapter->txdma.dma_tag, adapter->txdma.dma_map,
-			BUS_DMASYNC_POSTREAD);
-
-	/* record completed transmissions TODO
-	 *
-	 * instead of using TDH, we could read the transmitted status bit.
-	 */
-	j = E1000_READ_REG(&adapter->hw, E1000_TDH(0));
-	if (j >= kring->nkr_num_slots) { /* can it happen ? */
-		D("bad TDH %d", j);
-		j -= kring->nkr_num_slots;
-	}
-	int delta = j - adapter->next_tx_to_clean;
-	if (delta) {
-		if (delta < 0)
-			delta += kring->nkr_num_slots;
-		adapter->next_tx_to_clean = j;
-		kring->nr_hwavail += delta;
-	}
-
-	/* update avail to what the hardware knows */
-	ring->avail = kring->nr_hwavail;
-
-	j = kring->nr_hwcur;
-	if (j != k) {	/* we have new packets to send */
-		n = 0;
-		while (j != k) {
-			struct netmap_slot *slot = &ring->slot[j];
-			struct e1000_tx_desc *curr = &adapter->tx_desc_base[j];
-			struct em_buffer *txbuf = &adapter->tx_buffer_area[j];
-			void *addr = NMB(slot);
-			int flags = ((slot->flags & NS_REPORT) ||
-				j == 0 || j == report_frequency) ?
-					E1000_TXD_CMD_RS : 0;
-			int len = slot->len;
-
-			if (addr == netmap_buffer_base || len > NETMAP_BUF_SIZE) {
-				if (do_lock)
-					EM_TX_UNLOCK(adapter);
-				return netmap_ring_reinit(kring);
-			}
-
-			curr->upper.data = 0;
-			/* always interrupt. XXX make it conditional */
-			curr->lower.data =
-			    htole32( adapter->txd_cmd | len |
-				(E1000_TXD_CMD_EOP | flags) );
-			if (slot->flags & NS_BUF_CHANGED) {
-				curr->buffer_addr = htole64(vtophys(addr));
-				/* buffer has changed, unload and reload map */
-				netmap_reload_map(adapter->txtag, txbuf->map,
-					addr, na->buff_size);
-				slot->flags &= ~NS_BUF_CHANGED;
-			}
-
-			bus_dmamap_sync(adapter->txtag, txbuf->map,
-				BUS_DMASYNC_PREWRITE);
-			j = (j == lim) ? 0 : j + 1;
-			n++;
-		}
-		kring->nr_hwcur = ring->cur;
-
-		/* decrease avail by number of sent packets */
-		ring->avail -= n;
-		kring->nr_hwavail = ring->avail;
-
-		bus_dmamap_sync(adapter->txdma.dma_tag, adapter->txdma.dma_map,
-				BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
-
-		E1000_WRITE_REG(&adapter->hw, E1000_TDT(0), ring->cur);
-	}
-	if (do_lock)
-		EM_TX_UNLOCK(adapter);
-	return 0;
-}
-
-
-/*
- * Reconcile kernel and user view of the receive ring. see ixgbe.c
- */
-static int
-lem_netmap_rxsync(void *a, u_int ring_nr, int do_lock)
-{
-	struct adapter *adapter = a;
-	struct netmap_adapter *na = NA(adapter->ifp);
-	struct netmap_kring *kring = &na->rx_rings[0];
-	struct netmap_ring *ring = kring->ring;
-	int j, k, n, lim = kring->nkr_num_slots - 1;
-
-	k = ring->cur;
-	if ( (kring->nr_kflags & NR_REINIT) || k > lim)
-		return netmap_ring_reinit(kring);
-
-	if (do_lock)
-		EM_RX_LOCK(adapter);
-	/* XXX check sync modes */
-	bus_dmamap_sync(adapter->rxdma.dma_tag, adapter->rxdma.dma_map,
-			BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
-
-	/* acknowldge all the received packets. */
-	j = adapter->next_rx_desc_to_check;
-	for (n = 0; ; n++) {
-		struct e1000_rx_desc *curr = &adapter->rx_desc_base[j];
-		int len = le16toh(adapter->rx_desc_base[j].length) - 4; // CRC
-
-		if ((curr->status & E1000_RXD_STAT_DD) == 0)
-			break;
-
-		if (len < 0) {
-			D("bogus pkt size at %d", j);
-			len = 0;
-		}
-		ring->slot[j].len = len;
-		bus_dmamap_sync(adapter->rxtag, adapter->rx_buffer_area[j].map,
-			BUS_DMASYNC_POSTREAD);
-		j = (j == lim) ? 0 : j + 1;
-	}
-	if (n) {
-		adapter->next_rx_desc_to_check = j;
-		kring->nr_hwavail += n;
-	}
-
-	/* skip past packets that userspace has already processed,
-	 * making them available for reception. We don't need to set
-	 * the length as it is the same for all slots.
-	 */
-	j = kring->nr_hwcur;
-	if (j != k) {	/* userspace has read some packets. */
-		n = 0;
-		while (j != k) {
-			struct netmap_slot *slot = &ring->slot[j];
-			struct e1000_rx_desc *curr = &adapter->rx_desc_base[j];
-			struct em_buffer *rxbuf = &adapter->rx_buffer_area[j];
-			void *addr = NMB(slot);
-
-			if (addr == netmap_buffer_base) { /* bad buf */
-				if (do_lock)
-					EM_RX_UNLOCK(adapter);
-				return netmap_ring_reinit(kring);
-			}
-			curr = &adapter->rx_desc_base[j];
-			curr->status = 0;
-			if (slot->flags & NS_BUF_CHANGED) {
-				curr->buffer_addr = htole64(vtophys(addr));
-				/* buffer has changed, unload and reload map */
-				netmap_reload_map(adapter->rxtag, rxbuf->map,
-					addr, na->buff_size);
-				slot->flags &= ~NS_BUF_CHANGED;
-			}
-
-			bus_dmamap_sync(adapter->rxtag, rxbuf->map,
-				BUS_DMASYNC_PREREAD);
-
-			j = (j == lim) ? 0 : j + 1;
-			n++;
-		}
-		kring->nr_hwavail -= n;
-		kring->nr_hwcur = ring->cur;
-		bus_dmamap_sync(adapter->rxdma.dma_tag, adapter->rxdma.dma_map,
-			BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
-		/*
-		 * IMPORTANT: we must leave one free slot in the ring,
-		 * so move j back by one unit
-		 */
-		j = (j == 0) ? lim : j - 1;
-		E1000_WRITE_REG(&adapter->hw, E1000_RDT(0), j);
-	}
-
-	/* tell userspace that there are new packets */
-	ring->avail = kring->nr_hwavail ;
-	if (do_lock)
-		EM_RX_UNLOCK(adapter);
-	return 0;
-}
-
-
-/*
  * Register/unregister routine
  */
 static int
@@ -300,7 +106,7 @@
 	struct netmap_adapter *na = NA(ifp);
 	int error = 0;
 
-	if (!na)
+	if (na == NULL)
 		return EINVAL;
 
 	lem_disable_intr(adapter);
@@ -309,7 +115,7 @@
 	ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
 
 	/* lem_netmap_block_tasks(adapter); */
-#ifndef EM_LEGACY_IRQ
+#ifndef EM_LEGACY_IRQ // XXX do we need this ?
 	taskqueue_block(adapter->tq);
 	taskqueue_drain(adapter->tq, &adapter->rxtx_task);
 	taskqueue_drain(adapter->tq, &adapter->link_task);
@@ -337,8 +143,217 @@
 	}
 
 #ifndef EM_LEGACY_IRQ
-	taskqueue_unblock(adapter->tq);
+	taskqueue_unblock(adapter->tq); // XXX do we need this ?
 #endif /* !EM_LEGCY_IRQ */
 
 	return (error);
 }
+
+
+/*
+ * Reconcile kernel and user view of the transmit ring.
+ */
+static int
+lem_netmap_txsync(void *a, u_int ring_nr, int do_lock)
+{
+	struct adapter *adapter = a;
+	struct netmap_adapter *na = NA(adapter->ifp);
+	struct netmap_kring *kring = &na->tx_rings[0];
+	struct netmap_ring *ring = kring->ring;
+	int j, k, l, n = 0, lim = kring->nkr_num_slots - 1;
+
+	/* generate an interrupt approximately every half ring */
+	int report_frequency = kring->nkr_num_slots >> 1;
+
+	k = ring->cur;
+	if (k > lim)
+		return netmap_ring_reinit(kring);
+
+	if (do_lock)
+		EM_TX_LOCK(adapter);
+	bus_dmamap_sync(adapter->txdma.dma_tag, adapter->txdma.dma_map,
+			BUS_DMASYNC_POSTREAD);
+
+	/* update avail to what the hardware knows */
+	ring->avail = kring->nr_hwavail;
+
+	j = kring->nr_hwcur; /* points into the netmap ring */
+	if (j != k) {	/* we have new packets to send */
+		l = j - kring->nkr_hwofs; /* points into the NIC ring */
+		if (l < 0)
+			l += lim + 1;
+		while (j != k) {
+			struct netmap_slot *slot = &ring->slot[j];
+			struct e1000_tx_desc *curr = &adapter->tx_desc_base[l];
+			struct em_buffer *txbuf = &adapter->tx_buffer_area[l];
+			void *addr = NMB(slot);
+			int flags = ((slot->flags & NS_REPORT) ||
+				j == 0 || j == report_frequency) ?
+					E1000_TXD_CMD_RS : 0;
+			int len = slot->len;
+
+			if (addr == netmap_buffer_base || len > NETMAP_BUF_SIZE) {
+				if (do_lock)
+					EM_TX_UNLOCK(adapter);
+				return netmap_ring_reinit(kring);
+			}
+
+			slot->flags &= ~NS_REPORT;
+			curr->upper.data = 0;
+			curr->lower.data =
+			    htole32( adapter->txd_cmd | len |
+				(E1000_TXD_CMD_EOP | flags) );
+			if (slot->flags & NS_BUF_CHANGED) {
+				curr->buffer_addr = htole64(vtophys(addr));
+				/* buffer has changed, reload map */
+				netmap_reload_map(adapter->txtag, txbuf->map,
+				    addr, na->buff_size);
+				slot->flags &= ~NS_BUF_CHANGED;
+			}
+
+			bus_dmamap_sync(adapter->txtag, txbuf->map,
+			    BUS_DMASYNC_PREWRITE);
+			j = (j == lim) ? 0 : j + 1;
+			l = (l == lim) ? 0 : l + 1;
+			n++;
+		}
+		kring->nr_hwcur = k;
+
+		/* decrease avail by number of sent packets */
+		kring->nr_hwavail -= n;
+		ring->avail = kring->nr_hwavail;
+
+		bus_dmamap_sync(adapter->txdma.dma_tag, adapter->txdma.dma_map,
+		    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
+
+		E1000_WRITE_REG(&adapter->hw, E1000_TDT(0), l);
+	}
+
+	if (n == 0 || kring->nr_hwavail < 1) {
+		int delta;
+
+		/* record completed transmissions using TDH */
+		l = E1000_READ_REG(&adapter->hw, E1000_TDH(0));
+		if (l >= kring->nkr_num_slots) { /* can it happen ? */
+			D("bad TDH %d", l);
+			l -= kring->nkr_num_slots;
+		}
+		delta = l - adapter->next_tx_to_clean;
+		if (delta) {
+			if (delta < 0)
+				delta += kring->nkr_num_slots;
+			adapter->next_tx_to_clean = l;
+			kring->nr_hwavail += delta;
+			ring->avail = kring->nr_hwavail;
+		}
+	}
+	if (do_lock)
+		EM_TX_UNLOCK(adapter);
+	return 0;
+}
+
+
+/*
+ * Reconcile kernel and user view of the receive ring.
+ */
+static int
+lem_netmap_rxsync(void *a, u_int ring_nr, int do_lock)
+{
+	struct adapter *adapter = a;
+	struct netmap_adapter *na = NA(adapter->ifp);
+	struct netmap_kring *kring = &na->rx_rings[0];
+	struct netmap_ring *ring = kring->ring;
+	int j, k, l, n, lim = kring->nkr_num_slots - 1;
+
+	k = ring->cur;
+	if (k > lim)
+		return netmap_ring_reinit(kring);
+
+	if (do_lock)
+		EM_RX_LOCK(adapter);
+	/* XXX check sync modes */
+	bus_dmamap_sync(adapter->rxdma.dma_tag, adapter->rxdma.dma_map,
+			BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
+
+	/* import newly received packets into the netmap ring */
+	l = adapter->next_rx_desc_to_check; /* points into the NIC ring */
+	j = l + kring->nkr_hwofs; /* points into the netmap ring */
+	if (j > lim)
+		j -= lim + 1;
+	for (n = 0; ; n++) {
+		struct e1000_rx_desc *curr = &adapter->rx_desc_base[l];
+		int len;
+
+		if ((curr->status & E1000_RXD_STAT_DD) == 0)
+			break;
+		len = le16toh(curr->length) - 4; // CRC
+
+		if (len < 0) {
+			D("bogus pkt size at %d", j);
+			len = 0;
+		}
+		ring->slot[j].len = len;
+		bus_dmamap_sync(adapter->rxtag, adapter->rx_buffer_area[l].map,
+		    BUS_DMASYNC_POSTREAD);
+		j = (j == lim) ? 0 : j + 1;
+		l = (l == lim) ? 0 : l + 1;
+	}
+	if (n) {
+		adapter->next_rx_desc_to_check = l;
+		kring->nr_hwavail += n;
+	}
+
+	/* skip past packets that userspace has already processed */
+	j = kring->nr_hwcur; /* netmap ring index */
+	if (j != k) {	/* userspace has read some packets. */
+		n = 0;
+		l = j - kring->nkr_hwofs; /* NIC ring index */
+		if (l < 0)
+			l += lim + 1;
+		while (j != k) {
+			struct netmap_slot *slot = &ring->slot[j];
+			struct e1000_rx_desc *curr = &adapter->rx_desc_base[l];
+			struct em_buffer *rxbuf = &adapter->rx_buffer_area[l];
+			void *addr = NMB(slot);
+
+			if (addr == netmap_buffer_base) { /* bad buf */
+				if (do_lock)
+					EM_RX_UNLOCK(adapter);
+				return netmap_ring_reinit(kring);
+			}
+			curr->status = 0;
+			if (slot->flags & NS_BUF_CHANGED) {
+				curr->buffer_addr = htole64(vtophys(addr));
+				/* buffer has changed, and reload map */
+				netmap_reload_map(adapter->rxtag, rxbuf->map,
+				    addr, na->buff_size);
+				slot->flags &= ~NS_BUF_CHANGED;
+			}
+
+			bus_dmamap_sync(adapter->rxtag, rxbuf->map,
+			    BUS_DMASYNC_PREREAD);
+
+			j = (j == lim) ? 0 : j + 1;
+			l = (l == lim) ? 0 : l + 1;
+			n++;
+		}
+		kring->nr_hwavail -= n;
+		kring->nr_hwcur = k;
+		bus_dmamap_sync(adapter->rxdma.dma_tag, adapter->rxdma.dma_map,
+		    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
+		/*
+		 * IMPORTANT: we must leave one free slot in the ring,
+		 * so move l back by one unit
+		 */
+		l = (l == 0) ? lim : l - 1;
+		E1000_WRITE_REG(&adapter->hw, E1000_RDT(0), l);
+	}
+
+	/* tell userspace that there are new packets */
+	ring->avail = kring->nr_hwavail ;
+	if (do_lock)
+		EM_RX_UNLOCK(adapter);
+	return 0;
+}
+
+
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/netmap/if_re_netmap.h
--- a/head/sys/dev/netmap/if_re_netmap.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/netmap/if_re_netmap.h	Tue Dec 06 20:26:16 2011 +0200
@@ -24,8 +24,8 @@
  */
 
 /*
- * $FreeBSD: head/sys/dev/netmap/if_re_netmap.h 227614 2011-11-17 12:17:39Z luigi $
- * $Id: if_re_netmap.h 9662 2011-11-16 13:18:06Z luigi $
+ * $FreeBSD: head/sys/dev/netmap/if_re_netmap.h 228276 2011-12-05 12:06:53Z luigi $
+ * $Id: if_re_netmap.h 9802 2011-12-02 18:42:37Z luigi $
  *
  * netmap support for if_re
  */
@@ -56,7 +56,7 @@
 	na.nm_rxsync = re_netmap_rxsync;
 	na.nm_lock = re_netmap_lock_wrapper;
 	na.nm_register = re_netmap_reg;
-	na.buff_size = MCLBYTES;
+	na.buff_size = NETMAP_BUF_SIZE;
 	netmap_attach(&na, 1);
 }
 
@@ -99,7 +99,7 @@
 	struct netmap_adapter *na = NA(ifp);
 	int error = 0;
 
-	if (!na)
+	if (na == NULL)
 		return EINVAL;
 	/* Tell the stack that the interface is no longer active */
 	ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
@@ -109,9 +109,8 @@
 	if (onoff) {
 		ifp->if_capenable |= IFCAP_NETMAP;
 
-		/* save if_transmit and restore it */
+		/* save if_transmit to restore it later */
 		na->if_transmit = ifp->if_transmit;
-		/* XXX if_start and if_qflush ??? */
 		ifp->if_transmit = netmap_start;
 
 		re_init_locked(adapter);
@@ -127,23 +126,12 @@
 		ifp->if_capenable &= ~IFCAP_NETMAP;
 		re_init_locked(adapter);	/* also enables intr */
 	}
-    return (error);
-
+	return (error);
 }
 
 
 /*
  * Reconcile kernel and user view of the transmit ring.
- *
- * Userspace has filled tx slots up to cur (excluded).
- * The last unused slot previously known to the kernel was nr_hwcur,
- * and the last interrupt reported nr_hwavail slots available
- * (using the special value -1 to indicate idle transmit ring).
- * The function must first update avail to what the kernel
- * knows (translating the -1 to nkr_num_slots - 1),
- * subtract the newly used slots (cur - nr_hwcur)
- * from both avail and nr_hwavail, and set nr_hwcur = cur
- * issuing a dmamap_sync on all slots.
  */
 static int
 re_netmap_txsync(void *a, u_int ring_nr, int do_lock)
@@ -153,10 +141,10 @@
 	struct netmap_adapter *na = NA(sc->rl_ifp);
 	struct netmap_kring *kring = &na->tx_rings[ring_nr];
 	struct netmap_ring *ring = kring->ring;
-	int j, k, n, lim = kring->nkr_num_slots - 1;
+	int j, k, l, n, lim = kring->nkr_num_slots - 1;
 
 	k = ring->cur;
-	if ( (kring->nr_kflags & NR_REINIT) || k > lim)
+	if (k > lim)
 		return netmap_ring_reinit(kring);
 
 	if (do_lock)
@@ -167,17 +155,18 @@
             sc->rl_ldata.rl_tx_list_map,
             BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
 
+	/* XXX move after the transmissions */
 	/* record completed transmissions */
-        for (n = 0, j = sc->rl_ldata.rl_tx_considx;
-	    j != sc->rl_ldata.rl_tx_prodidx;
-	    n++, j = RL_TX_DESC_NXT(sc, j)) {
+        for (n = 0, l = sc->rl_ldata.rl_tx_considx;
+	    l != sc->rl_ldata.rl_tx_prodidx;
+	    n++, l = RL_TX_DESC_NXT(sc, l)) {
 		uint32_t cmdstat =
-			le32toh(sc->rl_ldata.rl_tx_list[j].rl_cmdstat);
+			le32toh(sc->rl_ldata.rl_tx_list[l].rl_cmdstat);
 		if (cmdstat & RL_TDESC_STAT_OWN)
 			break;
 	}
 	if (n > 0) {
-		sc->rl_ldata.rl_tx_considx = j;
+		sc->rl_ldata.rl_tx_considx = l;
 		sc->rl_ldata.rl_tx_free += n;
 		kring->nr_hwavail += n;
 	}
@@ -185,13 +174,13 @@
 	/* update avail to what the hardware knows */
 	ring->avail = kring->nr_hwavail;
 	
-	/* we trust prodidx, not hwcur */
-	j = kring->nr_hwcur = sc->rl_ldata.rl_tx_prodidx;
+	j = kring->nr_hwcur;
 	if (j != k) {	/* we have new packets to send */
 		n = 0;
+		l = sc->rl_ldata.rl_tx_prodidx;
 		while (j != k) {
 			struct netmap_slot *slot = &ring->slot[j];
-			struct rl_desc *desc = &sc->rl_ldata.rl_tx_list[j];
+			struct rl_desc *desc = &sc->rl_ldata.rl_tx_list[l];
 			int cmd = slot->len | RL_TDESC_CMD_EOF |
 				RL_TDESC_CMD_OWN | RL_TDESC_CMD_SOF ;
 			void *addr = NMB(slot);
@@ -200,10 +189,11 @@
 			if (addr == netmap_buffer_base || len > NETMAP_BUF_SIZE) {
 				if (do_lock)
 					RL_UNLOCK(sc);
+				// XXX what about prodidx ?
 				return netmap_ring_reinit(kring);
 			}
 			
-			if (j == lim)	/* mark end of ring */
+			if (l == lim)	/* mark end of ring */
 				cmd |= RL_TDESC_CMD_EOR;
 
 			if (slot->flags & NS_BUF_CHANGED) {
@@ -212,17 +202,19 @@
 				desc->rl_bufaddr_hi = htole32(RL_ADDR_HI(paddr));
 				/* buffer has changed, unload and reload map */
 				netmap_reload_map(sc->rl_ldata.rl_tx_mtag,
-					txd[j].tx_dmamap, addr, na->buff_size);
+					txd[l].tx_dmamap, addr, na->buff_size);
 				slot->flags &= ~NS_BUF_CHANGED;
 			}
 			slot->flags &= ~NS_REPORT;
 			desc->rl_cmdstat = htole32(cmd);
 			bus_dmamap_sync(sc->rl_ldata.rl_tx_mtag,
-				txd[j].tx_dmamap, BUS_DMASYNC_PREWRITE);
+				txd[l].tx_dmamap, BUS_DMASYNC_PREWRITE);
 			j = (j == lim) ? 0 : j + 1;
+			l = (l == lim) ? 0 : l + 1;
 			n++;
 		}
-		sc->rl_ldata.rl_tx_prodidx = kring->nr_hwcur = ring->cur;
+		sc->rl_ldata.rl_tx_prodidx = l;
+		kring->nr_hwcur = k;
 
 		/* decrease avail by number of sent packets */
 		ring->avail -= n;
@@ -243,15 +235,6 @@
 
 /*
  * Reconcile kernel and user view of the receive ring.
- *
- * Userspace has read rx slots up to cur (excluded).
- * The last unread slot previously known to the kernel was nr_hwcur,
- * and the last interrupt reported nr_hwavail slots available.
- * We must subtract the newly consumed slots (cur - nr_hwcur)
- * from nr_hwavail, clearing the descriptors for the next
- * read, tell the hardware that they are available,
- * and set nr_hwcur = cur and avail = nr_hwavail.
- * issuing a dmamap_sync on all slots.
  */
 static int
 re_netmap_rxsync(void *a, u_int ring_nr, int do_lock)
@@ -261,10 +244,10 @@
 	struct netmap_adapter *na = NA(sc->rl_ifp);
 	struct netmap_kring *kring = &na->rx_rings[ring_nr];
 	struct netmap_ring *ring = kring->ring;
-	int j, k, n, lim = kring->nkr_num_slots - 1;
+	int j, k, l, n, lim = kring->nkr_num_slots - 1;
 
 	k = ring->cur;
-	if ( (kring->nr_kflags & NR_REINIT) || k > lim)
+	if (k > lim)
 		return netmap_ring_reinit(kring);
 
 	if (do_lock)
@@ -280,9 +263,10 @@
 	 * cleared (all buffers could have it cleared. The easiest one
 	 * is to limit the amount of data reported up to 'lim'
 	 */
-	j = sc->rl_ldata.rl_rx_prodidx;
+	l = sc->rl_ldata.rl_rx_prodidx; /* next pkt to check */
+	j = l + kring->nkr_hwofs;
 	for (n = kring->nr_hwavail; n < lim ; n++) {
-		struct rl_desc *cur_rx = &sc->rl_ldata.rl_rx_list[j];
+		struct rl_desc *cur_rx = &sc->rl_ldata.rl_rx_list[l];
 		uint32_t rxstat = le32toh(cur_rx->rl_cmdstat);
 		uint32_t total_len;
 
@@ -294,11 +278,12 @@
 		kring->ring->slot[j].len = total_len;
 		/*  sync was in re_newbuf() */
 		bus_dmamap_sync(sc->rl_ldata.rl_rx_mtag,
-		    rxd[j].rx_dmamap, BUS_DMASYNC_POSTREAD);
-		j = RL_RX_DESC_NXT(sc, j);
+		    rxd[l].rx_dmamap, BUS_DMASYNC_POSTREAD);
+		j = (j == lim) ? 0 : j + 1;
+		l = (l == lim) ? 0 : l + 1;
 	}
 	if (n != kring->nr_hwavail) {
-		sc->rl_ldata.rl_rx_prodidx = j;
+		sc->rl_ldata.rl_rx_prodidx = l;
 		sc->rl_ifp->if_ipackets += n - kring->nr_hwavail;
 		kring->nr_hwavail = n;
 	}
@@ -312,9 +297,12 @@
 	j = kring->nr_hwcur;
 	if (j != k) {	/* userspace has read some packets. */
 		n = 0;
+		l = kring->nr_hwcur - kring->nkr_hwofs;
+		if (l < 0)
+			l += lim + 1;
 		while (j != k) {
 			struct netmap_slot *slot = ring->slot + j;
-			struct rl_desc *desc = &sc->rl_ldata.rl_rx_list[j];
+			struct rl_desc *desc = &sc->rl_ldata.rl_rx_list[l];
 			int cmd = na->buff_size | RL_RDESC_CMD_OWN;
 			void *addr = NMB(slot);
 
@@ -324,7 +312,7 @@
 				return netmap_ring_reinit(kring);
 			}
 
-			if (j == lim)	/* mark end of ring */
+			if (l == lim)	/* mark end of ring */
 				cmd |= RL_RDESC_CMD_EOR;
 
 			desc->rl_cmdstat = htole32(cmd);
@@ -334,12 +322,13 @@
 				desc->rl_bufaddr_lo = htole32(RL_ADDR_LO(paddr));
 				desc->rl_bufaddr_hi = htole32(RL_ADDR_HI(paddr));
 				netmap_reload_map(sc->rl_ldata.rl_rx_mtag,
-					rxd[j].rx_dmamap, addr, na->buff_size);
+					rxd[l].rx_dmamap, addr, na->buff_size);
 				slot->flags &= ~NS_BUF_CHANGED;
 			}
 			bus_dmamap_sync(sc->rl_ldata.rl_rx_mtag,
-				rxd[j].rx_dmamap, BUS_DMASYNC_PREREAD);
+				rxd[l].rx_dmamap, BUS_DMASYNC_PREREAD);
 			j = (j == lim) ? 0 : j + 1;
+			l = (l == lim) ? 0 : l + 1;
 			n++;
 		}
 		kring->nr_hwavail -= n;
@@ -351,18 +340,22 @@
 		    BUS_DMASYNC_PREWRITE|BUS_DMASYNC_PREREAD);
 	}
 	/* tell userspace that there are new packets */
-	ring->avail = kring->nr_hwavail ;
+	ring->avail = kring->nr_hwavail;
 	if (do_lock)
 		RL_UNLOCK(sc);
 	return 0;
 }
 
+/*
+ * Additional routines to init the tx and rx rings.
+ * In other drivers we do that inline in the main code.
+ */
 static void
 re_netmap_tx_init(struct rl_softc *sc)
 {   
 	struct rl_txdesc *txd;
 	struct rl_desc *desc;
-	int i;
+	int i, n;
 	struct netmap_adapter *na = NA(sc->rl_ifp);
 	struct netmap_slot *slot = netmap_reset(na, NR_TX, 0, 0);
 
@@ -372,11 +365,20 @@
 	/* in netmap mode, overwrite addresses and maps */
 	txd = sc->rl_ldata.rl_tx_desc;
 	desc = sc->rl_ldata.rl_tx_list;
+	n = sc->rl_ldata.rl_tx_desc_cnt;
 
-	for (i = 0; i < sc->rl_ldata.rl_tx_desc_cnt; i++) {
-		void *addr = NMB(slot+i);
-		uint64_t paddr = vtophys(addr);
+	/* l points in the netmap ring, i points in the NIC ring */
+	for (i = 0; i < n; i++) {
+		void *addr;
+		uint64_t paddr;
+		struct netmap_kring *kring = &na->tx_rings[0];
+		int l = i + kring->nkr_hwofs;
 
+		if (l >= n)
+			l -= n;
+
+		addr = NMB(slot + l);
+		paddr = vtophys(addr);
 		desc[i].rl_bufaddr_lo = htole32(RL_ADDR_LO(paddr));
 		desc[i].rl_bufaddr_hi = htole32(RL_ADDR_HI(paddr));
 		netmap_load_map(sc->rl_ldata.rl_tx_mtag,
@@ -387,26 +389,39 @@
 static void
 re_netmap_rx_init(struct rl_softc *sc)
 {
-	/* slot is NULL if we are not in netmap mode */  
 	struct netmap_adapter *na = NA(sc->rl_ifp);
 	struct netmap_slot *slot = netmap_reset(na, NR_RX, 0, 0);
 	struct rl_desc *desc = sc->rl_ldata.rl_rx_list;
 	uint32_t cmdstat;
-	int i;
+	int i, n;
 
 	if (!slot)
 		return;
+	n = sc->rl_ldata.rl_rx_desc_cnt;
+	for (i = 0; i < n; i++) {
+		void *addr;
+		uint64_t paddr;
+		struct netmap_kring *kring = &na->rx_rings[0];
+		int l = i + kring->nkr_hwofs;
 
-	for (i = 0; i < sc->rl_ldata.rl_rx_desc_cnt; i++) {
-		void *addr = NMB(slot+i);
-		uint64_t paddr = vtophys(addr);
+		if (l >= n)
+			l -= n;
 
+		addr = NMB(slot + l);
+		paddr = vtophys(addr);
 		desc[i].rl_bufaddr_lo = htole32(RL_ADDR_LO(paddr));
 		desc[i].rl_bufaddr_hi = htole32(RL_ADDR_HI(paddr));
-		cmdstat = slot[i].len = na->buff_size; // XXX
-		if (i == sc->rl_ldata.rl_rx_desc_cnt - 1)
+		cmdstat = na->buff_size;
+		if (i == n - 1)
 			cmdstat |= RL_RDESC_CMD_EOR;
-		desc[i].rl_cmdstat = htole32(cmdstat | RL_RDESC_CMD_OWN);
+		/*
+		 * userspace knows that hwavail packets were ready before the
+		 * reset, so we need to tell the NIC that last hwavail
+		 * descriptors of the ring are still owned by the driver.
+		 */
+		if (i < n - 1 - kring->nr_hwavail) // XXX + 1 ?
+			cmdstat |= RL_RDESC_CMD_OWN;
+		desc[i].rl_cmdstat = htole32(cmdstat);
 
 		netmap_reload_map(sc->rl_ldata.rl_rx_mtag,
 			sc->rl_ldata.rl_rx_desc[i].rx_dmamap,
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/netmap/ixgbe_netmap.h
--- a/head/sys/dev/netmap/ixgbe_netmap.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/netmap/ixgbe_netmap.h	Tue Dec 06 20:26:16 2011 +0200
@@ -24,26 +24,49 @@
  */
 
 /*
- * $FreeBSD: head/sys/dev/netmap/ixgbe_netmap.h 227614 2011-11-17 12:17:39Z luigi $
- * $Id: ixgbe_netmap.h 9662 2011-11-16 13:18:06Z luigi $
+ * $FreeBSD: head/sys/dev/netmap/ixgbe_netmap.h 228276 2011-12-05 12:06:53Z luigi $
+ * $Id: ixgbe_netmap.h 9802 2011-12-02 18:42:37Z luigi $
  *
  * netmap modifications for ixgbe
+ *
+ * This file is meant to be a reference on how to implement
+ * netmap support for a network driver.
+ * This file contains code but only static or inline functions
+ * that are used by a single driver. To avoid replication of
+ * code we just #include it near the beginning of the
+ * standard driver.
  */
 
 #include <net/netmap.h>
 #include <sys/selinfo.h>
-// #include <vm/vm.h>
-// #include <vm/pmap.h>    /* vtophys ? */
+/*
+ * Some drivers may need the following headers. Others
+ * already include them by default
+
+#include <vm/vm.h>
+#include <vm/pmap.h>
+
+ */
+
 #include <dev/netmap/netmap_kern.h>
 
+/*
+ * prototypes for the new API calls that are used by the
+ * *_netmap_attach() routine.
+ */
 static int	ixgbe_netmap_reg(struct ifnet *, int onoff);
 static int	ixgbe_netmap_txsync(void *, u_int, int);
 static int	ixgbe_netmap_rxsync(void *, u_int, int);
 static void	ixgbe_netmap_lock_wrapper(void *, int, u_int);
 
 
-SYSCTL_NODE(_dev, OID_AUTO, ixgbe, CTLFLAG_RW, 0, "ixgbe card");
-
+/*
+ * The attach routine, called near the end of ixgbe_attach(),
+ * fills the parameters for netmap_attach() and calls it.
+ * It cannot fail, in the worst case (such as no memory)
+ * netmap mode will be disabled and the driver will only
+ * operate in standard mode.
+ */
 static void
 ixgbe_netmap_attach(struct adapter *adapter)
 {
@@ -52,7 +75,7 @@
 	bzero(&na, sizeof(na));
 
 	na.ifp = adapter->ifp;
-	na.separate_locks = 1;
+	na.separate_locks = 1;	/* this card has separate rx/tx locks */
 	na.num_tx_desc = adapter->num_tx_desc;
 	na.num_rx_desc = adapter->num_rx_desc;
 	na.nm_txsync = ixgbe_netmap_txsync;
@@ -60,17 +83,18 @@
 	na.nm_lock = ixgbe_netmap_lock_wrapper;
 	na.nm_register = ixgbe_netmap_reg;
 	/*
+	 * XXX where do we put this comment ?
 	 * adapter->rx_mbuf_sz is set by SIOCSETMTU, but in netmap mode
 	 * we allocate the buffers on the first register. So we must
 	 * disallow a SIOCSETMTU when if_capenable & IFCAP_NETMAP is set.
 	 */
-	na.buff_size = MCLBYTES;
+	na.buff_size = NETMAP_BUF_SIZE;
 	netmap_attach(&na, adapter->num_queues);
 }	
 
 
 /*
- * wrapper to export locks to the generic code
+ * wrapper to export locks to the generic netmap code.
  */
 static void
 ixgbe_netmap_lock_wrapper(void *_a, int what, u_int queueid)
@@ -102,8 +126,8 @@
 
 
 /*
- * support for netmap register/unregisted. We are already under core lock.
- * only called on the first init or the last unregister.
+ * Netmap register/unregister. We are already under core lock.
+ * Only called on the first register or the last unregister.
  */
 static int
 ixgbe_netmap_reg(struct ifnet *ifp, int onoff)
@@ -112,7 +136,7 @@
 	struct netmap_adapter *na = NA(ifp);
 	int error = 0;
 
-	if (!na)
+	if (!na) /* probably, netmap_attach() failed */
 		return EINVAL;
 
 	ixgbe_disable_intr(adapter);
@@ -120,23 +144,28 @@
 	/* Tell the stack that the interface is no longer active */
 	ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
 
-	if (onoff) {
+	if (onoff) { /* enable netmap mode */
 		ifp->if_capenable |= IFCAP_NETMAP;
 
-		/* save if_transmit to restore it later */
+		/* save if_transmit and replace with our routine */
 		na->if_transmit = ifp->if_transmit;
 		ifp->if_transmit = netmap_start;
 
+		/*
+		 * reinitialize the adapter, now with netmap flag set,
+		 * so the rings will be set accordingly.
+		 */
 		ixgbe_init_locked(adapter);
 		if ((ifp->if_drv_flags & (IFF_DRV_RUNNING | IFF_DRV_OACTIVE)) == 0) {
 			error = ENOMEM;
 			goto fail;
 		}
-	} else {
+	} else { /* reset normal mode (explicit request or netmap failed) */
 fail:
 		/* restore if_transmit */
 		ifp->if_transmit = na->if_transmit;
 		ifp->if_capenable &= ~IFCAP_NETMAP;
+		/* initialize the card, this time in standard mode */
 		ixgbe_init_locked(adapter);	/* also enables intr */
 	}
 	return (error);
@@ -145,21 +174,23 @@
 
 /*
  * Reconcile kernel and user view of the transmit ring.
+ * This routine might be called frequently so it must be efficient.
  *
- * Userspace has filled tx slots up to cur (excluded).
- * The last unused slot previously known to the kernel was nr_hwcur,
- * and the last interrupt reported nr_hwavail slots available
- * (using the special value -1 to indicate idle transmit ring).
- * The function must first update avail to what the kernel
- * knows, subtract the newly used slots (cur - nr_hwcur)
- * from both avail and nr_hwavail, and set nr_hwcur = cur
+ * Userspace has filled tx slots up to ring->cur (excluded).
+ * The last unused slot previously known to the kernel was kring->nkr_hwcur,
+ * and the last interrupt reported kring->nr_hwavail slots available.
+ *
+ * This function runs under lock (acquired from the caller or internally).
+ * It must first update ring->avail to what the kernel knows,
+ * subtract the newly used slots (ring->cur - kring->nkr_hwcur)
+ * from both avail and nr_hwavail, and set ring->nkr_hwcur = ring->cur
  * issuing a dmamap_sync on all slots.
  *
- * Check parameters in the struct netmap_ring.
- * We don't use avail, only check for bogus values.
- * Make sure cur is valid, and same goes for buffer indexes and lengths.
- * To avoid races, read the values once, and never use those from
- * the ring afterwards.
+ * Since ring comes from userspace, its content must be read only once,
+ * and validated before being used to update the kernel's structures.
+ * (this is also true for every use of ring in the kernel).
+ *
+ * ring->avail is never used, only checked for bogus values.
  */
 static int
 ixgbe_netmap_txsync(void *a, u_int ring_nr, int do_lock)
@@ -169,42 +200,96 @@
 	struct netmap_adapter *na = NA(adapter->ifp);
 	struct netmap_kring *kring = &na->tx_rings[ring_nr];
 	struct netmap_ring *ring = kring->ring;
-	int j, k, n = 0, lim = kring->nkr_num_slots - 1;
+	int j, k, l, n = 0, lim = kring->nkr_num_slots - 1;
 
-	/* generate an interrupt approximately every half ring */
+	/*
+	 * ixgbe can generate an interrupt on every tx packet, but it
+	 * seems very expensive, so we interrupt once every half ring,
+	 * or when requested with NS_REPORT
+	 */
 	int report_frequency = kring->nkr_num_slots >> 1;
 
-	k = ring->cur;	/* ring is not protected by any lock */
-	if ( (kring->nr_kflags & NR_REINIT) || k > lim)
-		return netmap_ring_reinit(kring);
-
 	if (do_lock)
 		IXGBE_TX_LOCK(txr);
+	/* take a copy of ring->cur now, and never read it again */
+	k = ring->cur;
+	l = k - kring->nr_hwcur;
+	if (l < 0)
+		l += lim + 1;
+	/* if cur is invalid reinitialize the ring. */
+	if (k > lim || l > kring->nr_hwavail) {
+		if (do_lock)
+			IXGBE_TX_UNLOCK(txr);
+		return netmap_ring_reinit(kring);
+	}
+
 	bus_dmamap_sync(txr->txdma.dma_tag, txr->txdma.dma_map,
 			BUS_DMASYNC_POSTREAD);
 
-	/* update avail to what the hardware knows */
-	ring->avail = kring->nr_hwavail;
-
+	/*
+	 * Process new packets to send. j is the current index in the
+	 * netmap ring, l is the corresponding index in the NIC ring.
+	 * The two numbers differ because upon a *_init() we reset
+	 * the NIC ring but leave the netmap ring unchanged.
+	 * For the transmit ring, we have
+	 *
+	 *		j = kring->nr_hwcur
+	 *		l = IXGBE_TDT (not tracked in the driver)
+	 * and
+	 * 		j == (l + kring->nkr_hwofs) % ring_size
+	 *
+	 * In this driver kring->nkr_hwofs >= 0, but for other
+	 * drivers it might be negative as well.
+	 */
 	j = kring->nr_hwcur;
 	if (j != k) {	/* we have new packets to send */
+		l = j - kring->nkr_hwofs;
+		if (l < 0)	/* wraparound */
+			l += lim + 1;
+
 		while (j != k) {
+			/*
+			 * Collect per-slot info.
+			 * Note that txbuf and curr are indexed by l.
+			 *
+			 * In this driver we collect the buffer address
+			 * (using the NMB() macro) because we always
+			 * need to rewrite it into the NIC ring.
+			 * Many other drivers preserve the address, so
+			 * we only need to access it if NS_BUF_CHANGED
+			 * is set.
+			 */
 			struct netmap_slot *slot = &ring->slot[j];
-			struct ixgbe_tx_buf *txbuf = &txr->tx_buffers[j];
-			union ixgbe_adv_tx_desc *curr = &txr->tx_base[j];
+			struct ixgbe_tx_buf *txbuf = &txr->tx_buffers[l];
+			union ixgbe_adv_tx_desc *curr = &txr->tx_base[l];
 			void *addr = NMB(slot);
+			// XXX type for flags and len ?
 			int flags = ((slot->flags & NS_REPORT) ||
 				j == 0 || j == report_frequency) ?
 					IXGBE_TXD_CMD_RS : 0;
 			int len = slot->len;
 
+			/*
+			 * Quick check for valid addr and len.
+			 * NMB() returns netmap_buffer_base for invalid
+			 * buffer indexes (but the address is still a
+			 * valid one to be used in a ring). slot->len is
+			 * unsigned so no need to check for negative values.
+			 */
 			if (addr == netmap_buffer_base || len > NETMAP_BUF_SIZE) {
+ring_reset:
 				if (do_lock)
 					IXGBE_TX_UNLOCK(txr);
 				return netmap_ring_reinit(kring);
 			}
 
 			slot->flags &= ~NS_REPORT;
+			/*
+			 * Fill the slot in the NIC ring.
+			 * In this driver we need to rewrite the buffer
+			 * address in the NIC ring. Other drivers do not
+			 * need this.
+			 */
 			curr->read.buffer_addr = htole64(vtophys(addr));
 			curr->read.olinfo_status = 0;
 			curr->read.cmd_type_len =
@@ -212,6 +297,10 @@
 				(IXGBE_ADVTXD_DTYP_DATA |
 				    IXGBE_ADVTXD_DCMD_IFCS |
 				    IXGBE_TXD_CMD_EOP | flags) );
+			/* If the buffer has changed, unload and reload map
+			 * (and possibly the physical address in the NIC
+			 * slot, but we did it already).
+			 */
 			if (slot->flags & NS_BUF_CHANGED) {
 				/* buffer has changed, unload and reload map */
 				netmap_reload_map(txr->txtag, txbuf->map,
@@ -219,69 +308,89 @@
 				slot->flags &= ~NS_BUF_CHANGED;
 			}
 
+			/* make sure changes to the buffer are synced */
 			bus_dmamap_sync(txr->txtag, txbuf->map,
 				BUS_DMASYNC_PREWRITE);
 			j = (j == lim) ? 0 : j + 1;
+			l = (l == lim) ? 0 : l + 1;
 			n++;
 		}
-		kring->nr_hwcur = k;
+		kring->nr_hwcur = k; /* the saved ring->cur */
 
 		/* decrease avail by number of sent packets */
-		ring->avail -= n;
-		kring->nr_hwavail = ring->avail;
+		kring->nr_hwavail -= n;
 
+		/* synchronize the NIC ring */
 		bus_dmamap_sync(txr->txdma.dma_tag, txr->txdma.dma_map,
 			BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
-
-		IXGBE_WRITE_REG(&adapter->hw, IXGBE_TDT(txr->me), k);
+		/* (re)start the transmitter up to slot l (excluded) */
+		IXGBE_WRITE_REG(&adapter->hw, IXGBE_TDT(txr->me), l);
 	}
 
+	/*
+	 * If no packets are sent, or there is no room in the tx ring,
+	 * Check whether there are completed transmissions.
+	 * Because this is expensive (we need a register etc.)
+	 * we only do it if absolutely necessary, i.e. there is no room
+	 * in the tx ring, or where were no completed transmissions
+	 * (meaning that probably the caller really wanted to check
+	 * for completed transmissions).
+	 */
 	if (n == 0 || kring->nr_hwavail < 1) {
-		/* record completed transmissions. TODO
+		int delta;
+
+		/*
+		 * Record completed transmissions.
+		 * We (re)use the driver's txr->next_to_clean to keep
+		 * track of the most recently completed transmission.
 		 *
 		 * The datasheet discourages the use of TDH to find out the
-		 * number of sent packets; the right way to do so, is to check
-		 * the DD bit inside the status of a packet descriptor.  On the
-		 * other hand, we avoid to set the `report status' bit for
-		 * *all* outgoing packets (kind of interrupt mitigation),
-		 * consequently the DD bit is not guaranteed to be set for all
-		 * the packets: thats way, for the moment we continue to use
-		 * TDH.
+		 * number of sent packets. We should rather check the DD
+		 * status bit in a packet descriptor. However, we only set
+		 * the "report status" bit for some descriptors (a kind of
+		 * interrupt mitigation), so we can only check on those.
+		 * For the time being we use TDH, as we do it infrequently
+		 * enough not to pose performance problems.
 		 */
-		j = IXGBE_READ_REG(&adapter->hw, IXGBE_TDH(ring_nr));
-		if (j >= kring->nkr_num_slots) { /* XXX can happen */
-			D("TDH wrap %d", j);
-			j -= kring->nkr_num_slots;
+		l = IXGBE_READ_REG(&adapter->hw, IXGBE_TDH(ring_nr));
+		if (l >= kring->nkr_num_slots) { /* XXX can happen */
+			D("TDH wrap %d", l);
+			l -= kring->nkr_num_slots;
 		}
-		int delta = j - txr->next_to_clean;
+		delta = l - txr->next_to_clean;
 		if (delta) {
-			/* new transmissions were completed, increment
-			   ring->nr_hwavail. */
+			/* some tx completed, increment avail */
 			if (delta < 0)
 				delta += kring->nkr_num_slots;
-			txr->next_to_clean = j;
+			txr->next_to_clean = l;
 			kring->nr_hwavail += delta;
-			ring->avail = kring->nr_hwavail;
+			if (kring->nr_hwavail > lim)
+				goto ring_reset;
 		}
 	}
+	/* update avail to what the kernel knows */
+	ring->avail = kring->nr_hwavail;
 
 	if (do_lock)
 		IXGBE_TX_UNLOCK(txr);
 	return 0;
+
 }
 
 
 /*
  * Reconcile kernel and user view of the receive ring.
+ * Same as for the txsync, this routine must be efficient and
+ * avoid races in accessing the shared regions.
  *
- * Userspace has read rx slots up to cur (excluded).
- * The last unread slot previously known to the kernel was nr_hwcur,
- * and the last interrupt reported nr_hwavail slots available.
+ * When called, userspace has read data from slots kring->nr_hwcur
+ * up to ring->cur (excluded).
+ *
+ * The last interrupt reported kring->nr_hwavail slots available
+ * after kring->nr_hwcur.
  * We must subtract the newly consumed slots (cur - nr_hwcur)
- * from nr_hwavail, clearing the descriptors for the next
- * read, tell the hardware that they are available,
- * and set nr_hwcur = cur and avail = nr_hwavail.
- * issuing a dmamap_sync on all slots.
+ * from nr_hwavail, make the descriptors available for the next reads,
+ * and set kring->nr_hwcur = ring->cur and ring->avail = kring->nr_hwavail.
  */
 static int
 ixgbe_netmap_rxsync(void *a, u_int ring_nr, int do_lock)
@@ -291,86 +400,123 @@
 	struct netmap_adapter *na = NA(adapter->ifp);
 	struct netmap_kring *kring = &na->rx_rings[ring_nr];
 	struct netmap_ring *ring = kring->ring;
-	int j, k, n, lim = kring->nkr_num_slots - 1;
+	int j, k, l, n, lim = kring->nkr_num_slots - 1;
 
-	k = ring->cur;	/* ring is not protected by any lock */
-	if ( (kring->nr_kflags & NR_REINIT) || k > lim)
+	k = ring->cur;	/* cache and check value, same as in txsync */
+	n = k - kring->nr_hwcur;
+	if (n < 0)
+		n += lim + 1;
+	if (k > lim || n > kring->nr_hwavail) /* userspace is cheating */
 		return netmap_ring_reinit(kring);
 
 	if (do_lock)
 		IXGBE_RX_LOCK(rxr);
+	if (n < 0)
+		n += lim + 1;
 	/* XXX check sync modes */
 	bus_dmamap_sync(rxr->rxdma.dma_tag, rxr->rxdma.dma_map,
 			BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
 
-	j = rxr->next_to_check;
+	/*
+	 * First part, import newly received packets into the netmap ring.
+	 *
+	 * j is the index of the next free slot in the netmap ring,
+	 * and l is the index of the next received packet in the NIC ring,
+	 * and they may differ in case if_init() has been called while
+	 * in netmap mode. For the receive ring we have
+	 *
+	 *	j = (kring->nr_hwcur + kring->nr_hwavail) % ring_size
+	 *	l = rxr->next_to_check;
+	 * and
+	 *	j == (l + kring->nkr_hwofs) % ring_size
+	 *
+	 * rxr->next_to_check is set to 0 on a ring reinit
+	 */
+	l = rxr->next_to_check;
+	j = rxr->next_to_check + kring->nkr_hwofs;
+	if (j > lim)
+		j -= lim + 1;
+
 	for (n = 0; ; n++) {
-		union ixgbe_adv_rx_desc *curr = &rxr->rx_base[j];
+		union ixgbe_adv_rx_desc *curr = &rxr->rx_base[l];
 		uint32_t staterr = le32toh(curr->wb.upper.status_error);
 
 		if ((staterr & IXGBE_RXD_STAT_DD) == 0)
 			break;
 		ring->slot[j].len = le16toh(curr->wb.upper.length);
 		bus_dmamap_sync(rxr->ptag,
-			rxr->rx_buffers[j].pmap, BUS_DMASYNC_POSTREAD);
+			rxr->rx_buffers[l].pmap, BUS_DMASYNC_POSTREAD);
 		j = (j == lim) ? 0 : j + 1;
+		l = (l == lim) ? 0 : l + 1;
 	}
-	if (n) {
-		rxr->next_to_check = j;
+	if (n) { /* update the state variables */
+		rxr->next_to_check = l;
 		kring->nr_hwavail += n;
-		if (kring->nr_hwavail >= lim - 10) {
-			ND("rx ring %d almost full %d", ring_nr, kring->nr_hwavail);
-		}
 	}
 
-	/* skip past packets that userspace has already processed,
-	 * making them available for reception.
-	 * advance nr_hwcur and issue a bus_dmamap_sync on the
-	 * buffers so it is safe to write to them.
-	 * Also increase nr_hwavail
+	/*
+	 * Skip past packets that userspace has already processed
+	 * (from kring->nr_hwcur to ring->cur excluded), and make
+	 * the buffers available for reception.
+	 * As usual j is the index in the netmap ring, l is the index
+	 * in the NIC ring, and j == (l + kring->nkr_hwofs) % ring_size
 	 */
 	j = kring->nr_hwcur;
 	if (j != k) {	/* userspace has read some packets. */
 		n = 0;
+		l = kring->nr_hwcur - kring->nkr_hwofs;
+		if (l < 0)
+			l += lim + 1;
 		while (j != k) {
-			struct netmap_slot *slot = ring->slot + j;
-			union ixgbe_adv_rx_desc *curr = &rxr->rx_base[j];
-			struct ixgbe_rx_buf *rxbuf = rxr->rx_buffers + j;
+			/* collect per-slot info, with similar validations
+			 * and flag handling as in the txsync code.
+			 *
+			 * NOTE curr and rxbuf are indexed by l.
+			 * Also, this driver needs to update the physical				 * address in the NIC ring, but other drivers
+			 * may not have this requirement.
+			 */
+			struct netmap_slot *slot = &ring->slot[j];
+			union ixgbe_adv_rx_desc *curr = &rxr->rx_base[l];
+			struct ixgbe_rx_buf *rxbuf = &rxr->rx_buffers[l];
 			void *addr = NMB(slot);
 
-			if (addr == netmap_buffer_base) { /* bad buf */
-				if (do_lock)
-					IXGBE_RX_UNLOCK(rxr);
-				return netmap_ring_reinit(kring);
-			}
+			if (addr == netmap_buffer_base) /* bad buf */
+				goto ring_reset;
 
 			curr->wb.upper.status_error = 0;
 			curr->read.pkt_addr = htole64(vtophys(addr));
 			if (slot->flags & NS_BUF_CHANGED) {
 				netmap_reload_map(rxr->ptag, rxbuf->pmap,
-					addr, na->buff_size);
+				    addr, na->buff_size);
 				slot->flags &= ~NS_BUF_CHANGED;
 			}
 
 			bus_dmamap_sync(rxr->ptag, rxbuf->pmap,
-				BUS_DMASYNC_PREREAD);
+			    BUS_DMASYNC_PREREAD);
 
 			j = (j == lim) ? 0 : j + 1;
+			l = (l == lim) ? 0 : l + 1;
 			n++;
 		}
 		kring->nr_hwavail -= n;
-		kring->nr_hwcur = ring->cur;
+		kring->nr_hwcur = k;
 		bus_dmamap_sync(rxr->rxdma.dma_tag, rxr->rxdma.dma_map,
-			BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
+		    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
 		/* IMPORTANT: we must leave one free slot in the ring,
-		 * so move j back by one unit
+		 * so move l back by one unit
 		 */
-		j = (j == 0) ? lim : j - 1;
-		IXGBE_WRITE_REG(&adapter->hw, IXGBE_RDT(rxr->me), j);
+		l = (l == 0) ? lim : l - 1;
+		IXGBE_WRITE_REG(&adapter->hw, IXGBE_RDT(rxr->me), l);
 	}
 	/* tell userspace that there are new packets */
 	ring->avail = kring->nr_hwavail ;
 	if (do_lock)
 		IXGBE_RX_UNLOCK(rxr);
 	return 0;
+
+ring_reset:
+	if (do_lock)
+		IXGBE_RX_UNLOCK(rxr);
+	return netmap_ring_reinit(kring);
 }
+/* end of file */
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/netmap/netmap.c
--- a/head/sys/dev/netmap/netmap.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/netmap/netmap.c	Tue Dec 06 20:26:16 2011 +0200
@@ -1,15 +1,15 @@
 /*
  * Copyright (C) 2011 Matteo Landi, Luigi Rizzo. 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
+ *   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
@@ -24,8 +24,8 @@
  */
 
 /*
- * $FreeBSD: head/sys/dev/netmap/netmap.c 227875 2011-11-23 09:45:48Z luigi $
- * $Id: netmap.c 9662 2011-11-16 13:18:06Z luigi $
+ * $FreeBSD: head/sys/dev/netmap/netmap.c 228280 2011-12-05 15:21:21Z luigi $
+ * $Id: netmap.c 9795 2011-12-02 11:39:08Z luigi $
  *
  * This module supports memory mapped access to network devices,
  * see netmap(4).
@@ -56,12 +56,13 @@
  */
 
 #include <sys/cdefs.h> /* prerequisite */
-__FBSDID("$FreeBSD: head/sys/dev/netmap/netmap.c 227875 2011-11-23 09:45:48Z luigi $");
+__FBSDID("$FreeBSD: head/sys/dev/netmap/netmap.c 228280 2011-12-05 15:21:21Z luigi $");
 
 #include <sys/types.h>
 #include <sys/module.h>
 #include <sys/errno.h>
 #include <sys/param.h>	/* defines used in kernel.h */
+#include <sys/jail.h>
 #include <sys/kernel.h>	/* types used in module initialization */
 #include <sys/conf.h>	/* cdevsw struct */
 #include <sys/uio.h>	/* uio struct */
@@ -70,6 +71,7 @@
 #include <sys/malloc.h>
 #include <sys/mman.h>	/* PROT_EXEC */
 #include <sys/poll.h>
+#include <sys/proc.h>
 #include <vm/vm.h>	/* vtophys */
 #include <vm/pmap.h>	/* vtophys */
 #include <sys/socket.h> /* sockaddrs */
@@ -78,6 +80,7 @@
 #include <sys/sysctl.h>
 #include <net/if.h>
 #include <net/bpf.h>		/* BIOCIMMEDIATE */
+#include <net/vnet.h>
 #include <net/netmap.h>
 #include <dev/netmap/netmap_kern.h>
 #include <machine/bus.h>	/* bus_dmamap_* */
@@ -572,7 +575,13 @@
 
 
 /*
- * handler for synchronization of the queues from/to the host
+ * Handlers for synchronization of the queues from/to the host.
+ *
+ * netmap_sync_to_host() passes packets up. We are called from a
+ * system call in user process context, and the only contention
+ * can be among multiple user threads erroneously calling
+ * this routine concurrently. In principle we should not even
+ * need to lock.
  */
 static void
 netmap_sync_to_host(struct netmap_adapter *na)
@@ -580,15 +589,20 @@
 	struct netmap_kring *kring = &na->tx_rings[na->num_queues];
 	struct netmap_ring *ring = kring->ring;
 	struct mbuf *head = NULL, *tail = NULL, *m;
-	u_int n, lim = kring->nkr_num_slots - 1;
+	u_int k, n, lim = kring->nkr_num_slots - 1;
 
-	na->nm_lock(na->ifp->if_softc, NETMAP_CORE_LOCK, 0);
+	k = ring->cur;
+	if (k > lim) {
+		netmap_ring_reinit(kring);
+		return;
+	}
+	// na->nm_lock(na->ifp->if_softc, NETMAP_CORE_LOCK, 0);
 
 	/* Take packets from hwcur to cur and pass them up.
 	 * In case of no buffers we give up. At the end of the loop,
 	 * the queue is drained in all cases.
 	 */
-	for (n = kring->nr_hwcur; n != ring->cur;) {
+	for (n = kring->nr_hwcur; n != k;) {
 		struct netmap_slot *slot = &ring->slot[n];
 
 		n = (n == lim) ? 0 : n + 1;
@@ -607,9 +621,9 @@
 		tail = m;
 		m->m_nextpkt = NULL;
 	}
-	kring->nr_hwcur = ring->cur;
+	kring->nr_hwcur = k;
 	kring->nr_hwavail = ring->avail = lim;
-	na->nm_lock(na->ifp->if_softc, NETMAP_CORE_UNLOCK, 0);
+	// na->nm_lock(na->ifp->if_softc, NETMAP_CORE_UNLOCK, 0);
 
 	/* send packets up, outside the lock */
 	while ((m = head) != NULL) {
@@ -623,6 +637,10 @@
 }
 
 /*
+ * rxsync backend for packets coming from the host stack.
+ * They have been put in the queue by netmap_start() so we
+ * need to protect access to the kring using a lock.
+ *
  * This routine also does the selrecord if called from the poll handler
  * (we know because td != NULL).
  */
@@ -631,24 +649,29 @@
 {
 	struct netmap_kring *kring = &na->rx_rings[na->num_queues];
 	struct netmap_ring *ring = kring->ring;
-	int delta;
+	int error = 1, delta;
+	u_int k = ring->cur, lim = kring->nkr_num_slots;
 
 	na->nm_lock(na->ifp->if_softc, NETMAP_CORE_LOCK, 0);
-
-	/* skip past packets processed by userspace,
-	 * and then sync cur/avail with hwcur/hwavail
-	 */
-	delta = ring->cur - kring->nr_hwcur;
+	if (k >= lim) /* bad value */
+		goto done;
+	delta = k - kring->nr_hwcur;
 	if (delta < 0)
-		delta += kring->nkr_num_slots;
+		delta += lim;
 	kring->nr_hwavail -= delta;
-	kring->nr_hwcur = ring->cur;
-	ring->avail = kring->nr_hwavail;
-	if (ring->avail == 0 && td)
+	if (kring->nr_hwavail < 0)	/* error */
+		goto done;
+	kring->nr_hwcur = k;
+	error = 0;
+	k = ring->avail = kring->nr_hwavail;
+	if (k == 0 && td)
 		selrecord(td, &kring->si);
-	if (ring->avail && (netmap_verbose & NM_VERB_HOST))
-		D("%d pkts from stack", ring->avail);
+	if (k && (netmap_verbose & NM_VERB_HOST))
+		D("%d pkts from stack", k);
+done:
 	na->nm_lock(na->ifp->if_softc, NETMAP_CORE_UNLOCK, 0);
+	if (error)
+		netmap_ring_reinit(kring);
 }
 
 
@@ -678,6 +701,13 @@
  * Error routine called when txsync/rxsync detects an error.
  * Can't do much more than resetting cur = hwcur, avail = hwavail.
  * Return 1 on reinit.
+ *
+ * This routine is only called by the upper half of the kernel.
+ * It only reads hwcur (which is changed only by the upper half, too)
+ * and hwavail (which may be changed by the lower half, but only on
+ * a tx ring and only to increase it, so any error will be recovered
+ * on the next call). For the above, we don't strictly need to call
+ * it under lock.
  */
 int
 netmap_ring_reinit(struct netmap_kring *kring)
@@ -717,29 +747,10 @@
 			ring->avail, kring->nr_hwavail);
 		ring->cur = kring->nr_hwcur;
 		ring->avail = kring->nr_hwavail;
-		ring->flags |= NR_REINIT;
-		kring->na->flags |= NR_REINIT;
 	}
 	return (errors ? 1 : 0);
 }
 
-/*
- * Clean the reinit flag for our rings.
- * XXX at the moment, clear for all rings
- */
-static void
-netmap_clean_reinit(struct netmap_adapter *na)
-{
-	//struct netmap_kring *kring;
-	u_int i;
-
-	na->flags &= ~NR_REINIT;
-	D("--- NR_REINIT reset on %s", na->ifp->if_xname);
-	for (i = 0; i < na->num_queues + 1; i++) {
-		na->tx_rings[i].ring->flags &= ~NR_REINIT;
-		na->rx_rings[i].ring->flags &= ~NR_REINIT;
-	}
-}
 
 /*
  * Set the ring ID. For devices with a single queue, a request
@@ -801,7 +812,7 @@
  */
 static int
 netmap_ioctl(__unused struct cdev *dev, u_long cmd, caddr_t data,
-	__unused int fflag, __unused struct thread *td)
+	__unused int fflag, struct thread *td)
 {
 	struct netmap_priv_d *priv = NULL;
 	struct ifnet *ifp;
@@ -812,9 +823,13 @@
 	u_int i;
 	struct netmap_if *nifp;
 
+	CURVNET_SET(TD_TO_VNET(td));
+
 	error = devfs_get_cdevpriv((void **)&priv);
-	if (error != ENOENT && error != 0)
+	if (error != ENOENT && error != 0) {
+		CURVNET_RESTORE();
 		return (error);
+	}
 
 	error = 0;	/* Could be ENOENT */
 	switch (cmd) {
@@ -836,8 +851,10 @@
 		break;
 
 	case NIOCREGIF:
-		if (priv != NULL)	/* thread already registered */
-			return netmap_set_ringid(priv, nmr->nr_ringid);
+		if (priv != NULL) {	/* thread already registered */
+			error = netmap_set_ringid(priv, nmr->nr_ringid);
+			break;
+		}
 		/* find the interface and a reference */
 		error = get_ifp(nmr->nr_name, &ifp); /* keep reference */
 		if (error)
@@ -927,8 +944,10 @@
 		break;
 
 	case NIOCUNREGIF:
-		if (priv == NULL)
-			return (ENXIO);
+		if (priv == NULL) {
+			error = ENXIO;
+			break;
+		}
 
 		/* the interface is unregistered inside the
 		   destructor of the private data. */
@@ -937,22 +956,21 @@
 
 	case NIOCTXSYNC:
         case NIOCRXSYNC:
-		if (priv == NULL)
-			return (ENXIO);
+		if (priv == NULL) {
+			error = ENXIO;
+			break;
+		}
 		ifp = priv->np_ifp;	/* we have a reference */
 		na = NA(ifp); /* retrieve netmap adapter */
 		adapter = ifp->if_softc;	/* shorthand */
 
-		if (na->flags & NR_REINIT)
-			netmap_clean_reinit(na);
-
 		if (priv->np_qfirst == na->num_queues) {
 			/* queues to/from host */
 			if (cmd == NIOCTXSYNC)
 				netmap_sync_to_host(na);
 			else
 				netmap_sync_from_host(na, NULL);
-			return error;
+			break;
 		}
 
 		for (i = priv->np_qfirst; i < priv->np_qlast; i++) {
@@ -999,6 +1017,7 @@
 	    }
 	}
 
+	CURVNET_RESTORE();
 	return (error);
 }
 
@@ -1039,13 +1058,6 @@
 	adapter = ifp->if_softc;
 	na = NA(ifp); /* retrieve netmap adapter */
 
-	/* pending reinit, report up as a poll error. Pending
-	 * reads and writes are lost.
-	 */
-	if (na->flags & NR_REINIT) {
-		netmap_clean_reinit(na);
-		revents |= POLLERR;
-	}
 	/* how many queues we are scanning */
 	i = priv->np_qfirst;
 	if (i == na->num_queues) { /* from/to host */
@@ -1111,20 +1123,20 @@
 	 * data available. If this fails, then lock and call the sync
 	 * routines.
 	 */
-	for (i = priv->np_qfirst; want_rx && i < priv->np_qlast; i++) {
-		kring = &na->rx_rings[i];
-		if (kring->ring->avail > 0) {
-			revents |= want_rx;
-			want_rx = 0;	/* also breaks the loop */
+		for (i = priv->np_qfirst; want_rx && i < priv->np_qlast; i++) {
+			kring = &na->rx_rings[i];
+			if (kring->ring->avail > 0) {
+				revents |= want_rx;
+				want_rx = 0;	/* also breaks the loop */
+			}
 		}
-	}
-	for (i = priv->np_qfirst; want_tx && i < priv->np_qlast; i++) {
-		kring = &na->tx_rings[i];
-		if (kring->ring->avail > 0) {
-			revents |= want_tx;
-			want_tx = 0;	/* also breaks the loop */
+		for (i = priv->np_qfirst; want_tx && i < priv->np_qlast; i++) {
+			kring = &na->tx_rings[i];
+			if (kring->ring->avail > 0) {
+				revents |= want_tx;
+				want_tx = 0;	/* also breaks the loop */
+			}
 		}
-	}
 
 	/*
 	 * If we to push packets out (priv->np_txpoll) or want_tx is
@@ -1270,25 +1282,24 @@
 
 
 /*
- * intercept packets coming from the network stack and present
- * them to netmap as incoming packets on a separate ring.
+ * Intercept packets from the network stack and pass them
+ * to netmap as incoming packets on the 'software' ring.
  * We are not locked when called.
  */
 int
 netmap_start(struct ifnet *ifp, struct mbuf *m)
 {
 	struct netmap_adapter *na = NA(ifp);
-	u_int i, len, n = na->num_queues;
-	int error = EBUSY;
-	struct netmap_kring *kring = &na->rx_rings[n];
+	struct netmap_kring *kring = &na->rx_rings[na->num_queues];
+	u_int i, len = m->m_pkthdr.len;
+	int error = EBUSY, lim = kring->nkr_num_slots - 1;
 	struct netmap_slot *slot;
 
-	len = m->m_pkthdr.len;
 	if (netmap_verbose & NM_VERB_HOST)
 		D("%s packet %d len %d from the stack", ifp->if_xname,
 			kring->nr_hwcur + kring->nr_hwavail, len);
 	na->nm_lock(ifp->if_softc, NETMAP_CORE_LOCK, 0);
-	if (kring->nr_hwavail >= (int)kring->nkr_num_slots - 1) {
+	if (kring->nr_hwavail >= lim) {
 		D("stack ring %s full\n", ifp->if_xname);
 		goto done;	/* no space */
 	}
@@ -1299,8 +1310,8 @@
 
 	/* compute the insert position */
 	i = kring->nr_hwcur + kring->nr_hwavail;
-	if (i >= kring->nkr_num_slots)
-		i -= kring->nkr_num_slots;
+	if (i > lim)
+		i -= lim + 1;
 	slot = &kring->ring->slot[i];
 	m_copydata(m, 0, len, NMB(slot));
 	slot->len = len;
@@ -1326,24 +1337,6 @@
  * netmap_reset() is called by the driver routines when reinitializing
  * a ring. The driver is in charge of locking to protect the kring.
  * If netmap mode is not set just return NULL.
- * Otherwise set NR_REINIT (in the ring and in na) to signal
- * that a ring has been reinitialized,
- * set cur = hwcur = 0 and avail = hwavail = num_slots - 1 .
- * IT IS IMPORTANT to leave one slot free even in the tx ring because
- * we rely on cur=hwcur only for empty rings.
- * These are good defaults but can be overridden later in the device
- * specific code if, after a reinit, the ring does not start from 0
- * (e.g. if_em.c does this).
- *
- * XXX we shouldn't be touching the ring, but there is a
- * race anyways and this is our best option.
- *
- * XXX setting na->flags makes the syscall code faster, as there is
- * only one place to check. On the other hand, we will need a better
- * way to notify multiple threads that rings have been reset.
- * One way is to increment na->rst_count at each ring reset.
- * Each thread in its own priv structure will keep a matching counter,
- * and on a reset will acknowledge and clean its own rings.
  */
 struct netmap_slot *
 netmap_reset(struct netmap_adapter *na, enum txrx tx, int n,
@@ -1351,8 +1344,7 @@
 {
 	struct netmap_kring *kring;
 	struct netmap_ring *ring;
-	struct netmap_slot *slot;
-	u_int i;
+	int new_hwofs, lim;
 
 	if (na == NULL)
 		return NULL;	/* no netmap support here */
@@ -1360,74 +1352,26 @@
 		return NULL;	/* nothing to reinitialize */
 	kring = tx == NR_TX ?  na->tx_rings + n : na->rx_rings + n;
 	ring = kring->ring;
-    if (tx == NR_TX) {
+	lim = kring->nkr_num_slots - 1;
+
+	if (tx == NR_TX)
+		new_hwofs = kring->nr_hwcur - new_cur;
+	else
+		new_hwofs = kring->nr_hwcur + kring->nr_hwavail - new_cur;
+	if (new_hwofs > lim)
+		new_hwofs -= lim + 1;
+
+	/* Alwayws set the new offset value and realign the ring. */
+	kring->nkr_hwofs = new_hwofs;
+	if (tx == NR_TX)
+		kring->nr_hwavail = kring->nkr_num_slots - 1;
+	D("new hwofs %d on %s %s[%d]",
+			kring->nkr_hwofs, na->ifp->if_xname,
+			tx == NR_TX ? "TX" : "RX", n);
+
 	/*
-	 * The last argument is the new value of next_to_clean.
-	 *
-	 * In the TX ring, we have P pending transmissions (from
-	 * next_to_clean to nr_hwcur) followed by nr_hwavail free slots.
-	 * Generally we can use all the slots in the ring so
-	 * P = ring_size - nr_hwavail hence (modulo ring_size):
-	 *	next_to_clean == nr_hwcur + nr_hwavail
-	 * 
-	 * If, upon a reset, nr_hwavail == ring_size and next_to_clean
-	 * does not change we have nothing to report. Otherwise some
-	 * pending packets may be lost, or newly injected packets will.
-	 */
-	/* if hwcur does not change, nothing to report.
-	 * otherwise remember the change so perhaps we can
-	 * shift the block at the next reinit
-	 */
-	if (new_cur == kring->nr_hwcur &&
-		    kring->nr_hwavail == kring->nkr_num_slots - 1) {
-		/* all ok */
-		D("+++ NR_REINIT ok on %s TX[%d]", na->ifp->if_xname, n);
-	} else {
-		D("+++ NR_REINIT set on %s TX[%d]", na->ifp->if_xname, n);
-	}
-		ring->flags |= NR_REINIT;
-		na->flags |= NR_REINIT;
-		ring->avail = kring->nr_hwavail = kring->nkr_num_slots - 1;
-		ring->cur = kring->nr_hwcur = new_cur;
-    } else {
-	/*
-	 * The last argument is the next free slot.
-	 * In the RX ring we have nr_hwavail full buffers starting
-	 * from nr_hwcur.
-	 * If nr_hwavail == 0 and nr_hwcur does not change we are ok
-	 * otherwise we might be in trouble as the buffers are
-	 * changing.
-	 */
-	if (new_cur == kring->nr_hwcur && kring->nr_hwavail == 0) {
-		/* all ok */
-		D("+++ NR_REINIT ok on %s RX[%d]", na->ifp->if_xname, n);
-	} else {
-		D("+++ NR_REINIT set on %s RX[%d]", na->ifp->if_xname, n);
-	}
-	ring->flags |= NR_REINIT;
-	na->flags |= NR_REINIT;
-	ring->avail = kring->nr_hwavail = 0; /* no data */
-	ring->cur = kring->nr_hwcur = new_cur;
-    }
-
-	slot = ring->slot;
-	/*
-	 * Check that buffer indexes are correct. If we find a
-	 * bogus value we are a bit in trouble because we cannot
-	 * recover easily. Best we can do is (probably) persistently
-	 * reset the ring.
-	 */
-	for (i = 0; i < kring->nkr_num_slots; i++) {
-		if (slot[i].buf_idx >= netmap_total_buffers) {
-			D("invalid buf_idx %d at slot %d", slot[i].buf_idx, i);
-			slot[i].buf_idx = 0; /* XXX reset */
-		}
-		/* XXX we don't really need to set the length */
-		slot[i].len = 0;
-	}
-	/* wakeup possible waiters, both on the ring and on the global
-	 * selfd. Perhaps a bit early now but the device specific
-	 * routine is locked so hopefully we won't have a race.
+	 * We do the wakeup here, but the ring is not yet reconfigured.
+	 * However, we are under lock so there are no races.
 	 */
 	selwakeuppri(&kring->si, PI_NET);
 	selwakeuppri(&kring[na->num_queues + 1 - n].si, PI_NET);
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/netmap/netmap_kern.h
--- a/head/sys/dev/netmap/netmap_kern.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/netmap/netmap_kern.h	Tue Dec 06 20:26:16 2011 +0200
@@ -1,15 +1,15 @@
 /*
  * Copyright (C) 2011 Matteo Landi, Luigi Rizzo. 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
+ *   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
@@ -24,8 +24,8 @@
  */
 
 /*
- * $FreeBSD: head/sys/dev/netmap/netmap_kern.h 227614 2011-11-17 12:17:39Z luigi $
- * $Id: netmap_kern.h 9662 2011-11-16 13:18:06Z luigi $
+ * $FreeBSD: head/sys/dev/netmap/netmap_kern.h 228276 2011-12-05 12:06:53Z luigi $
+ * $Id: netmap_kern.h 9795 2011-12-02 11:39:08Z luigi $
  *
  * The header contains the definitions of constants and function
  * prototypes used only in kernelspace.
@@ -68,7 +68,7 @@
 	u_int nr_kflags;
 	u_int nkr_num_slots;
 
-	u_int	nkr_hwofs;	/* offset between NIC and netmap ring */
+	int	nkr_hwofs;	/* offset between NIC and netmap ring */
 	struct netmap_adapter *na;	 // debugging
 	struct selinfo si; /* poll/select wait queue */
 };
@@ -94,7 +94,7 @@
 	u_int num_rx_desc;
 	u_int buff_size;
 
-	u_int	flags;	/* NR_REINIT */
+	u_int	flags;
 	/* tx_rings and rx_rings are private but allocated
 	 * as a contiguous chunk of memory. Each array has
 	 * N+1 entries, for the adapter queues and for the host queue.
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/ofw/ofw_fdt.c
--- a/head/sys/dev/ofw/ofw_fdt.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/ofw/ofw_fdt.c	Tue Dec 06 20:26:16 2011 +0200
@@ -28,7 +28,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/ofw/ofw_fdt.c 226466 2011-10-17 13:44:33Z jchandra $");
+__FBSDID("$FreeBSD: head/sys/dev/ofw/ofw_fdt.c 228201 2011-12-02 15:24:39Z jchandra $");
 
 #include <sys/param.h>
 #include <sys/kernel.h>
@@ -392,6 +392,8 @@
 	int offset;
 
 	offset = fdt_path_offset(fdtp, device);
+	if (offset < 0)
+		return (-1);
 	return (fdt_offset_phandle(offset));
 }
 
@@ -420,7 +422,7 @@
 	ssize_t len;
 	int i;
 
-	if ((root = ofw_fdt_finddevice(ofw, "/")) == 0)
+	if ((root = ofw_fdt_finddevice(ofw, "/")) == -1)
 		return (ENODEV);
 
 	if ((len = ofw_fdt_getproplen(ofw, root, "model")) <= 0)
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/ofw/openfirm.c
--- a/head/sys/dev/ofw/openfirm.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/ofw/openfirm.c	Tue Dec 06 20:26:16 2011 +0200
@@ -56,7 +56,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/ofw/openfirm.c 227537 2011-11-15 20:11:03Z marius $");
+__FBSDID("$FreeBSD: head/sys/dev/ofw/openfirm.c 228201 2011-12-02 15:24:39Z jchandra $");
 
 #include "opt_platform.h"
 
@@ -131,7 +131,7 @@
 
 	rv = OFW_INIT(ofw_obj, cookie);
 
-	if ((chosen = OF_finddevice("/chosen")) > 0)
+	if ((chosen = OF_finddevice("/chosen")) != -1)
 		if (OF_getprop(chosen, "stdout", &stdout, sizeof(stdout)) == -1)
 			stdout = -1;
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/pci/pcireg.h
--- a/head/sys/dev/pci/pcireg.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/pci/pcireg.h	Tue Dec 06 20:26:16 2011 +0200
@@ -23,7 +23,7 @@
  * (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: head/sys/dev/pci/pcireg.h 222018 2011-05-17 11:23:43Z ru $
+ * $FreeBSD: head/sys/dev/pci/pcireg.h 228161 2011-11-30 18:33:23Z jhb $
  *
  */
 
@@ -715,6 +715,7 @@
 #define	PCIM_AER_COR_BAD_DLLP		0x00000080
 #define	PCIM_AER_COR_REPLAY_ROLLOVER	0x00000100
 #define	PCIM_AER_COR_REPLAY_TIMEOUT	0x00001000
+#define	PCIM_AER_COR_ADVISORY_NF_ERROR	0x00002000
 #define	PCIR_AER_COR_MASK	0x14	/* Shares bits with COR_STATUS */
 #define	PCIR_AER_CAP_CONTROL	0x18
 #define	PCIM_AER_FIRST_ERROR_PTR	0x0000001f
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/re/if_re.c
--- a/head/sys/dev/re/if_re.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/re/if_re.c	Tue Dec 06 20:26:16 2011 +0200
@@ -31,7 +31,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/re/if_re.c 227854 2011-11-23 02:08:05Z yongari $");
+__FBSDID("$FreeBSD: head/sys/dev/re/if_re.c 228281 2011-12-05 15:33:13Z luigi $");
 
 /*
  * RealTek 8139C+/8169/8169S/8110S/8168/8111/8101E PCI NIC driver
@@ -294,6 +294,11 @@
 static void re_reset		(struct rl_softc *);
 static void re_setwol		(struct rl_softc *);
 static void re_clrwol		(struct rl_softc *);
+static void re_set_linkspeed	(struct rl_softc *);
+
+#ifdef DEV_NETMAP	/* see ixgbe.c for details */
+#include <dev/netmap/if_re_netmap.h>
+#endif /* !DEV_NETMAP */
 
 #ifdef RE_DIAG
 static int re_diag		(struct rl_softc *);
@@ -1401,13 +1406,18 @@
 		    RL_FLAG_AUTOPAD | RL_FLAG_MACSLEEP;
 		break;
 	case RL_HWREV_8401E:
-	case RL_HWREV_8402:
 	case RL_HWREV_8105E:
 	case RL_HWREV_8105E_SPIN1:
 		sc->rl_flags |= RL_FLAG_PHYWAKE | RL_FLAG_PHYWAKE_PM |
 		    RL_FLAG_PAR | RL_FLAG_DESCV2 | RL_FLAG_MACSTAT |
 		    RL_FLAG_FASTETHER | RL_FLAG_CMDSTOP | RL_FLAG_AUTOPAD;
 		break;
+	case RL_HWREV_8402:
+		sc->rl_flags |= RL_FLAG_PHYWAKE | RL_FLAG_PHYWAKE_PM |
+		    RL_FLAG_PAR | RL_FLAG_DESCV2 | RL_FLAG_MACSTAT |
+		    RL_FLAG_FASTETHER | RL_FLAG_CMDSTOP | RL_FLAG_AUTOPAD |
+		    RL_FLAG_CMDSTOP_WAIT_TXQ;
+		break;
 	case RL_HWREV_8168B_SPIN1:
 	case RL_HWREV_8168B_SPIN2:
 		sc->rl_flags |= RL_FLAG_WOLRXENB;
@@ -1424,22 +1434,28 @@
 		/* FALLTHROUGH */
 	case RL_HWREV_8168CP:
 	case RL_HWREV_8168D:
+		sc->rl_flags |= RL_FLAG_PHYWAKE | RL_FLAG_PAR |
+		    RL_FLAG_DESCV2 | RL_FLAG_MACSTAT | RL_FLAG_CMDSTOP |
+		    RL_FLAG_AUTOPAD | RL_FLAG_JUMBOV2 | RL_FLAG_WOL_MANLINK;
+		break;
 	case RL_HWREV_8168DP:
 		sc->rl_flags |= RL_FLAG_PHYWAKE | RL_FLAG_PAR |
-		    RL_FLAG_DESCV2 | RL_FLAG_MACSTAT | RL_FLAG_CMDSTOP |
-		    RL_FLAG_AUTOPAD | RL_FLAG_JUMBOV2;
+		    RL_FLAG_DESCV2 | RL_FLAG_MACSTAT | RL_FLAG_AUTOPAD |
+		    RL_FLAG_JUMBOV2 | RL_FLAG_WAIT_TXPOLL | RL_FLAG_WOL_MANLINK;
 		break;
 	case RL_HWREV_8168E:
 		sc->rl_flags |= RL_FLAG_PHYWAKE | RL_FLAG_PHYWAKE_PM |
 		    RL_FLAG_PAR | RL_FLAG_DESCV2 | RL_FLAG_MACSTAT |
-		    RL_FLAG_CMDSTOP | RL_FLAG_AUTOPAD | RL_FLAG_JUMBOV2;
+		    RL_FLAG_CMDSTOP | RL_FLAG_AUTOPAD | RL_FLAG_JUMBOV2 |
+		    RL_FLAG_WOL_MANLINK;
 		break;
 	case RL_HWREV_8168E_VL:
 	case RL_HWREV_8168F:
 	case RL_HWREV_8411:
 		sc->rl_flags |= RL_FLAG_PHYWAKE | RL_FLAG_PAR |
 		    RL_FLAG_DESCV2 | RL_FLAG_MACSTAT | RL_FLAG_CMDSTOP |
-		    RL_FLAG_AUTOPAD | RL_FLAG_JUMBOV2;
+		    RL_FLAG_AUTOPAD | RL_FLAG_JUMBOV2 |
+		    RL_FLAG_CMDSTOP_WAIT_TXQ | RL_FLAG_WOL_MANLINK;
 		break;
 	case RL_HWREV_8169_8110SB:
 	case RL_HWREV_8169_8110SBL:
@@ -1608,6 +1624,9 @@
 	 */
 	ifp->if_data.ifi_hdrlen = sizeof(struct ether_vlan_header);
 
+#ifdef DEV_NETMAP
+	re_netmap_attach(sc);
+#endif /* DEV_NETMAP */
 #ifdef RE_DIAG
 	/*
 	 * Perform hardware diagnostic on the original RTL8169.
@@ -1803,6 +1822,9 @@
 		bus_dma_tag_destroy(sc->rl_ldata.rl_stag);
 	}
 
+#ifdef DEV_NETMAP
+	netmap_detach(ifp);
+#endif /* DEV_NETMAP */
 	if (sc->rl_parent_tag)
 		bus_dma_tag_destroy(sc->rl_parent_tag);
 
@@ -1977,6 +1999,9 @@
 	    sc->rl_ldata.rl_tx_desc_cnt * sizeof(struct rl_desc));
 	for (i = 0; i < sc->rl_ldata.rl_tx_desc_cnt; i++)
 		sc->rl_ldata.rl_tx_desc[i].tx_m = NULL;
+#ifdef DEV_NETMAP
+	re_netmap_tx_init(sc);
+#endif /* DEV_NETMAP */
 	/* Set EOR. */
 	desc = &sc->rl_ldata.rl_tx_list[sc->rl_ldata.rl_tx_desc_cnt - 1];
 	desc->rl_cmdstat |= htole32(RL_TDESC_CMD_EOR);
@@ -2004,6 +2029,9 @@
 		if ((error = re_newbuf(sc, i)) != 0)
 			return (error);
 	}
+#ifdef DEV_NETMAP
+	re_netmap_rx_init(sc);
+#endif /* DEV_NETMAP */
 
 	/* Flush the RX descriptors */
 
@@ -2060,6 +2088,12 @@
 	RL_LOCK_ASSERT(sc);
 
 	ifp = sc->rl_ifp;
+#ifdef DEV_NETMAP
+	if (ifp->if_capenable & IFCAP_NETMAP) {
+		selwakeuppri(&NA(ifp)->rx_rings->si, PI_NET);
+		return 0;
+	}
+#endif /* DEV_NETMAP */
 	if (ifp->if_mtu > RL_MTU && (sc->rl_flags & RL_FLAG_JUMBOV2) != 0)
 		jumbo = 1;
 	else
@@ -2301,6 +2335,12 @@
 		return;
 
 	ifp = sc->rl_ifp;
+#ifdef DEV_NETMAP
+	if (ifp->if_capenable & IFCAP_NETMAP) {
+		selwakeuppri(&NA(ifp)->tx_rings[0].si, PI_NET);
+		return;
+	}
+#endif /* DEV_NETMAP */
 	/* Invalidate the TX descriptor list */
 	bus_dmamap_sync(sc->rl_ldata.rl_tx_list_tag,
 	    sc->rl_ldata.rl_tx_list_map,
@@ -2819,6 +2859,21 @@
 
 	sc = ifp->if_softc;
 
+#ifdef DEV_NETMAP
+	/* XXX is this necessary ? */
+	if (ifp->if_capenable & IFCAP_NETMAP) {
+		struct netmap_kring *kring = &NA(ifp)->tx_rings[0];
+		if (sc->rl_ldata.rl_tx_prodidx != kring->nr_hwcur) {
+			/* kick the tx unit */
+			CSR_WRITE_1(sc, sc->rl_txstart, RL_TXSTART_START);
+#ifdef RE_TX_MODERATION
+			CSR_WRITE_4(sc, RL_TIMERCNT, 1);
+#endif
+			sc->rl_watchdog_timer = 5;
+		}
+		return;
+	}
+#endif /* DEV_NETMAP */
 	if ((ifp->if_drv_flags & (IFF_DRV_RUNNING | IFF_DRV_OACTIVE)) !=
 	    IFF_DRV_RUNNING || (sc->rl_flags & RL_FLAG_LINK) == 0)
 		return;
@@ -3466,10 +3521,32 @@
 	    ~(RL_RXCFG_RX_ALLPHYS | RL_RXCFG_RX_INDIV | RL_RXCFG_RX_MULTI |
 	    RL_RXCFG_RX_BROAD));
 
-	if ((sc->rl_flags & RL_FLAG_CMDSTOP) != 0)
+	if ((sc->rl_flags & RL_FLAG_WAIT_TXPOLL) != 0) {
+		for (i = RL_TIMEOUT; i > 0; i--) {
+			if ((CSR_READ_1(sc, sc->rl_txstart) &
+			    RL_TXSTART_START) == 0)
+				break;
+			DELAY(20);
+		}
+		if (i == 0)
+			device_printf(sc->rl_dev,
+			    "stopping TX poll timed out!\n");
+		CSR_WRITE_1(sc, RL_COMMAND, 0x00);
+	} else if ((sc->rl_flags & RL_FLAG_CMDSTOP) != 0) {
 		CSR_WRITE_1(sc, RL_COMMAND, RL_CMD_STOPREQ | RL_CMD_TX_ENB |
 		    RL_CMD_RX_ENB);
-	else
+		if ((sc->rl_flags & RL_FLAG_CMDSTOP_WAIT_TXQ) != 0) {
+			for (i = RL_TIMEOUT; i > 0; i--) {
+				if ((CSR_READ_4(sc, RL_TXCFG) &
+				    RL_TXCFG_QUEUE_EMPTY) != 0)
+					break;
+				DELAY(100);
+			}
+			if (i == 0)
+				device_printf(sc->rl_dev,
+				   "stopping TXQ timed out!\n");
+		}
+	} else
 		CSR_WRITE_1(sc, RL_COMMAND, 0x00);
 	DELAY(1000);
 	CSR_WRITE_2(sc, RL_IMR, 0x0000);
@@ -3595,6 +3672,74 @@
 }
 
 static void
+re_set_linkspeed(struct rl_softc *sc)
+{
+	struct mii_softc *miisc;
+	struct mii_data *mii;
+	int aneg, i, phyno;
+
+	RL_LOCK_ASSERT(sc);
+
+	mii = device_get_softc(sc->rl_miibus);
+	mii_pollstat(mii);
+	aneg = 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:
+		case IFM_100_TX:
+			return;
+		case IFM_1000_T:
+			aneg++;
+			break;
+		default:
+			break;
+		}
+	}
+	miisc = LIST_FIRST(&mii->mii_phys);
+	phyno = miisc->mii_phy;
+	LIST_FOREACH(miisc, &mii->mii_phys, mii_list)
+		PHY_RESET(miisc);
+	re_miibus_writereg(sc->rl_dev, phyno, MII_100T2CR, 0);
+	re_miibus_writereg(sc->rl_dev, phyno,
+	    MII_ANAR, ANAR_TX_FD | ANAR_TX | ANAR_10_FD | ANAR_10 | ANAR_CSMA);
+	re_miibus_writereg(sc->rl_dev, phyno,
+	    MII_BMCR, BMCR_AUTOEN | BMCR_STARTNEG);
+	DELAY(1000);
+	if (aneg != 0) {
+		/*
+		 * Poll link state until re(4) get a 10/100Mbps link.
+		 */
+		for (i = 0; i < MII_ANEGTICKS_GIGE; i++) {
+			mii_pollstat(mii);
+			if ((mii->mii_media_status & (IFM_ACTIVE | IFM_AVALID))
+			    == (IFM_ACTIVE | IFM_AVALID)) {
+				switch (IFM_SUBTYPE(mii->mii_media_active)) {
+				case IFM_10_T:
+				case IFM_100_TX:
+					return;
+				default:
+					break;
+				}
+			}
+			RL_UNLOCK(sc);
+			pause("relnk", hz);
+			RL_LOCK(sc);
+		}
+		if (i == MII_ANEGTICKS_GIGE)
+			device_printf(sc->rl_dev,
+			    "establishing a link failed, WOL may not work!");
+	}
+	/*
+	 * No link, force MAC to have 100Mbps, full-duplex link.
+	 * MAC does not require reprogramming on resolved speed/duplex,
+	 * so this is just for completeness.
+	 */
+	mii->mii_media_status = IFM_AVALID | IFM_ACTIVE;
+	mii->mii_media_active = IFM_ETHER | IFM_100_TX | IFM_FDX;
+}
+
+static void
 re_setwol(struct rl_softc *sc)
 {
 	struct ifnet		*ifp;
@@ -3616,6 +3761,8 @@
 	}
 	if ((ifp->if_capenable & IFCAP_WOL) != 0) {
 		re_set_rxmode(sc);
+		if ((sc->rl_flags & RL_FLAG_WOL_MANLINK) != 0)
+			re_set_linkspeed(sc);
 		if ((sc->rl_flags & RL_FLAG_WOLRXENB) != 0)
 			CSR_WRITE_1(sc, RL_COMMAND, RL_CMD_RX_ENB);
 	}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/sfxge/common/efsys.h
--- a/head/sys/dev/sfxge/common/efsys.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/sfxge/common/efsys.h	Tue Dec 06 20:26:16 2011 +0200
@@ -25,14 +25,13 @@
  * 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: head/sys/dev/sfxge/common/efsys.h 228078 2011-11-28 17:19:05Z philip $
  */
 
 #ifndef	_SYS_EFSYS_H
 #define	_SYS_EFSYS_H
 
-#include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/sfxge/common/efsys.h 227641 2011-11-17 22:59:16Z marius $");
-
 #ifdef	__cplusplus
 extern "C" {
 #endif
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/sfxge/common/efx.h
--- a/head/sys/dev/sfxge/common/efx.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/sfxge/common/efx.h	Tue Dec 06 20:26:16 2011 +0200
@@ -21,6 +21,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: head/sys/dev/sfxge/common/efx.h 228078 2011-11-28 17:19:05Z philip $
  */
 
 #ifndef	_SYS_EFX_H
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/sfxge/common/efx_bootcfg.c
--- a/head/sys/dev/sfxge/common/efx_bootcfg.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/sfxge/common/efx_bootcfg.c	Tue Dec 06 20:26:16 2011 +0200
@@ -23,6 +23,9 @@
  * SUCH DAMAGE.
  */
 
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD: head/sys/dev/sfxge/common/efx_bootcfg.c 228078 2011-11-28 17:19:05Z philip $");
+
 #include "efsys.h"
 #include "efx.h"
 #include "efx_types.h"
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/sfxge/common/efx_ev.c
--- a/head/sys/dev/sfxge/common/efx_ev.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/sfxge/common/efx_ev.c	Tue Dec 06 20:26:16 2011 +0200
@@ -23,6 +23,9 @@
  * SUCH DAMAGE.
  */
 
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD: head/sys/dev/sfxge/common/efx_ev.c 228078 2011-11-28 17:19:05Z philip $");
+
 #include "efsys.h"
 #include "efx.h"
 #include "efx_types.h"
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/sfxge/common/efx_filter.c
--- a/head/sys/dev/sfxge/common/efx_filter.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/sfxge/common/efx_filter.c	Tue Dec 06 20:26:16 2011 +0200
@@ -23,6 +23,9 @@
  * SUCH DAMAGE.
  */
 
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD: head/sys/dev/sfxge/common/efx_filter.c 228078 2011-11-28 17:19:05Z philip $");
+
 #include "efsys.h"
 #include "efx.h"
 #include "efx_types.h"
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/sfxge/common/efx_impl.h
--- a/head/sys/dev/sfxge/common/efx_impl.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/sfxge/common/efx_impl.h	Tue Dec 06 20:26:16 2011 +0200
@@ -21,6 +21,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: head/sys/dev/sfxge/common/efx_impl.h 228078 2011-11-28 17:19:05Z philip $
  */
 
 #ifndef	_SYS_EFX_IMPL_H
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/sfxge/common/efx_intr.c
--- a/head/sys/dev/sfxge/common/efx_intr.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/sfxge/common/efx_intr.c	Tue Dec 06 20:26:16 2011 +0200
@@ -23,6 +23,9 @@
  * SUCH DAMAGE.
  */
 
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD: head/sys/dev/sfxge/common/efx_intr.c 228078 2011-11-28 17:19:05Z philip $");
+
 #include "efsys.h"
 #include "efx.h"
 #include "efx_types.h"
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/sfxge/common/efx_mac.c
--- a/head/sys/dev/sfxge/common/efx_mac.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/sfxge/common/efx_mac.c	Tue Dec 06 20:26:16 2011 +0200
@@ -23,6 +23,9 @@
  * SUCH DAMAGE.
  */
 
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD: head/sys/dev/sfxge/common/efx_mac.c 228078 2011-11-28 17:19:05Z philip $");
+
 #include "efsys.h"
 #include "efx.h"
 #include "efx_types.h"
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/sfxge/common/efx_mcdi.c
--- a/head/sys/dev/sfxge/common/efx_mcdi.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/sfxge/common/efx_mcdi.c	Tue Dec 06 20:26:16 2011 +0200
@@ -23,6 +23,9 @@
  * SUCH DAMAGE.
  */
 
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD: head/sys/dev/sfxge/common/efx_mcdi.c 228078 2011-11-28 17:19:05Z philip $");
+
 #include "efsys.h"
 #include "efx.h"
 #include "efx_types.h"
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/sfxge/common/efx_mcdi.h
--- a/head/sys/dev/sfxge/common/efx_mcdi.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/sfxge/common/efx_mcdi.h	Tue Dec 06 20:26:16 2011 +0200
@@ -21,6 +21,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: head/sys/dev/sfxge/common/efx_mcdi.h 228078 2011-11-28 17:19:05Z philip $
  */
 
 #ifndef _SYS_EFX_MCDI_H
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/sfxge/common/efx_mon.c
--- a/head/sys/dev/sfxge/common/efx_mon.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/sfxge/common/efx_mon.c	Tue Dec 06 20:26:16 2011 +0200
@@ -23,6 +23,9 @@
  * SUCH DAMAGE.
  */
 
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD: head/sys/dev/sfxge/common/efx_mon.c 228078 2011-11-28 17:19:05Z philip $");
+
 #include "efsys.h"
 #include "efx.h"
 #include "efx_types.h"
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/sfxge/common/efx_nic.c
--- a/head/sys/dev/sfxge/common/efx_nic.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/sfxge/common/efx_nic.c	Tue Dec 06 20:26:16 2011 +0200
@@ -23,6 +23,9 @@
  * SUCH DAMAGE.
  */
 
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD: head/sys/dev/sfxge/common/efx_nic.c 228078 2011-11-28 17:19:05Z philip $");
+
 #include "efsys.h"
 #include "efx.h"
 #include "efx_types.h"
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/sfxge/common/efx_nvram.c
--- a/head/sys/dev/sfxge/common/efx_nvram.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/sfxge/common/efx_nvram.c	Tue Dec 06 20:26:16 2011 +0200
@@ -23,6 +23,9 @@
  * SUCH DAMAGE.
  */
 
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD: head/sys/dev/sfxge/common/efx_nvram.c 228078 2011-11-28 17:19:05Z philip $");
+
 #include "efsys.h"
 #include "efx.h"
 #include "efx_types.h"
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/sfxge/common/efx_phy.c
--- a/head/sys/dev/sfxge/common/efx_phy.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/sfxge/common/efx_phy.c	Tue Dec 06 20:26:16 2011 +0200
@@ -23,6 +23,9 @@
  * SUCH DAMAGE.
  */
 
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD: head/sys/dev/sfxge/common/efx_phy.c 228078 2011-11-28 17:19:05Z philip $");
+
 #include "efsys.h"
 #include "efx.h"
 #include "efx_types.h"
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/sfxge/common/efx_port.c
--- a/head/sys/dev/sfxge/common/efx_port.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/sfxge/common/efx_port.c	Tue Dec 06 20:26:16 2011 +0200
@@ -23,6 +23,9 @@
  * SUCH DAMAGE.
  */
 
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD: head/sys/dev/sfxge/common/efx_port.c 228078 2011-11-28 17:19:05Z philip $");
+
 #include "efsys.h"
 #include "efx.h"
 #include "efx_types.h"
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/sfxge/common/efx_regs.h
--- a/head/sys/dev/sfxge/common/efx_regs.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/sfxge/common/efx_regs.h	Tue Dec 06 20:26:16 2011 +0200
@@ -21,6 +21,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: head/sys/dev/sfxge/common/efx_regs.h 228078 2011-11-28 17:19:05Z philip $
  */
 
 #ifndef	_SYS_EFX_REGS_H
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/sfxge/common/efx_regs_ef10.h
--- a/head/sys/dev/sfxge/common/efx_regs_ef10.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/sfxge/common/efx_regs_ef10.h	Tue Dec 06 20:26:16 2011 +0200
@@ -21,6 +21,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: head/sys/dev/sfxge/common/efx_regs_ef10.h 228078 2011-11-28 17:19:05Z philip $
  */
 
 #ifndef	_SYS_EFX_EF10_REGS_H
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/sfxge/common/efx_regs_mcdi.h
--- a/head/sys/dev/sfxge/common/efx_regs_mcdi.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/sfxge/common/efx_regs_mcdi.h	Tue Dec 06 20:26:16 2011 +0200
@@ -21,10 +21,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.
+ *
+ * $FreeBSD: head/sys/dev/sfxge/common/efx_regs_mcdi.h 228078 2011-11-28 17:19:05Z philip $
  */
 
-/*! \cidoxg_firmware_mc_cmd */
-
 #ifndef _SIENA_MC_DRIVER_PCOL_H
 #define	_SIENA_MC_DRIVER_PCOL_H
 
@@ -2783,4 +2783,3 @@
 #define	MC_CMD_TCM_TXQ_INIT_OUT_LEN 0
 
 #endif /* _SIENA_MC_DRIVER_PCOL_H */
-/*! \cidoxg_end */
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/sfxge/common/efx_regs_pci.h
--- a/head/sys/dev/sfxge/common/efx_regs_pci.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/sfxge/common/efx_regs_pci.h	Tue Dec 06 20:26:16 2011 +0200
@@ -21,6 +21,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: head/sys/dev/sfxge/common/efx_regs_pci.h 228078 2011-11-28 17:19:05Z philip $
  */
 
 #ifndef	_SYS_EFX_REGS_PCI_H
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/sfxge/common/efx_rx.c
--- a/head/sys/dev/sfxge/common/efx_rx.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/sfxge/common/efx_rx.c	Tue Dec 06 20:26:16 2011 +0200
@@ -23,6 +23,9 @@
  * SUCH DAMAGE.
  */
 
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD: head/sys/dev/sfxge/common/efx_rx.c 228078 2011-11-28 17:19:05Z philip $");
+
 #include "efsys.h"
 #include "efx.h"
 #include "efx_types.h"
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/sfxge/common/efx_sram.c
--- a/head/sys/dev/sfxge/common/efx_sram.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/sfxge/common/efx_sram.c	Tue Dec 06 20:26:16 2011 +0200
@@ -23,6 +23,9 @@
  * SUCH DAMAGE.
  */
 
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD: head/sys/dev/sfxge/common/efx_sram.c 228078 2011-11-28 17:19:05Z philip $");
+
 #include "efsys.h"
 #include "efx.h"
 #include "efx_types.h"
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/sfxge/common/efx_tx.c
--- a/head/sys/dev/sfxge/common/efx_tx.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/sfxge/common/efx_tx.c	Tue Dec 06 20:26:16 2011 +0200
@@ -23,6 +23,9 @@
  * SUCH DAMAGE.
  */
 
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD: head/sys/dev/sfxge/common/efx_tx.c 228078 2011-11-28 17:19:05Z philip $");
+
 #include "efsys.h"
 #include "efx.h"
 #include "efx_types.h"
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/sfxge/common/efx_types.h
--- a/head/sys/dev/sfxge/common/efx_types.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/sfxge/common/efx_types.h	Tue Dec 06 20:26:16 2011 +0200
@@ -23,6 +23,8 @@
  * SUCH DAMAGE.
  *
  * Ackowledgement to Fen Systems Ltd.
+ *
+ * $FreeBSD: head/sys/dev/sfxge/common/efx_types.h 228078 2011-11-28 17:19:05Z philip $
  */
 
 #ifndef	_SYS_EFX_TYPES_H
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/sfxge/common/efx_vpd.c
--- a/head/sys/dev/sfxge/common/efx_vpd.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/sfxge/common/efx_vpd.c	Tue Dec 06 20:26:16 2011 +0200
@@ -23,6 +23,9 @@
  * SUCH DAMAGE.
  */
 
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD: head/sys/dev/sfxge/common/efx_vpd.c 228078 2011-11-28 17:19:05Z philip $");
+
 #include "efsys.h"
 #include "efx.h"
 #include "efx_types.h"
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/sfxge/common/efx_wol.c
--- a/head/sys/dev/sfxge/common/efx_wol.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/sfxge/common/efx_wol.c	Tue Dec 06 20:26:16 2011 +0200
@@ -23,6 +23,9 @@
  * SUCH DAMAGE.
  */
 
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD: head/sys/dev/sfxge/common/efx_wol.c 228078 2011-11-28 17:19:05Z philip $");
+
 #include "efsys.h"
 #include "efx.h"
 #include "efx_types.h"
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/sfxge/common/siena_flash.h
--- a/head/sys/dev/sfxge/common/siena_flash.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/sfxge/common/siena_flash.h	Tue Dec 06 20:26:16 2011 +0200
@@ -21,9 +21,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.
+ *
+ * $FreeBSD: head/sys/dev/sfxge/common/siena_flash.h 228078 2011-11-28 17:19:05Z philip $
  */
 
-
 #ifndef	_SYS_SIENA_FLASH_H
 #define	_SYS_SIENA_FLASH_H
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/sfxge/common/siena_impl.h
--- a/head/sys/dev/sfxge/common/siena_impl.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/sfxge/common/siena_impl.h	Tue Dec 06 20:26:16 2011 +0200
@@ -21,6 +21,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: head/sys/dev/sfxge/common/siena_impl.h 228078 2011-11-28 17:19:05Z philip $
  */
 
 #ifndef _SYS_SIENA_IMPL_H
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/sfxge/common/siena_mac.c
--- a/head/sys/dev/sfxge/common/siena_mac.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/sfxge/common/siena_mac.c	Tue Dec 06 20:26:16 2011 +0200
@@ -22,6 +22,10 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  */
+
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD: head/sys/dev/sfxge/common/siena_mac.c 228078 2011-11-28 17:19:05Z philip $");
+
 #include "efsys.h"
 #include "efx.h"
 #include "efx_impl.h"
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/sfxge/common/siena_mon.c
--- a/head/sys/dev/sfxge/common/siena_mon.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/sfxge/common/siena_mon.c	Tue Dec 06 20:26:16 2011 +0200
@@ -22,6 +22,10 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  */
+
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD: head/sys/dev/sfxge/common/siena_mon.c 228078 2011-11-28 17:19:05Z philip $");
+
 #include "efsys.h"
 #include "efx.h"
 #include "efx_impl.h"
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/sfxge/common/siena_nic.c
--- a/head/sys/dev/sfxge/common/siena_nic.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/sfxge/common/siena_nic.c	Tue Dec 06 20:26:16 2011 +0200
@@ -22,6 +22,10 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  */
+
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD: head/sys/dev/sfxge/common/siena_nic.c 228078 2011-11-28 17:19:05Z philip $");
+
 #include "efsys.h"
 #include "efx.h"
 #include "efx_impl.h"
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/sfxge/common/siena_nvram.c
--- a/head/sys/dev/sfxge/common/siena_nvram.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/sfxge/common/siena_nvram.c	Tue Dec 06 20:26:16 2011 +0200
@@ -23,6 +23,9 @@
  * SUCH DAMAGE.
  */
 
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD: head/sys/dev/sfxge/common/siena_nvram.c 228078 2011-11-28 17:19:05Z philip $");
+
 #include "efsys.h"
 #include "efx.h"
 #include "efx_types.h"
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/sfxge/common/siena_phy.c
--- a/head/sys/dev/sfxge/common/siena_phy.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/sfxge/common/siena_phy.c	Tue Dec 06 20:26:16 2011 +0200
@@ -22,6 +22,10 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  */
+
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD: head/sys/dev/sfxge/common/siena_phy.c 228078 2011-11-28 17:19:05Z philip $");
+
 #include "efsys.h"
 #include "efx.h"
 #include "efx_impl.h"
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/sfxge/common/siena_sram.c
--- a/head/sys/dev/sfxge/common/siena_sram.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/sfxge/common/siena_sram.c	Tue Dec 06 20:26:16 2011 +0200
@@ -22,6 +22,10 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  */
+
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD: head/sys/dev/sfxge/common/siena_sram.c 228078 2011-11-28 17:19:05Z philip $");
+
 #include "efsys.h"
 #include "efx.h"
 #include "efx_impl.h"
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/sfxge/common/siena_vpd.c
--- a/head/sys/dev/sfxge/common/siena_vpd.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/sfxge/common/siena_vpd.c	Tue Dec 06 20:26:16 2011 +0200
@@ -23,6 +23,9 @@
  * SUCH DAMAGE.
  */
 
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD: head/sys/dev/sfxge/common/siena_vpd.c 228078 2011-11-28 17:19:05Z philip $");
+
 #include "efsys.h"
 #include "efx.h"
 #include "efx_types.h"
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/uart/uart_bus_fdt.c
--- a/head/sys/dev/uart/uart_bus_fdt.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/uart/uart_bus_fdt.c	Tue Dec 06 20:26:16 2011 +0200
@@ -28,7 +28,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/sys/dev/uart/uart_bus_fdt.c 228201 2011-12-02 15:24:39Z jchandra $");
 
 #include <sys/param.h>
 #include <sys/bus.h>
@@ -155,11 +155,11 @@
 	/*
 	 * Retrieve /chosen/std{in,out}.
 	 */
-	if ((chosen = OF_finddevice("/chosen")) == 0)
+	if ((chosen = OF_finddevice("/chosen")) == -1)
 		return (ENXIO);
 	if (OF_getprop(chosen, "stdin", buf, sizeof(buf)) <= 0)
 		return (ENXIO);
-	if ((node = OF_finddevice(buf)) == 0)
+	if ((node = OF_finddevice(buf)) == -1)
 		return (ENXIO);
 	if (OF_getprop(chosen, "stdout", buf, sizeof(buf)) <= 0)
 		return (ENXIO);
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/usb/net/ruephy.c
--- a/head/sys/dev/usb/net/ruephy.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/usb/net/ruephy.c	Tue Dec 06 20:26:16 2011 +0200
@@ -26,7 +26,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/usb/net/ruephy.c 226154 2011-10-08 12:33:10Z marius $");
+__FBSDID("$FreeBSD: head/sys/dev/usb/net/ruephy.c 227908 2011-11-23 20:27:26Z marius $");
 
 /*
  * driver for RealTek RTL8150 internal PHY
@@ -61,7 +61,7 @@
 	DEVMETHOD(device_attach,	ruephy_attach),
 	DEVMETHOD(device_detach,	mii_phy_detach),
 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
-	{ 0, 0 }
+	DEVMETHOD_END
 };
 
 static devclass_t ruephy_devclass;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/usb/quirk/usb_quirk.c
--- a/head/sys/dev/usb/quirk/usb_quirk.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/usb/quirk/usb_quirk.c	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-/* $FreeBSD: head/sys/dev/usb/quirk/usb_quirk.c 227610 2011-11-17 10:46:51Z hselasky $ */
+/* $FreeBSD: head/sys/dev/usb/quirk/usb_quirk.c 228243 2011-12-03 19:56:52Z emaste $ */
 /*-
  * Copyright (c) 1998 The NetBSD Foundation, Inc. All rights reserved.
  * Copyright (c) 1998 Lennart Augustsson. All rights reserved.
@@ -248,6 +248,7 @@
 	USB_QUIRK(MICROTECH, DPCM, 0x0000, 0xffff, UQ_MSC_FORCE_WIRE_CBI,
 	    UQ_MSC_FORCE_PROTO_SCSI, UQ_MSC_NO_TEST_UNIT_READY,
 	    UQ_MSC_NO_START_STOP),
+	USB_QUIRK(MICRON, REALSSD, 0x0000, 0xffff, UQ_MSC_NO_SYNC_CACHE),
 	USB_QUIRK(MICROTECH, SCSIDB25, 0x0000, 0xffff, UQ_MSC_FORCE_WIRE_BBB,
 	    UQ_MSC_FORCE_PROTO_SCSI),
 	USB_QUIRK(MICROTECH, SCSIHD50, 0x0000, 0xffff, UQ_MSC_FORCE_WIRE_BBB,
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/usb/template/usb_template.c
--- a/head/sys/dev/usb/template/usb_template.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/usb/template/usb_template.c	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-/* $FreeBSD: head/sys/dev/usb/template/usb_template.c 227461 2011-11-12 08:16:45Z hselasky $ */
+/* $FreeBSD: head/sys/dev/usb/template/usb_template.c 228304 2011-12-06 08:08:52Z hselasky $ */
 /*-
  * Copyright (c) 2007 Hans Petter Selasky. All rights reserved.
  *
@@ -260,7 +260,7 @@
 					ed->bInterval = 1;	/* 1 ms */
 					break;
 				default:
-					ed->bInterval = 8;	/* 8*125 us */
+					ed->bInterval = 4;	/* 1 ms */
 					break;
 				}
 				break;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/usb/template/usb_template_kbd.c
--- a/head/sys/dev/usb/template/usb_template_kbd.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/usb/template/usb_template_kbd.c	Tue Dec 06 20:26:16 2011 +0200
@@ -1,5 +1,5 @@
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/usb/template/usb_template_kbd.c 223472 2011-06-23 10:35:45Z hselasky $");
+__FBSDID("$FreeBSD: head/sys/dev/usb/template/usb_template_kbd.c 228304 2011-12-06 08:08:52Z hselasky $");
 
 /*-
  * Copyright (c) 2010 Hans Petter Selasky. All rights reserved.
@@ -89,9 +89,9 @@
 };
 
 static const struct usb_temp_interval keyboard_intr_interval = {
-	.bInterval[USB_SPEED_LOW] = 2,	/* ms */
-	.bInterval[USB_SPEED_FULL] = 2,
-	.bInterval[USB_SPEED_HIGH] = 2 * 8,
+	.bInterval[USB_SPEED_LOW] = 2,	/* 2 ms */
+	.bInterval[USB_SPEED_FULL] = 2,	/* 2 ms */
+	.bInterval[USB_SPEED_HIGH] = 5,	/* 2 ms */
 };
 
 /* The following HID descriptor was dumped from a HP keyboard. */
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/usb/template/usb_template_modem.c
--- a/head/sys/dev/usb/template/usb_template_modem.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/usb/template/usb_template_modem.c	Tue Dec 06 20:26:16 2011 +0200
@@ -1,5 +1,5 @@
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/usb/template/usb_template_modem.c 223467 2011-06-23 07:54:03Z hselasky $");
+__FBSDID("$FreeBSD: head/sys/dev/usb/template/usb_template_modem.c 228304 2011-12-06 08:08:52Z hselasky $");
 
 /*-
  * Copyright (c) 2010 Hans Petter Selasky. All rights reserved.
@@ -98,9 +98,9 @@
 };
 
 static const struct usb_temp_interval modem_intr_interval = {
-	.bInterval[USB_SPEED_LOW] = 10,
-	.bInterval[USB_SPEED_FULL] = 10,
-	.bInterval[USB_SPEED_HIGH] = 10 * 8,
+	.bInterval[USB_SPEED_LOW] = 8,	/* 8ms */
+	.bInterval[USB_SPEED_FULL] = 8,	/* 8ms */
+	.bInterval[USB_SPEED_HIGH] = 7,	/* 8ms */
 };
 
 static const struct usb_temp_endpoint_desc modem_ep_0 = {
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/usb/template/usb_template_mouse.c
--- a/head/sys/dev/usb/template/usb_template_mouse.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/usb/template/usb_template_mouse.c	Tue Dec 06 20:26:16 2011 +0200
@@ -1,5 +1,5 @@
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/usb/template/usb_template_mouse.c 223472 2011-06-23 10:35:45Z hselasky $");
+__FBSDID("$FreeBSD: head/sys/dev/usb/template/usb_template_mouse.c 228304 2011-12-06 08:08:52Z hselasky $");
 
 /*-
  * Copyright (c) 2010 Hans Petter Selasky. All rights reserved.
@@ -101,9 +101,9 @@
 };
 
 static const struct usb_temp_interval mouse_intr_interval = {
-	.bInterval[USB_SPEED_LOW] = 2,
-	.bInterval[USB_SPEED_FULL] = 2,
-	.bInterval[USB_SPEED_HIGH] = 2 * 8,
+	.bInterval[USB_SPEED_LOW] = 2,		/* 2ms */
+	.bInterval[USB_SPEED_FULL] = 2,		/* 2ms */
+	.bInterval[USB_SPEED_HIGH] = 5,		/* 2ms */
 };
 
 static const struct usb_temp_endpoint_desc mouse_ep_0 = {
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/usb/usb_msctest.c
--- a/head/sys/dev/usb/usb_msctest.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/usb/usb_msctest.c	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-/* $FreeBSD: head/sys/dev/usb/usb_msctest.c 227461 2011-11-12 08:16:45Z hselasky $ */
+/* $FreeBSD: head/sys/dev/usb/usb_msctest.c 228232 2011-12-03 14:54:44Z hselasky $ */
 /*-
  * Copyright (c) 2008,2011 Hans Petter Selasky. All rights reserved.
  *
@@ -477,7 +477,7 @@
 	sc->cmd_len = cmd_len;
 	memset(&sc->cbw.CBWCDB, 0, sizeof(sc->cbw.CBWCDB));
 	memcpy(&sc->cbw.CBWCDB, cmd_ptr, cmd_len);
-	DPRINTFN(1, "SCSI cmd = %*D\n", (int)cmd_len, &sc->cbw.CBWCDB, ":");
+	DPRINTFN(1, "SCSI cmd = %*D\n", (int)cmd_len, (char *)sc->cbw.CBWCDB, ":");
 
 	mtx_lock(&sc->mtx);
 	usbd_transfer_start(sc->xfer[sc->state]);
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/usb/usb_transfer.h
--- a/head/sys/dev/usb/usb_transfer.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/usb/usb_transfer.h	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-/* $FreeBSD$ */
+/* $FreeBSD: head/sys/dev/usb/usb_transfer.h 228056 2011-11-28 09:54:41Z hselasky $ */
 /*-
  * Copyright (c) 2008 Hans Petter Selasky. All rights reserved.
  *
@@ -28,6 +28,120 @@
 #define	_USB_TRANSFER_H_
 
 /*
+ * Definition of internal USB transfer states:
+ * ===========================================
+ *
+ * The main reason there are many USB states is that we are allowed to
+ * cancel USB transfers, then start the USB transfer again and that
+ * this state transaction cannot always be done in a single atomic
+ * operation without blocking the calling thread. One reason for this
+ * is that the USB hardware sometimes needs to wait for DMA
+ * controllers to finish which is done asynchronously and grows the
+ * statemachine.
+ *
+ * When extending the following statemachine there are basically two
+ * things you should think about: Which states should be executed or
+ * modified in case of USB transfer stop and which states should be
+ * executed or modified in case of USB transfer start. Also respect
+ * the "can_cancel_immed" flag which basically tells if you can go
+ * directly from a wait state to the cancelling states.
+ */
+
+enum {
+	/* XFER start execute state */
+
+	/* USB_ST_SETUP = 0 (already defined) */
+
+	/* XFER transferred execute state */
+
+	/* USB_ST_TRANSFERRED = 1 (already defined) */
+
+	/* XFER error execute state */
+
+	/* USB_ST_ERROR = 2 (already defined) */
+
+	/* XFER restart after error execute state */
+
+	USB_ST_RESTART = 8,
+
+	/* XFER transfer idle state */
+
+	USB_ST_WAIT_SETUP,
+
+	/* Other XFER execute states */
+
+	USB_ST_PIPE_OPEN = 16,
+	USB_ST_PIPE_OPEN_ERROR,
+	USB_ST_PIPE_OPEN_RESTART,
+
+	USB_ST_BDMA_LOAD,
+	USB_ST_BDMA_LOAD_ERROR,
+	USB_ST_BDMA_LOAD_RESTART,
+
+	USB_ST_IVAL_DLY,
+	USB_ST_IVAL_DLY_ERROR,
+	USB_ST_IVAL_DLY_RESTART,
+
+	USB_ST_PIPE_STALL,
+	USB_ST_PIPE_STALL_ERROR,
+	USB_ST_PIPE_STALL_RESTART,
+
+	USB_ST_ENTER,
+	USB_ST_ENTER_ERROR,
+	USB_ST_ENTER_RESTART,
+
+	USB_ST_START,
+	USB_ST_START_ERROR,
+	USB_ST_START_RESTART,
+
+	USB_ST_PIPE_CLOSE,
+	USB_ST_PIPE_CLOSE_ERROR,
+	USB_ST_PIPE_CLOSE_RESTART,
+
+	USB_ST_BDMA_DLY,
+	USB_ST_BDMA_DLY_ERROR,
+	USB_ST_BDMA_DLY_RESTART,
+
+	/* XFER transfer wait states */
+
+	USB_ST_WAIT_PIPE_OPEN = 64,
+	USB_ST_WAIT_PIPE_OPEN_ERROR,
+	USB_ST_WAIT_PIPE_OPEN_RESTART,
+
+	USB_ST_WAIT_BDMA_LOAD,
+	USB_ST_WAIT_BDMA_LOAD_ERROR,
+	USB_ST_WAIT_BDMA_LOAD_RESTART,
+
+	USB_ST_WAIT_IVAL_DLY,
+	USB_ST_WAIT_IVAL_DLY_ERROR,
+	USB_ST_WAIT_IVAL_DLY_RESTART,
+
+	USB_ST_WAIT_PIPE_STALL,
+	USB_ST_WAIT_PIPE_STALL_ERROR,
+	USB_ST_WAIT_PIPE_STALL_RESTART,
+
+	USB_ST_WAIT_ENTER,
+	USB_ST_WAIT_ENTER_ERROR,
+	USB_ST_WAIT_ENTER_RESTART,
+
+	USB_ST_WAIT_START,
+	USB_ST_WAIT_START_ERROR,
+	USB_ST_WAIT_START_RESTART,
+
+	USB_ST_WAIT_PIPE_CLOSE,
+	USB_ST_WAIT_PIPE_CLOSE_ERROR,
+	USB_ST_WAIT_PIPE_CLOSE_RESTART,
+
+	USB_ST_WAIT_BDMA_DLY,
+	USB_ST_WAIT_BDMA_DLY_ERROR,
+	USB_ST_WAIT_BDMA_DLY_RESTART,
+
+	USB_ST_WAIT_TRANSFERRED,
+	USB_ST_WAIT_TRANSFERRED_ERROR,
+	USB_ST_WAIT_TRANSFERRED_RESTART,
+};
+
+/*
  * The following structure defines the messages that is used to signal
  * the "done_p" USB process.
  */
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/usb/usbdevs
--- a/head/sys/dev/usb/usbdevs	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/usb/usbdevs	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-$FreeBSD: head/sys/dev/usb/usbdevs 227781 2011-11-21 07:50:29Z hselasky $
+$FreeBSD: head/sys/dev/usb/usbdevs 228243 2011-12-03 19:56:52Z emaste $
 /* $NetBSD: usbdevs,v 1.392 2004/12/29 08:38:44 imp Exp $ */
 
 /*-
@@ -317,6 +317,7 @@
 vendor ALARIS		0x0620	Alaris
 vendor APEX		0x0624	Apex
 vendor CREATIVE3	0x062a	Creative Labs
+vendor MICRON		0x0634	Micron Technology
 vendor VIVITAR		0x0636	Vivitar
 vendor GUNZE		0x0637	Gunze Electronics USA
 vendor AVISION		0x0638	Avision
@@ -2229,6 +2230,9 @@
 product MSI RT2573_3		0xa861	RT2573
 product MSI RT2573_4		0xa874	RT2573
 
+/* Micron products */
+product MICRON REALSSD		0x0655	Real SSD eUSB
+
 /* Microsoft products */
 product MICROSOFT SIDEPREC	0x0008	SideWinder Precision Pro
 product MICROSOFT INTELLIMOUSE	0x0009	IntelliMouse
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/usb/wlan/if_urtw.c
--- a/head/sys/dev/usb/wlan/if_urtw.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/usb/wlan/if_urtw.c	Tue Dec 06 20:26:16 2011 +0200
@@ -15,7 +15,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/usb/wlan/if_urtw.c 227461 2011-11-12 08:16:45Z hselasky $");
+__FBSDID("$FreeBSD: head/sys/dev/usb/wlan/if_urtw.c 228195 2011-12-02 02:19:03Z kevlo $");
 #include <sys/param.h>
 #include <sys/sockio.h>
 #include <sys/sysctl.h>
@@ -1053,10 +1053,10 @@
 
 	if (!(sc->sc_flags & URTW_INIT_ONCE)) {
 		ret = urtw_alloc_rx_data_list(sc);
-		if (error != 0)
+		if (ret != 0)
 			goto fail;
 		ret = urtw_alloc_tx_data_list(sc);
-		if (error != 0)
+		if (ret != 0)
 			goto fail;
 		sc->sc_flags |= URTW_INIT_ONCE;
 	}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/usb/wlan/if_zyd.c
--- a/head/sys/dev/usb/wlan/if_zyd.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/usb/wlan/if_zyd.c	Tue Dec 06 20:26:16 2011 +0200
@@ -1,6 +1,6 @@
 /*	$OpenBSD: if_zyd.c,v 1.52 2007/02/11 00:08:04 jsg Exp $	*/
 /*	$NetBSD: if_zyd.c,v 1.7 2007/06/21 04:04:29 kiyohara Exp $	*/
-/*	$FreeBSD: head/sys/dev/usb/wlan/if_zyd.c 227461 2011-11-12 08:16:45Z hselasky $	*/
+/*	$FreeBSD: head/sys/dev/usb/wlan/if_zyd.c 228303 2011-12-06 07:55:25Z hselasky $	*/
 
 /*-
  * Copyright (c) 2006 by Damien Bergamini <damien.bergamini at free.fr>
@@ -20,7 +20,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/usb/wlan/if_zyd.c 227461 2011-11-12 08:16:45Z hselasky $");
+__FBSDID("$FreeBSD: head/sys/dev/usb/wlan/if_zyd.c 228303 2011-12-06 07:55:25Z hselasky $");
 
 /*
  * ZyDAS ZD1211/ZD1211B USB WLAN driver.
@@ -686,7 +686,7 @@
 				memcpy(rqp->odata, cmd->data, rqp->olen);
 				DPRINTF(sc, ZYD_DEBUG_CMD,
 				    "command %p complete, data = %*D \n",
-				    rqp, rqp->olen, rqp->odata, ":");
+				    rqp, rqp->olen, (char *)rqp->odata, ":");
 				wakeup(rqp);	/* wakeup caller */
 				break;
 			}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/virtio/balloon/virtio_balloon.c
--- a/head/sys/dev/virtio/balloon/virtio_balloon.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/virtio/balloon/virtio_balloon.c	Tue Dec 06 20:26:16 2011 +0200
@@ -27,7 +27,7 @@
 /* Driver for VirtIO memory balloon devices. */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/virtio/balloon/virtio_balloon.c 227652 2011-11-18 05:43:43Z grehan $");
+__FBSDID("$FreeBSD: head/sys/dev/virtio/balloon/virtio_balloon.c 228301 2011-12-06 06:28:32Z grehan $");
 
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -475,7 +475,6 @@
 	virtio_write_dev_config_4(sc->vtballoon_dev,
 	    offsetof(struct virtio_balloon_config, actual),
 	    htole32(sc->vtballoon_current_npages));
-
 }
 
 static int
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/virtio/balloon/virtio_balloon.h
--- a/head/sys/dev/virtio/balloon/virtio_balloon.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/virtio/balloon/virtio_balloon.h	Tue Dec 06 20:26:16 2011 +0200
@@ -1,8 +1,31 @@
-/*
+/*-
  * This header is BSD licensed so anyone can use the definitions to implement
  * compatible drivers/servers.
  *
- * $FreeBSD: head/sys/dev/virtio/balloon/virtio_balloon.h 227652 2011-11-18 05:43:43Z grehan $
+ * 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 IBM 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 COPYRIGHT HOLDERS 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 IBM 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: head/sys/dev/virtio/balloon/virtio_balloon.h 228301 2011-12-06 06:28:32Z grehan $
  */
 
 #ifndef _VIRTIO_BALLOON_H
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/virtio/block/virtio_blk.c
--- a/head/sys/dev/virtio/block/virtio_blk.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/virtio/block/virtio_blk.c	Tue Dec 06 20:26:16 2011 +0200
@@ -27,7 +27,7 @@
 /* Driver for VirtIO block devices. */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/virtio/block/virtio_blk.c 227652 2011-11-18 05:43:43Z grehan $");
+__FBSDID("$FreeBSD: head/sys/dev/virtio/block/virtio_blk.c 228301 2011-12-06 06:28:32Z grehan $");
 
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -87,9 +87,7 @@
 	struct taskqueue	*vtblk_tq;
 	struct task		 vtblk_intr_task;
 
-	int			 vtblk_sector_size;
 	int			 vtblk_max_nsegs;
-	int			 vtblk_unit;
 	int			 vtblk_request_count;
 
 	struct vtblk_request	 vtblk_dump_request;
@@ -185,7 +183,6 @@
 				mtx_init(VTBLK_MTX((_sc)), (_name), \
 				    "VTBLK Lock", MTX_DEF)
 #define VTBLK_LOCK(_sc)		mtx_lock(VTBLK_MTX((_sc)))
-#define VTBLK_TRYLOCK(_sc)	mtx_trylock(VTBLK_MTX((_sc)))
 #define VTBLK_UNLOCK(_sc)	mtx_unlock(VTBLK_MTX((_sc)))
 #define VTBLK_LOCK_DESTROY(_sc)	mtx_destroy(VTBLK_MTX((_sc)))
 #define VTBLK_LOCK_ASSERT(_sc)	mtx_assert(VTBLK_MTX((_sc)), MA_OWNED)
@@ -281,7 +278,6 @@
 
 	sc = device_get_softc(dev);
 	sc->vtblk_dev = dev;
-	sc->vtblk_unit = device_get_unit(dev);
 
 	VTBLK_LOCK_INIT(sc, device_get_nameunit(dev));
 
@@ -299,13 +295,8 @@
 		sc->vtblk_flags |= VTBLK_FLAG_READONLY;
 
 	/* Get local copy of config. */
-	if (virtio_with_feature(dev, VIRTIO_BLK_F_TOPOLOGY) == 0) {
-		bzero(&blkcfg, sizeof(struct virtio_blk_config));
-		virtio_read_device_config(dev, 0, &blkcfg,
-		    offsetof(struct virtio_blk_config, physical_block_exp));
-	} else
-		virtio_read_device_config(dev, 0, &blkcfg,
-		    sizeof(struct virtio_blk_config));
+	virtio_read_device_config(dev, 0, &blkcfg,
+	    sizeof(struct virtio_blk_config));
 
 	/*
 	 * With the current sglist(9) implementation, it is not easy
@@ -498,12 +489,6 @@
 	if ((sc = dp->d_drv1) == NULL)
 		return (ENXIO);
 
-	if (VTBLK_TRYLOCK(sc) == 0) {
-		device_printf(sc->vtblk_dev,
-		    "softc already locked, cannot dump...\n");
-		return (EBUSY);
-	}
-
 	if ((sc->vtblk_flags & VTBLK_FLAG_DUMPING) == 0) {
 		vtblk_prepare_dump(sc);
 		sc->vtblk_flags |= VTBLK_FLAG_DUMPING;
@@ -622,7 +607,7 @@
 	dp->d_ioctl = vtblk_ioctl;
 	dp->d_strategy = vtblk_strategy;
 	dp->d_name = VTBLK_DISK_NAME;
-	dp->d_unit = sc->vtblk_unit;
+	dp->d_unit = device_get_unit(dev);
 	dp->d_drv1 = sc;
 
 	if ((sc->vtblk_flags & VTBLK_FLAG_READONLY) == 0)
@@ -632,10 +617,9 @@
 	dp->d_mediasize = blkcfg->capacity * 512;
 
 	if (virtio_with_feature(dev, VIRTIO_BLK_F_BLK_SIZE))
-		sc->vtblk_sector_size = blkcfg->blk_size;
+		dp->d_sectorsize = blkcfg->blk_size;
 	else
-		sc->vtblk_sector_size = 512;
-	dp->d_sectorsize = sc->vtblk_sector_size;
+		dp->d_sectorsize = 512;
 
 	/*
 	 * The VirtIO maximum I/O size is given in terms of segments.
@@ -905,8 +889,9 @@
 
 	VTBLK_LOCK(sc);
 	error = vtblk_poll_request(sc, req);
+	VTBLK_UNLOCK(sc);
+
 	vtblk_enqueue_request(sc, req);
-	VTBLK_UNLOCK(sc);
 
 	if (error) {
 		device_printf(sc->vtblk_dev,
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/virtio/block/virtio_blk.h
--- a/head/sys/dev/virtio/block/virtio_blk.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/virtio/block/virtio_blk.h	Tue Dec 06 20:26:16 2011 +0200
@@ -1,8 +1,31 @@
-/*
+/*-
  * This header is BSD licensed so anyone can use the definitions to implement
  * compatible drivers/servers.
  *
- * $FreeBSD: head/sys/dev/virtio/block/virtio_blk.h 227652 2011-11-18 05:43:43Z grehan $
+ * 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 IBM 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 COPYRIGHT HOLDERS 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 IBM 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: head/sys/dev/virtio/block/virtio_blk.h 228301 2011-12-06 06:28:32Z grehan $
  */
 
 #ifndef _VIRTIO_BLK_H
@@ -39,16 +62,6 @@
 
 	/* block size of device (if VIRTIO_BLK_F_BLK_SIZE) */
 	uint32_t blk_size;
-
-	/* the next 4 entries are guarded by VIRTIO_BLK_F_TOPOLOGY  */
-	/* exponent for physical block per logical block. */
-	uint8_t physical_block_exp;
-	/* alignment offset in logical blocks. */
-	uint8_t alignment_offset;
-	/* minimum I/O size without performance penalty in logical blocks. */
-	uint16_t min_io_size;
-	/* optimal sustained I/O size in logical blocks. */
-	uint32_t opt_io_size;
 } __packed;
 
 /*
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/virtio/network/if_vtnet.c
--- a/head/sys/dev/virtio/network/if_vtnet.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/virtio/network/if_vtnet.c	Tue Dec 06 20:26:16 2011 +0200
@@ -27,7 +27,7 @@
 /* Driver for VirtIO network devices. */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/virtio/network/if_vtnet.c 227652 2011-11-18 05:43:43Z grehan $");
+__FBSDID("$FreeBSD: head/sys/dev/virtio/network/if_vtnet.c 228301 2011-12-06 06:28:32Z grehan $");
 
 #ifdef HAVE_KERNEL_OPTION_HEADERS
 #include "opt_device_polling.h"
@@ -317,8 +317,20 @@
 	if (virtio_with_feature(dev, VIRTIO_NET_F_CTRL_VQ)) {
 		sc->vtnet_flags |= VTNET_FLAG_CTRL_VQ;
 
-		if (virtio_with_feature(dev, VIRTIO_NET_F_CTRL_RX))
+		if (virtio_with_feature(dev, VIRTIO_NET_F_CTRL_RX)) {
+			sc->vtnet_mac_filter = malloc(
+			    sizeof(struct vtnet_mac_filter), M_DEVBUF,
+			    M_NOWAIT | M_ZERO);
+			if (sc->vtnet_mac_filter == NULL) {
+				device_printf(dev,
+				    "cannot allocate mac filter table\n");
+				error = ENOMEM;
+				goto fail;
+			}
+
 			sc->vtnet_flags |= VTNET_FLAG_CTRL_RX;
+		}
+
 		if (virtio_with_feature(dev, VIRTIO_NET_F_CTRL_VLAN))
 			sc->vtnet_flags |= VTNET_FLAG_VLAN_FILTER;
 	}
@@ -505,7 +517,12 @@
 		sc->vtnet_vlan_detach = NULL;
 	}
 
-	if (ifp) {
+	if (sc->vtnet_mac_filter != NULL) {
+		free(sc->vtnet_mac_filter, M_DEVBUF);
+		sc->vtnet_mac_filter = NULL;
+	}
+
+	if (ifp != NULL) {
 		if_free(ifp);
 		sc->vtnet_ifp = NULL;
 	}
@@ -742,17 +759,11 @@
 
 	if (link && ((sc->vtnet_flags & VTNET_FLAG_LINK) == 0)) {
 		sc->vtnet_flags |= VTNET_FLAG_LINK;
-		if (bootverbose)
-			device_printf(dev, "Link is up\n");
-
 		if_link_state_change(ifp, LINK_STATE_UP);
 		if (!IFQ_DRV_IS_EMPTY(&ifp->if_snd))
 			vtnet_start_locked(ifp);
 	} else if (!link && (sc->vtnet_flags & VTNET_FLAG_LINK)) {
 		sc->vtnet_flags &= ~VTNET_FLAG_LINK;
-		if (bootverbose)
-			device_printf(dev, "Link is down\n");
-
 		if_link_state_change(ifp, LINK_STATE_DOWN);
 	}
 }
@@ -1105,7 +1116,7 @@
 		KASSERT(sc->vtnet_flags & VTNET_FLAG_LRO_NOMRG,
 		    ("chained Rx mbuf requested without LRO_NOMRG"));
 
-		for (i = 0; i < nbufs - 1; i++) {
+		for (i = 1; i < nbufs; i++) {
 			m = m_getjcl(M_DONTWAIT, MT_DATA, 0, clsize);
 			if (m == NULL)
 				goto fail;
@@ -1143,9 +1154,8 @@
 	clsize = sc->vtnet_rx_mbuf_size;
 	nreplace = 0;
 
-	if (m->m_next != NULL)
-		KASSERT(sc->vtnet_flags & VTNET_FLAG_LRO_NOMRG,
-		    ("chained Rx mbuf without LRO_NOMRG"));
+	KASSERT(sc->vtnet_flags & VTNET_FLAG_LRO_NOMRG ||
+	    m->m_next == NULL, ("chained Rx mbuf without LRO_NOMRG"));
 
 	/*
 	 * Since LRO_NOMRG mbuf chains are so large, we want to avoid
@@ -1275,8 +1285,8 @@
 	int offset, error;
 
 	VTNET_LOCK_ASSERT(sc);
-	if ((sc->vtnet_flags & VTNET_FLAG_LRO_NOMRG) == 0)
-		KASSERT(m->m_next == NULL, ("chained Rx mbuf"));
+	KASSERT(sc->vtnet_flags & VTNET_FLAG_LRO_NOMRG ||
+	    m->m_next == NULL, ("chained Rx mbuf without LRO_NOMRG"));
 
 	sglist_init(&sg, VTNET_MAX_RX_SEGS, segs);
 
@@ -1688,7 +1698,8 @@
 			break;
 	}
 
-	virtqueue_notify(vq);
+	if (deq > 0)
+		virtqueue_notify(vq);
 
 	if (rx_npktsp != NULL)
 		*rx_npktsp = rx_npkts;
@@ -1946,9 +1957,14 @@
 	struct mbuf *m;
 	int error;
 
+	m = *m_head;
+
 	txhdr = uma_zalloc(vtnet_tx_header_zone, M_NOWAIT | M_ZERO);
-	if (txhdr == NULL)
+	if (txhdr == NULL) {
+		*m_head = NULL;
+		m_freem(m);
 		return (ENOMEM);
+	}
 
 	/*
 	 * Always use the non-mergeable header to simplify things. When
@@ -1957,21 +1973,22 @@
 	 * the correct header size to the host.
 	 */
 	hdr = &txhdr->vth_uhdr.hdr;
-	m = *m_head;
-
-	error = ENOBUFS;
 
 	if (m->m_flags & M_VLANTAG) {
 		m = ether_vlanencap(m, m->m_pkthdr.ether_vtag);
-		if ((*m_head = m) == NULL)
+		if ((*m_head = m) == NULL) {
+			error = ENOBUFS;
 			goto fail;
+		}
 		m->m_flags &= ~M_VLANTAG;
 	}
 
 	if (m->m_pkthdr.csum_flags != 0) {
 		m = vtnet_tx_offload(sc, m, hdr);
-		if ((*m_head = m) == NULL)
+		if ((*m_head = m) == NULL) {
+			error = ENOBUFS;
 			goto fail;
+		}
 	}
 
 	error = vtnet_enqueue_txbuf(sc, m_head, txhdr);
@@ -2387,6 +2404,7 @@
 	uint8_t ack;
 
 	ifp = sc->vtnet_ifp;
+	filter = sc->vtnet_mac_filter;
 	ucnt = 0;
 	mcnt = 0;
 	promisc = 0;
@@ -2397,19 +2415,6 @@
 	KASSERT(sc->vtnet_flags & VTNET_FLAG_CTRL_RX,
 	    ("CTRL_RX feature not negotiated"));
 
-	/*
-	 * Allocate the MAC filtering table. Note we could do this
-	 * at attach time, but it is probably not worth keeping it
-	 * around for an infrequent occurrence.
-	 */
-	filter = malloc(sizeof(struct vtnet_mac_filter), M_DEVBUF,
-	    M_NOWAIT | M_ZERO);
-	if (filter == NULL) {
-		device_printf(sc->vtnet_dev,
-		    "cannot allocate MAC address filtering table\n");
-		return;
-	}
-
 	/* Unicast MAC addresses: */
 	if_addr_rlock(ifp);
 	TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
@@ -2481,8 +2486,6 @@
 		if_printf(ifp, "error setting host MAC filter table\n");
 
 out:
-	free(filter, M_DEVBUF);
-
 	if (promisc)
 		if (vtnet_set_promisc(sc, 1) != 0)
 			if_printf(ifp, "cannot enable promiscuous mode\n");
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/virtio/network/if_vtnetvar.h
--- a/head/sys/dev/virtio/network/if_vtnetvar.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/virtio/network/if_vtnetvar.h	Tue Dec 06 20:26:16 2011 +0200
@@ -23,7 +23,7 @@
  * (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: head/sys/dev/virtio/network/if_vtnetvar.h 227652 2011-11-18 05:43:43Z grehan $
+ * $FreeBSD: head/sys/dev/virtio/network/if_vtnetvar.h 228301 2011-12-06 06:28:32Z grehan $
  */
 
 #ifndef _IF_VTNETVAR_H
@@ -99,6 +99,7 @@
 #define VTNET_MEDIATYPE		 (IFM_ETHER | IFM_1000_T | IFM_FDX)
 	char			 vtnet_hwaddr[ETHER_ADDR_LEN];
 
+	struct vtnet_mac_filter	*vtnet_mac_filter;
 	/*
 	 * During reset, the host's VLAN filtering table is lost. The
 	 * array below is used to restore all the VLANs configured on
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/virtio/network/virtio_net.h
--- a/head/sys/dev/virtio/network/virtio_net.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/virtio/network/virtio_net.h	Tue Dec 06 20:26:16 2011 +0200
@@ -1,8 +1,31 @@
-/*
+/*-
  * This header is BSD licensed so anyone can use the definitions to implement
  * compatible drivers/servers.
  *
- * $FreeBSD: head/sys/dev/virtio/network/virtio_net.h 227652 2011-11-18 05:43:43Z grehan $
+ * 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 IBM 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 COPYRIGHT HOLDERS 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 IBM 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: head/sys/dev/virtio/network/virtio_net.h 228301 2011-12-06 06:28:32Z grehan $
  */
 
 #ifndef _VIRTIO_NET_H
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/virtio/pci/virtio_pci.h
--- a/head/sys/dev/virtio/pci/virtio_pci.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/virtio/pci/virtio_pci.h	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-/*
+/*-
  * Copyright IBM Corp. 2007
  *
  * Authors:
@@ -7,7 +7,30 @@
  * This header is BSD licensed so anyone can use the definitions to implement
  * compatible drivers/servers.
  *
- * $FreeBSD: head/sys/dev/virtio/pci/virtio_pci.h 227652 2011-11-18 05:43:43Z grehan $
+ * 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 IBM 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 COPYRIGHT HOLDERS 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 IBM 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: head/sys/dev/virtio/pci/virtio_pci.h 228301 2011-12-06 06:28:32Z grehan $
  */
 
 #ifndef _VIRTIO_PCI_H
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/virtio/virtio.h
--- a/head/sys/dev/virtio/virtio.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/virtio/virtio.h	Tue Dec 06 20:26:16 2011 +0200
@@ -1,8 +1,31 @@
-/*
+/*-
  * This header is BSD licensed so anyone can use the definitions to implement
  * compatible drivers/servers.
  *
- * $FreeBSD: head/sys/dev/virtio/virtio.h 227652 2011-11-18 05:43:43Z grehan $
+ * 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 IBM 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 COPYRIGHT HOLDERS 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 IBM 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: head/sys/dev/virtio/virtio.h 228301 2011-12-06 06:28:32Z grehan $
  */
 
 #ifndef _VIRTIO_H_
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/virtio/virtio_ring.h
--- a/head/sys/dev/virtio/virtio_ring.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/virtio/virtio_ring.h	Tue Dec 06 20:26:16 2011 +0200
@@ -1,10 +1,34 @@
-/*
- * This header is BSD licensed so anyone can use the definitions
- * to implement compatible drivers/servers.
+/*-
+ * Copyright Rusty Russell IBM Corporation 2007.
  *
- * Copyright Rusty Russell IBM Corporation 2007.
+ * This header is BSD licensed so anyone can use the definitions to implement
+ * compatible drivers/servers.
+ *
+ * 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 IBM 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 COPYRIGHT HOLDERS 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 IBM 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: head/sys/dev/virtio/virtio_ring.h 228301 2011-12-06 06:28:32Z grehan $
  */
-/* $FreeBSD: head/sys/dev/virtio/virtio_ring.h 227652 2011-11-18 05:43:43Z grehan $ */
 
 #ifndef VIRTIO_RING_H
 #define	VIRTIO_RING_H
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/vr/if_vr.c
--- a/head/sys/dev/vr/if_vr.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/vr/if_vr.c	Tue Dec 06 20:26:16 2011 +0200
@@ -31,7 +31,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/vr/if_vr.c 227843 2011-11-22 21:28:20Z marius $");
+__FBSDID("$FreeBSD: head/sys/dev/vr/if_vr.c 228086 2011-11-28 19:03:59Z yongari $");
 
 /*
  * VIA Rhine fast ethernet PCI NIC driver
@@ -305,20 +305,20 @@
 	    (ifp->if_drv_flags & IFF_DRV_RUNNING) == 0)
 		return;
 
-	sc->vr_link = 0;
+	sc->vr_flags &= ~(VR_F_LINK | VR_F_TXPAUSE);
 	if ((mii->mii_media_status & (IFM_ACTIVE | IFM_AVALID)) ==
 	    (IFM_ACTIVE | IFM_AVALID)) {
 		switch (IFM_SUBTYPE(mii->mii_media_active)) {
 		case IFM_10_T:
 		case IFM_100_TX:
-			sc->vr_link = 1;
+			sc->vr_flags |= VR_F_LINK;
 			break;
 		default:
 			break;
 		}
 	}
 
-	if (sc->vr_link != 0) {
+	if ((sc->vr_flags & VR_F_LINK) != 0) {
 		cr0 = CSR_READ_1(sc, VR_CR0);
 		cr1 = CSR_READ_1(sc, VR_CR1);
 		mfdx = (cr1 & VR_CR1_FULLDUPLEX) != 0;
@@ -342,7 +342,6 @@
 			CSR_WRITE_1(sc, VR_CR1, cr1);
 		}
 		fc = 0;
-#ifdef notyet
 		/* Configure flow-control. */
 		if (sc->vr_revid >= REV_ID_VT6105_A0) {
 			fc = CSR_READ_1(sc, VR_FLOWCR1);
@@ -351,8 +350,10 @@
 			    IFM_ETH_RXPAUSE) != 0)
 				fc |= VR_FLOWCR1_RXPAUSE;
 			if ((IFM_OPTIONS(mii->mii_media_active) &
-			    IFM_ETH_TXPAUSE) != 0)
+			    IFM_ETH_TXPAUSE) != 0) {
 				fc |= VR_FLOWCR1_TXPAUSE;
+				sc->vr_flags |= VR_F_TXPAUSE;
+			}
 			CSR_WRITE_1(sc, VR_FLOWCR1, fc);
 		} else if (sc->vr_revid >= REV_ID_VT6102_A) {
 			/* No Tx puase capability available for Rhine II. */
@@ -363,7 +364,6 @@
 				fc |= VR_MISCCR0_RXPAUSE;
 			CSR_WRITE_1(sc, VR_MISC_CR0, fc);
 		}
-#endif
 		vr_rx_start(sc);
 		vr_tx_start(sc);
 	} else {
@@ -766,7 +766,8 @@
 	else
 		phy = CSR_READ_1(sc, VR_PHYADDR) & VR_PHYADDR_MASK;
 	error = mii_attach(dev, &sc->vr_miibus, ifp, vr_ifmedia_upd,
-	    vr_ifmedia_sts, BMSR_DEFCAPMASK, phy, MII_OFFSET_ANY, 0);
+	    vr_ifmedia_sts, BMSR_DEFCAPMASK, phy, MII_OFFSET_ANY,
+	    sc->vr_revid >= REV_ID_VT6102_A ? MIIF_DOPAUSE : 0);
 	if (error != 0) {
 		device_printf(dev, "attaching PHYs failed\n");
 		goto fail;
@@ -821,7 +822,7 @@
 	/* These should only be active if attach succeeded. */
 	if (device_is_attached(dev)) {
 		VR_LOCK(sc);
-		sc->vr_detach = 1;
+		sc->vr_flags |= VR_F_DETACHED;
 		vr_stop(sc);
 		VR_UNLOCK(sc);
 		callout_drain(&sc->vr_stat_callout);
@@ -1396,6 +1397,17 @@
 	}
 
 	if (prog > 0) {
+		/*
+		 * Let controller know how many number of RX buffers
+		 * are posted but avoid expensive register access if
+		 * TX pause capability was not negotiated with link
+		 * partner.
+		 */
+		if ((sc->vr_flags & VR_F_TXPAUSE) != 0) {
+			if (prog >= VR_RX_RING_CNT)
+				prog = VR_RX_RING_CNT - 1;
+			CSR_WRITE_1(sc, VR_FLOWCR0, prog);
+		}
 		sc->vr_cdata.vr_rx_cons = cons;
 		bus_dmamap_sync(sc->vr_cdata.vr_rx_ring_tag,
 		    sc->vr_cdata.vr_rx_ring_map,
@@ -1542,7 +1554,7 @@
 
 	mii = device_get_softc(sc->vr_miibus);
 	mii_tick(mii);
-	if (sc->vr_link == 0)
+	if ((sc->vr_flags & VR_F_LINK) == 0)
 		vr_miibus_statchg(sc->vr_dev);
 	vr_watchdog(sc);
 	callout_reset(&sc->vr_stat_callout, hz, vr_tick, sc);
@@ -1652,7 +1664,7 @@
 
 	VR_LOCK(sc);
 
-	if (sc->vr_suspended != 0)
+	if ((sc->vr_flags & VR_F_SUSPENDED) != 0)
 		goto done_locked;
 
 	status = CSR_READ_2(sc, VR_ISR);
@@ -1933,7 +1945,7 @@
 	VR_LOCK_ASSERT(sc);
 
 	if ((ifp->if_drv_flags & (IFF_DRV_RUNNING | IFF_DRV_OACTIVE)) !=
-	    IFF_DRV_RUNNING || sc->vr_link == 0)
+	    IFF_DRV_RUNNING || (sc->vr_flags & VR_F_LINK) == 0)
 		return;
 
 	for (enq = 0; !IFQ_DRV_IS_EMPTY(&ifp->if_snd) &&
@@ -2071,14 +2083,32 @@
 
 	/* Set flow-control parameters for Rhine III. */
 	if (sc->vr_revid >= REV_ID_VT6105_A0) {
- 		/* Rx buffer count available for incoming packet. */
-		CSR_WRITE_1(sc, VR_FLOWCR0, VR_RX_RING_CNT);
 		/*
-		 * Tx pause low threshold : 16 free receive buffers
-		 * Tx pause XON high threshold : 48 free receive buffers
+		 * Configure Rx buffer count available for incoming
+		 * packet.
+		 * Even though data sheet says almost nothing about
+		 * this register, this register should be updated
+		 * whenever driver adds new RX buffers to controller.
+		 * Otherwise, XON frame is not sent to link partner
+		 * even if controller has enough RX buffers and you
+		 * would be isolated from network.
+		 * The controller is not smart enough to know number
+		 * of available RX buffers so driver have to let
+		 * controller know how many RX buffers are posted.
+		 * In other words, this register works like a residue
+		 * counter for RX buffers and should be initialized
+		 * to the number of total RX buffers  - 1 before
+		 * enabling RX MAC.  Note, this register is 8bits so
+		 * it effectively limits the maximum number of RX
+		 * buffer to be configured by controller is 255.
+		 */
+		CSR_WRITE_1(sc, VR_FLOWCR0, VR_RX_RING_CNT - 1);
+		/*
+		 * Tx pause low threshold : 8 free receive buffers
+		 * Tx pause XON high threshold : 24 free receive buffers
 		 */
 		CSR_WRITE_1(sc, VR_FLOWCR1,
-		    VR_FLOWCR1_TXLO16 | VR_FLOWCR1_TXHI48 | VR_FLOWCR1_XONXOFF);
+		    VR_FLOWCR1_TXLO8 | VR_FLOWCR1_TXHI24 | VR_FLOWCR1_XONXOFF);
 		/* Set Tx pause timer. */
 		CSR_WRITE_2(sc, VR_PAUSETIMER, 0xffff);
 	}
@@ -2103,12 +2133,12 @@
 	if (sc->vr_revid > REV_ID_VT6102_A)
 		CSR_WRITE_2(sc, VR_MII_IMR, 0);
 
-	sc->vr_link = 0;
-	mii_mediachg(mii);
-
 	ifp->if_drv_flags |= IFF_DRV_RUNNING;
 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
 
+	sc->vr_flags &= ~(VR_F_LINK | VR_F_TXPAUSE);
+	mii_mediachg(mii);
+
 	callout_reset(&sc->vr_stat_callout, hz, vr_tick, sc);
 }
 
@@ -2128,6 +2158,7 @@
 	mii = device_get_softc(sc->vr_miibus);
 	LIST_FOREACH(miisc, &mii->mii_phys, mii_list)
 		PHY_RESET(miisc);
+	sc->vr_flags &= ~(VR_F_LINK | VR_F_TXPAUSE);
 	error = mii_mediachg(mii);
 	VR_UNLOCK(sc);
 
@@ -2177,7 +2208,7 @@
 				    (IFF_PROMISC | IFF_ALLMULTI))
 					vr_set_filter(sc);
 			} else {
-				if (sc->vr_detach == 0)
+				if ((sc->vr_flags & VR_F_DETACHED) == 0)
 					vr_init_locked(sc);
 			}
 		} else {
@@ -2265,7 +2296,7 @@
 	if (sc->vr_cdata.vr_tx_cnt == 0)
 		return;
 
-	if (sc->vr_link == 0) {
+	if ((sc->vr_flags & VR_F_LINK) == 0) {
 		if (bootverbose)
 			if_printf(sc->vr_ifp, "watchdog timeout "
 			   "(missed link)\n");
@@ -2443,7 +2474,7 @@
 	VR_LOCK(sc);
 	vr_stop(sc);
 	vr_setwol(sc);
-	sc->vr_suspended = 1;
+	sc->vr_flags |= VR_F_SUSPENDED;
 	VR_UNLOCK(sc);
 
 	return (0);
@@ -2464,7 +2495,7 @@
 	if (ifp->if_flags & IFF_UP)
 		vr_init_locked(sc);
 
-	sc->vr_suspended = 0;
+	sc->vr_flags &= ~VR_F_SUSPENDED;
 	VR_UNLOCK(sc);
 
 	return (0);
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/vr/if_vrreg.h
--- a/head/sys/dev/vr/if_vrreg.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/vr/if_vrreg.h	Tue Dec 06 20:26:16 2011 +0200
@@ -29,7 +29,7 @@
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
  * THE POSSIBILITY OF SUCH DAMAGE.
  *
- * $FreeBSD: head/sys/dev/vr/if_vrreg.h 223405 2011-06-22 02:18:45Z yongari $
+ * $FreeBSD: head/sys/dev/vr/if_vrreg.h 228086 2011-11-28 19:03:59Z yongari $
  */
 
 /*
@@ -720,20 +720,21 @@
 	void			*vr_intrhand;
 	device_t		vr_miibus;
 	uint8_t			vr_revid;	/* Rhine chip revision */
-	uint8_t			vr_flags;	/* See VR_F_* below */
-#define	VR_F_RESTART		0x01		/* Restart unit on next tick */
+	int			vr_flags;	/* See VR_F_* below */
+#define	VR_F_RESTART		0x0001		/* Restart unit on next tick */
+#define	VR_F_TXPAUSE		0x0010
+#define	VR_F_SUSPENDED		0x2000
+#define	VR_F_DETACHED		0x4000
+#define	VR_F_LINK		0x8000
 	int			vr_if_flags;
 	struct vr_chain_data	vr_cdata;
 	struct vr_ring_data	vr_rdata;
 	struct vr_statistics	vr_stat;
 	struct callout		vr_stat_callout;
 	struct mtx		vr_mtx;
-	int			vr_suspended;	/* if 1, sleeping/detaching */
 	int			vr_quirks;
-	int			vr_link;
 	int			vr_watchdog_timer;
 	int			vr_txthresh;
-	int			vr_detach;
 #ifdef DEVICE_POLLING
 	int			rxcycles;
 #endif
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/dev/xl/xlphy.c
--- a/head/sys/dev/xl/xlphy.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/dev/xl/xlphy.c	Tue Dec 06 20:26:16 2011 +0200
@@ -55,7 +55,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/dev/xl/xlphy.c 226154 2011-10-08 12:33:10Z marius $");
+__FBSDID("$FreeBSD: head/sys/dev/xl/xlphy.c 227908 2011-11-23 20:27:26Z marius $");
 
 /*
  * driver for 3Com internal PHYs
@@ -86,7 +86,7 @@
 	DEVMETHOD(device_attach,	xlphy_attach),
 	DEVMETHOD(device_detach,	mii_phy_detach),
 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
-	{ 0, 0 }
+	DEVMETHOD_END
 };
 
 static devclass_t xlphy_devclass;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/fs/fifofs/fifo_vnops.c
--- a/head/sys/fs/fifofs/fifo_vnops.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/fs/fifofs/fifo_vnops.c	Tue Dec 06 20:26:16 2011 +0200
@@ -29,7 +29,7 @@
  * SUCH DAMAGE.
  *
  *	@(#)fifo_vnops.c	8.10 (Berkeley) 5/27/95
- * $FreeBSD: head/sys/fs/fifofs/fifo_vnops.c 224914 2011-08-16 20:07:47Z kib $
+ * $FreeBSD: head/sys/fs/fifofs/fifo_vnops.c 228263 2011-12-04 19:25:49Z kib $
  */
 
 #include <sys/param.h>
@@ -218,7 +218,7 @@
 			free(fip, M_VNODE);
 			return (error);
 		}
-		fip->fi_readers = fip->fi_writers = 0;
+		fip->fi_wgen = fip->fi_readers = fip->fi_writers = 0;
 		wso->so_snd.sb_lowat = PIPE_BUF;
 		SOCKBUF_LOCK(&rso->so_rcv);
 		rso->so_rcv.sb_state |= SBS_CANTRCVMORE;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/fs/nfs/nfsclstate.h
--- a/head/sys/fs/nfs/nfsclstate.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/fs/nfs/nfsclstate.h	Tue Dec 06 20:26:16 2011 +0200
@@ -23,7 +23,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: head/sys/fs/nfs/nfsclstate.h 227743 2011-11-20 00:39:15Z rmacklem $
+ * $FreeBSD: head/sys/fs/nfs/nfsclstate.h 228217 2011-12-03 02:27:26Z rmacklem $
  */
 
 #ifndef _NFS_NFSCLSTATE_H_
@@ -34,6 +34,7 @@
  */
 LIST_HEAD(nfsclopenhead, nfsclopen);
 LIST_HEAD(nfscllockownerhead, nfscllockowner);
+SLIST_HEAD(nfscllockownerfhhead, nfscllockownerfh);
 LIST_HEAD(nfscllockhead, nfscllock);
 LIST_HEAD(nfsclhead, nfsclclient);
 LIST_HEAD(nfsclownerhead, nfsclowner);
@@ -149,8 +150,8 @@
 	struct nfsclopen	*nfsl_open;
 	NFSPROC_T		*nfsl_inprog;
 	nfsv4stateid_t		nfsl_stateid;
+	int			nfsl_lockflags;
 	u_int32_t		nfsl_seqid;
-	u_int32_t		nfsl_defunct;
 	struct nfsv4lock	nfsl_rwlock;
 	u_int8_t		nfsl_owner[NFSV4CL_LOCKNAMELEN];
 	u_int8_t		nfsl_openowner[NFSV4CL_LOCKNAMELEN];
@@ -166,6 +167,14 @@
 	short			nfslo_type;
 };
 
+/* This structure is used to collect a list of lockowners to free up. */
+struct nfscllockownerfh {
+	SLIST_ENTRY(nfscllockownerfh)	nfslfh_list;
+	struct nfscllockownerhead	nfslfh_lock;
+	int				nfslfh_len;
+	uint8_t				nfslfh_fh[NFSX_V4FHMAX];
+};
+
 /*
  * Macro for incrementing the seqid#.
  */
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/fs/nfsclient/nfs_clbio.c
--- a/head/sys/fs/nfsclient/nfs_clbio.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/fs/nfsclient/nfs_clbio.c	Tue Dec 06 20:26:16 2011 +0200
@@ -33,7 +33,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/fs/nfsclient/nfs_clbio.c 223280 2011-06-18 23:02:53Z rmacklem $");
+__FBSDID("$FreeBSD: head/sys/fs/nfsclient/nfs_clbio.c 228156 2011-11-30 17:39:00Z kib $");
 
 #include "opt_kdtrace.h"
 
@@ -211,7 +211,7 @@
 			 * Read operation filled a partial page.
 			 */
 			m->valid = 0;
-			vm_page_set_valid(m, 0, size - toff);
+			vm_page_set_valid_range(m, 0, size - toff);
 			KASSERT(m->dirty == 0,
 			    ("nfs_getpages: page %p is dirty", m));
 		} else {
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/fs/nfsclient/nfs_clstate.c
--- a/head/sys/fs/nfsclient/nfs_clstate.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/fs/nfsclient/nfs_clstate.c	Tue Dec 06 20:26:16 2011 +0200
@@ -26,7 +26,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/fs/nfsclient/nfs_clstate.c 227796 2011-11-21 16:06:23Z rmacklem $");
+__FBSDID("$FreeBSD: head/sys/fs/nfsclient/nfs_clstate.c 228217 2011-12-03 02:27:26Z rmacklem $");
 
 /*
  * These functions implement the client side state handling for NFSv4.
@@ -143,6 +143,8 @@
 static void nfscl_cleandeleg(struct nfscldeleg *);
 static int nfscl_trydelegreturn(struct nfscldeleg *, struct ucred *,
     struct nfsmount *, NFSPROC_T *);
+static void nfscl_emptylockowner(struct nfscllockowner *,
+    struct nfscllockownerfhhead *);
 
 static short nfscberr_null[] = {
 	0,
@@ -1030,7 +1032,7 @@
 			NFSBCOPY(op->nfso_own->nfsow_owner, nlp->nfsl_openowner,
 			    NFSV4CL_LOCKNAMELEN);
 		nlp->nfsl_seqid = 0;
-		nlp->nfsl_defunct = 0;
+		nlp->nfsl_lockflags = flags;
 		nlp->nfsl_inprog = NULL;
 		nfscl_lockinit(&nlp->nfsl_rwlock);
 		LIST_INIT(&nlp->nfsl_lock);
@@ -1638,7 +1640,6 @@
 nfscl_cleanup_common(struct nfsclclient *clp, u_int8_t *own)
 {
 	struct nfsclowner *owp, *nowp;
-	struct nfsclopen *op;
 	struct nfscllockowner *lp, *nlp;
 	struct nfscldeleg *dp;
 
@@ -1667,15 +1668,6 @@
 				nfscl_freeopenowner(owp, 0);
 			else
 				owp->nfsow_defunct = 1;
-		} else {
-			/* look for lockowners on other opens */
-			LIST_FOREACH(op, &owp->nfsow_open, nfso_list) {
-				LIST_FOREACH(lp, &op->nfso_lock, nfsl_list) {
-					if (!NFSBCMP(lp->nfsl_owner, own,
-					    NFSV4CL_LOCKNAMELEN))
-						lp->nfsl_defunct = 1;
-				}
-			}
 		}
 		owp = nowp;
 	}
@@ -1685,13 +1677,21 @@
  * Find open/lock owners for processes that have exited.
  */
 static void
-nfscl_cleanupkext(struct nfsclclient *clp)
+nfscl_cleanupkext(struct nfsclclient *clp, struct nfscllockownerfhhead *lhp)
 {
 	struct nfsclowner *owp, *nowp;
+	struct nfsclopen *op;
+	struct nfscllockowner *lp, *nlp;
 
 	NFSPROCLISTLOCK();
 	NFSLOCKCLSTATE();
 	LIST_FOREACH_SAFE(owp, &clp->nfsc_owner, nfsow_list, nowp) {
+		LIST_FOREACH(op, &owp->nfsow_open, nfso_list) {
+			LIST_FOREACH_SAFE(lp, &op->nfso_lock, nfsl_list, nlp) {
+				if (LIST_EMPTY(&lp->nfsl_lock))
+					nfscl_emptylockowner(lp, lhp);
+			}
+		}
 		if (nfscl_procdoesntexist(owp->nfsow_owner))
 			nfscl_cleanup_common(clp, owp->nfsow_owner);
 	}
@@ -1699,6 +1699,58 @@
 	NFSPROCLISTUNLOCK();
 }
 
+/*
+ * Take the empty lock owner and move it to the local lhp list if the
+ * associated process no longer exists.
+ */
+static void
+nfscl_emptylockowner(struct nfscllockowner *lp,
+    struct nfscllockownerfhhead *lhp)
+{
+	struct nfscllockownerfh *lfhp, *mylfhp;
+	struct nfscllockowner *nlp;
+	int fnd_it;
+
+	/* If not a Posix lock owner, just return. */
+	if ((lp->nfsl_lockflags & F_POSIX) == 0)
+		return;
+
+	fnd_it = 0;
+	mylfhp = NULL;
+	/*
+	 * First, search to see if this lock owner is already in the list.
+	 * If it is, then the associated process no longer exists.
+	 */
+	SLIST_FOREACH(lfhp, lhp, nfslfh_list) {
+		if (lfhp->nfslfh_len == lp->nfsl_open->nfso_fhlen &&
+		    !NFSBCMP(lfhp->nfslfh_fh, lp->nfsl_open->nfso_fh,
+		    lfhp->nfslfh_len))
+			mylfhp = lfhp;
+		LIST_FOREACH(nlp, &lfhp->nfslfh_lock, nfsl_list)
+			if (!NFSBCMP(nlp->nfsl_owner, lp->nfsl_owner,
+			    NFSV4CL_LOCKNAMELEN))
+				fnd_it = 1;
+	}
+	/* If not found, check if process still exists. */
+	if (fnd_it == 0 && nfscl_procdoesntexist(lp->nfsl_owner) == 0)
+		return;
+
+	/* Move the lock owner over to the local list. */
+	if (mylfhp == NULL) {
+		mylfhp = malloc(sizeof(struct nfscllockownerfh), M_TEMP,
+		    M_NOWAIT);
+		if (mylfhp == NULL)
+			return;
+		mylfhp->nfslfh_len = lp->nfsl_open->nfso_fhlen;
+		NFSBCOPY(lp->nfsl_open->nfso_fh, mylfhp->nfslfh_fh,
+		    mylfhp->nfslfh_len);
+		LIST_INIT(&mylfhp->nfslfh_lock);
+		SLIST_INSERT_HEAD(lhp, mylfhp, nfslfh_list);
+	}
+	LIST_REMOVE(lp, nfsl_list);
+	LIST_INSERT_HEAD(&mylfhp->nfslfh_lock, lp, nfsl_list);
+}
+
 static int	fake_global;	/* Used to force visibility of MNTK_UNMOUNTF */
 /*
  * Called from nfs umount to free up the clientid.
@@ -2331,9 +2383,8 @@
 {
 	struct nfsclowner *owp, *nowp;
 	struct nfsclopen *op;
-	struct nfscllockowner *lp, *nlp, *olp;
+	struct nfscllockowner *lp, *nlp;
 	struct nfscldeleghead dh;
-	struct nfscllockownerhead lh;
 	struct nfscldeleg *dp, *ndp;
 	struct ucred *cred;
 	u_int32_t clidrev;
@@ -2341,6 +2392,8 @@
 	uint32_t recover_done_time = 0;
 	struct timespec mytime;
 	static time_t prevsec = 0;
+	struct nfscllockownerfh *lfhp, *nlfhp;
+	struct nfscllockownerfhhead lfh;
 
 	cred = newnfs_getcred();
 	NFSLOCKCLSTATE();
@@ -2379,7 +2432,6 @@
 			    (void) nfscl_hasexpired(clp, clidrev, p);
 		}
 
-		LIST_INIT(&lh);
 		TAILQ_INIT(&dh);
 		NFSLOCKCLSTATE();
 		if (cbpathdown)
@@ -2389,41 +2441,11 @@
 		/*
 		 * Now, handle defunct owners.
 		 */
-		owp = LIST_FIRST(&clp->nfsc_owner);
-		while (owp != NULL) {
-		    nowp = LIST_NEXT(owp, nfsow_list);
-		    if (LIST_EMPTY(&owp->nfsow_open)) {
-			if (owp->nfsow_defunct)
-			    nfscl_freeopenowner(owp, 0);
-		    } else {
-			LIST_FOREACH(op, &owp->nfsow_open, nfso_list) {
-			    lp = LIST_FIRST(&op->nfso_lock);
-			    while (lp != NULL) {
-				nlp = LIST_NEXT(lp, nfsl_list);
-				if (lp->nfsl_defunct &&
-				    LIST_EMPTY(&lp->nfsl_lock)) {
-				    LIST_FOREACH(olp, &lh, nfsl_list) {
-					if (!NFSBCMP(olp->nfsl_owner,
-					    lp->nfsl_owner,NFSV4CL_LOCKNAMELEN))
-					    break;
-				    }
-				    if (olp == NULL) {
-					LIST_REMOVE(lp, nfsl_list);
-					LIST_INSERT_HEAD(&lh, lp, nfsl_list);
-				    } else {
-					nfscl_freelockowner(lp, 0);
-				    }
-				}
-				lp = nlp;
-			    }
+		LIST_FOREACH_SAFE(owp, &clp->nfsc_owner, nfsow_list, nowp) {
+			if (LIST_EMPTY(&owp->nfsow_open)) {
+				if (owp->nfsow_defunct != 0)
+					nfscl_freeopenowner(owp, 0);
 			}
-		    }
-		    owp = nowp;
-		}
-
-		/* and release defunct lock owners */
-		LIST_FOREACH_SAFE(lp, &lh, nfsl_list, nlp) {
-		    nfscl_freelockowner(lp, 0);
 		}
 
 		/*
@@ -2528,6 +2550,7 @@
 			FREE((caddr_t)dp, M_NFSCLDELEG);
 		}
 
+		SLIST_INIT(&lfh);
 		/*
 		 * Call nfscl_cleanupkext() once per second to check for
 		 * open/lock owners where the process has exited.
@@ -2535,9 +2558,27 @@
 		NFSGETNANOTIME(&mytime);
 		if (prevsec != mytime.tv_sec) {
 			prevsec = mytime.tv_sec;
-			nfscl_cleanupkext(clp);
+			nfscl_cleanupkext(clp, &lfh);
 		}
 
+		/*
+		 * Do a ReleaseLockOwner for all lock owners where the
+		 * associated process no longer exists, as found by
+		 * nfscl_cleanupkext().
+		 */
+		newnfs_setroot(cred);
+		SLIST_FOREACH_SAFE(lfhp, &lfh, nfslfh_list, nlfhp) {
+			LIST_FOREACH_SAFE(lp, &lfhp->nfslfh_lock, nfsl_list,
+			    nlp) {
+				(void)nfsrpc_rellockown(clp->nfsc_nmp, lp,
+				    lfhp->nfslfh_fh, lfhp->nfslfh_len, cred,
+				    p);
+				nfscl_freelockowner(lp, 0);
+			}
+			free(lfhp, M_TEMP);
+		}
+		SLIST_INIT(&lfh);
+
 		NFSLOCKCLSTATE();
 		if ((clp->nfsc_flags & NFSCLFLAGS_RECOVER) == 0)
 			(void)mtx_sleep(clp, NFSCLSTATEMUTEXPTR, PWAIT, "nfscl",
@@ -3539,8 +3580,8 @@
 	off = lop->nfslo_first;
 	len = lop->nfslo_end - lop->nfslo_first;
 	error = nfscl_getbytelock(vp, off, len, lop->nfslo_type, cred, p,
-	    clp, 1, NULL, 0, lp->nfsl_owner, lp->nfsl_openowner, &nlp, &newone,
-	    &donelocally);
+	    clp, 1, NULL, lp->nfsl_lockflags, lp->nfsl_owner,
+	    lp->nfsl_openowner, &nlp, &newone, &donelocally);
 	if (error || donelocally)
 		return (error);
 	if (nmp->nm_clp != NULL)
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/fs/nfsserver/nfs_nfsdport.c
--- a/head/sys/fs/nfsserver/nfs_nfsdport.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/fs/nfsserver/nfs_nfsdport.c	Tue Dec 06 20:26:16 2011 +0200
@@ -32,7 +32,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/fs/nfsserver/nfs_nfsdport.c 227809 2011-11-22 00:35:30Z rmacklem $");
+__FBSDID("$FreeBSD: head/sys/fs/nfsserver/nfs_nfsdport.c 228185 2011-12-01 18:46:28Z jhb $");
 
 #include <sys/capability.h>
 
@@ -90,20 +90,78 @@
 SYSCTL_INT(_vfs_nfsd, OID_AUTO, enable_locallocks, CTLFLAG_RW,
     &nfsrv_dolocallocks, 0, "Enable nfsd to acquire local locks on files");
 
-#define	NUM_HEURISTIC		1017
+#define	MAX_REORDERED_RPC	16
+#define	NUM_HEURISTIC		1031
 #define	NHUSE_INIT		64
 #define	NHUSE_INC		16
 #define	NHUSE_MAX		2048
 
 static struct nfsheur {
 	struct vnode *nh_vp;	/* vp to match (unreferenced pointer) */
-	off_t nh_nextr;		/* next offset for sequential detection */
+	off_t nh_nextoff;	/* next offset for sequential detection */
 	int nh_use;		/* use count for selection */
 	int nh_seqcount;	/* heuristic */
 } nfsheur[NUM_HEURISTIC];
 
 
 /*
+ * Heuristic to detect sequential operation.
+ */
+static struct nfsheur *
+nfsrv_sequential_heuristic(struct uio *uio, struct vnode *vp)
+{
+	struct nfsheur *nh;
+	int hi, try;
+
+	/* Locate best candidate. */
+	try = 32;
+	hi = ((int)(vm_offset_t)vp / sizeof(struct vnode)) % NUM_HEURISTIC;
+	nh = &nfsheur[hi];
+	while (try--) {
+		if (nfsheur[hi].nh_vp == vp) {
+			nh = &nfsheur[hi];
+			break;
+		}
+		if (nfsheur[hi].nh_use > 0)
+			--nfsheur[hi].nh_use;
+		hi = (hi + 1) % NUM_HEURISTIC;
+		if (nfsheur[hi].nh_use < nh->nh_use)
+			nh = &nfsheur[hi];
+	}
+
+	/* Initialize hint if this is a new file. */
+	if (nh->nh_vp != vp) {
+		nh->nh_vp = vp;
+		nh->nh_nextoff = uio->uio_offset;
+		nh->nh_use = NHUSE_INIT;
+		if (uio->uio_offset == 0)
+			nh->nh_seqcount = 4;
+		else
+			nh->nh_seqcount = 1;
+	}
+
+	/* Calculate heuristic. */
+	if ((uio->uio_offset == 0 && nh->nh_seqcount > 0) ||
+	    uio->uio_offset == nh->nh_nextoff) {
+		/* See comments in vfs_vnops.c:sequential_heuristic(). */
+		nh->nh_seqcount += howmany(uio->uio_resid, 16384);
+		if (nh->nh_seqcount > IO_SEQMAX)
+			nh->nh_seqcount = IO_SEQMAX;
+	} else if (qabs(uio->uio_offset - nh->nh_nextoff) <= MAX_REORDERED_RPC *
+	    imax(vp->v_mount->mnt_stat.f_iosize, uio->uio_resid)) {
+		/* Probably a reordered RPC, leave seqcount alone. */
+	} else if (nh->nh_seqcount > 1) {
+		nh->nh_seqcount /= 2;
+	} else {
+		nh->nh_seqcount = 0;
+	}
+	nh->nh_use += NHUSE_INC;
+	if (nh->nh_use > NHUSE_MAX)
+		nh->nh_use = NHUSE_MAX;
+	return (nh);
+}
+
+/*
  * Get attributes into nfsvattr structure.
  */
 int
@@ -567,60 +625,11 @@
 	int i;
 	struct iovec *iv;
 	struct iovec *iv2;
-	int error = 0, len, left, siz, tlen, ioflag = 0, hi, try = 32;
+	int error = 0, len, left, siz, tlen, ioflag = 0;
 	struct mbuf *m2 = NULL, *m3;
 	struct uio io, *uiop = &io;
 	struct nfsheur *nh;
 
-	/*
-	 * Calculate seqcount for heuristic
-	 */
-	/*
-	 * Locate best candidate
-	 */
-
-	hi = ((int)(vm_offset_t)vp / sizeof(struct vnode)) % NUM_HEURISTIC;
-	nh = &nfsheur[hi];
-
-	while (try--) {
-		if (nfsheur[hi].nh_vp == vp) {
-			nh = &nfsheur[hi];
-			break;
-		}
-		if (nfsheur[hi].nh_use > 0)
-			--nfsheur[hi].nh_use;
-		hi = (hi + 1) % NUM_HEURISTIC;
-		if (nfsheur[hi].nh_use < nh->nh_use)
-			nh = &nfsheur[hi];
-	}
-
-	if (nh->nh_vp != vp) {
-		nh->nh_vp = vp;
-		nh->nh_nextr = off;
-		nh->nh_use = NHUSE_INIT;
-		if (off == 0)
-			nh->nh_seqcount = 4;
-		else
-			nh->nh_seqcount = 1;
-	}
-
-	/*
-	 * Calculate heuristic
-	 */
-
-	if ((off == 0 && nh->nh_seqcount > 0) || off == nh->nh_nextr) {
-		if (++nh->nh_seqcount > IO_SEQMAX)
-			nh->nh_seqcount = IO_SEQMAX;
-	} else if (nh->nh_seqcount > 1) {
-		nh->nh_seqcount = 1;
-	} else {
-		nh->nh_seqcount = 0;
-	}
-	nh->nh_use += NHUSE_INC;
-	if (nh->nh_use > NHUSE_MAX)
-		nh->nh_use = NHUSE_MAX;
-	ioflag |= nh->nh_seqcount << IO_SEQSHIFT;
-
 	len = left = NFSM_RNDUP(cnt);
 	m3 = NULL;
 	/*
@@ -665,6 +674,8 @@
 	uiop->uio_resid = len;
 	uiop->uio_rw = UIO_READ;
 	uiop->uio_segflg = UIO_SYSSPACE;
+	nh = nfsrv_sequential_heuristic(uiop, vp);
+	ioflag |= nh->nh_seqcount << IO_SEQSHIFT;
 	error = VOP_READ(vp, uiop, IO_NODELOCKED | ioflag, cred);
 	FREE((caddr_t)iv2, M_TEMP);
 	if (error) {
@@ -672,6 +683,7 @@
 		*mpp = NULL;
 		goto out;
 	}
+	nh->nh_nextoff = uiop->uio_offset;
 	tlen = len - uiop->uio_resid;
 	cnt = cnt < tlen ? cnt : tlen;
 	tlen = NFSM_RNDUP(cnt);
@@ -700,6 +712,7 @@
 	struct iovec *iv;
 	int ioflags, error;
 	struct uio io, *uiop = &io;
+	struct nfsheur *nh;
 
 	MALLOC(ivp, struct iovec *, cnt * sizeof (struct iovec), M_TEMP,
 	    M_WAITOK);
@@ -733,7 +746,11 @@
 	uiop->uio_segflg = UIO_SYSSPACE;
 	NFSUIOPROC(uiop, p);
 	uiop->uio_offset = off;
+	nh = nfsrv_sequential_heuristic(uiop, vp);
+	ioflags |= nh->nh_seqcount << IO_SEQSHIFT;
 	error = VOP_WRITE(vp, uiop, ioflags, cred);
+	if (error == 0)
+		nh->nh_nextoff = uiop->uio_offset;
 	FREE((caddr_t)iv, M_TEMP);
 
 	NFSEXITCODE(error);
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/fs/nfsserver/nfs_nfsdsubs.c
--- a/head/sys/fs/nfsserver/nfs_nfsdsubs.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/fs/nfsserver/nfs_nfsdsubs.c	Tue Dec 06 20:26:16 2011 +0200
@@ -32,7 +32,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/fs/nfsserver/nfs_nfsdsubs.c 224086 2011-07-16 08:51:09Z zack $");
+__FBSDID("$FreeBSD: head/sys/fs/nfsserver/nfs_nfsdsubs.c 228260 2011-12-04 16:33:04Z rmacklem $");
 
 #ifndef APPLEKEXT
 /*
@@ -56,6 +56,13 @@
 extern nfstype nfsv34_type[9];
 #endif	/* !APPLEKEXT */
 
+SYSCTL_DECL(_vfs_nfsd);
+
+static int	disable_checkutf8 = 0;
+SYSCTL_INT(_vfs_nfsd, OID_AUTO, disable_checkutf8, CTLFLAG_RW,
+    &disable_checkutf8, 0,
+    "Disable the NFSv4 check for a UTF8 compliant name");
+
 static char nfsrv_hexdigit(char, int *);
 
 /*
@@ -1963,7 +1970,8 @@
 		    error = 0;
 		    goto nfsmout;
 		}
-		if (nfsrv_checkutf8((u_int8_t *)bufp, outlen)) {
+		if (disable_checkutf8 == 0 &&
+		    nfsrv_checkutf8((u_int8_t *)bufp, outlen)) {
 		    nd->nd_repstat = NFSERR_INVAL;
 		    error = 0;
 		    goto nfsmout;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/fs/ntfs/ntfs_subr.c
--- a/head/sys/fs/ntfs/ntfs_subr.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/fs/ntfs/ntfs_subr.c	Tue Dec 06 20:26:16 2011 +0200
@@ -25,7 +25,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: head/sys/fs/ntfs/ntfs_subr.c 227293 2011-11-07 06:44:47Z ed $
+ * $FreeBSD: head/sys/fs/ntfs/ntfs_subr.c 228023 2011-11-27 15:43:49Z kevlo $
  */
 
 #include <sys/param.h>
@@ -669,23 +669,17 @@
 	const char *astr;
 	size_t astrlen;
 {
-	int len;
+	const char *astrp = astr;
+	int len, res;
 	size_t i, j, mbstrlen = astrlen;
-	int res;
-	wchar wc;
 
 	if (ntmp->ntm_ic_l2u) {
-		for (i = 0, j = 0; i < ustrlen && j < astrlen; i++, j++) {
-			if (j < astrlen -1) {
-				wc = (wchar)astr[j]<<8 | (astr[j+1]&0xFF);
-				len = 2;
-			} else {
-				wc = (wchar)astr[j]<<8 & 0xFF00;
-				len = 1;
-			}
+		for (i = 0, j = 0; i < ustrlen && j < astrlen; i++) {
+			len = 4;
 			res = ((int) NTFS_TOUPPER(ustr[i])) -
-				((int)NTFS_TOUPPER(NTFS_82U(wc, &len)));
-			j += len - 1;
+			    ((int)NTFS_TOUPPER(NTFS_82U(astrp, &len)));
+			astrp += len;
+			j += len;
 			mbstrlen -= len - 1;
 
 			if (res)
@@ -698,7 +692,8 @@
 		 */
 		for (i = 0; i < ustrlen && i < astrlen; i++) {
 			res = ((int) NTFS_TOUPPER(NTFS_82U(NTFS_U28(ustr[i]), &len))) -
-				((int)NTFS_TOUPPER(NTFS_82U((wchar)astr[i], &len)));
+				((int)NTFS_TOUPPER(NTFS_82U(astrp, &len)));
+			astrp++;
 			if (res)
 				return res;
 		}
@@ -717,23 +712,18 @@
 	const char *astr;
 	size_t astrlen;
 {
-	char u, l;
+	char *c;
 	size_t i, j, mbstrlen = astrlen;
 	int res;
-	wchar wc;
 
-	for (i = 0, j = 0; (i < ustrlen) && (j < astrlen); i++, j++) {
-		res = 0;
-		wc = NTFS_U28(ustr[i]);
-		u = (char)(wc>>8);
-		l = (char)wc;
-		if (u != '\0' && j < astrlen -1) {
-			res = (int) (u - astr[j++]);
+	for (i = 0, j = 0; (i < ustrlen) && (j < astrlen); i++, mbstrlen++) {
+		c = NTFS_U28(ustr[i]);
+		while (*c != '\0') {
+			res = (int) (*c++ - astr[j++]);
+			if (res)
+				return res;
 			mbstrlen--;
 		}
-		res = (res<<8) + (int) (l - astr[j]);
-		if (res)
-			return res;
 	}
 	return (ustrlen - mbstrlen);
 }
@@ -2137,50 +2127,47 @@
 }
 
 /*
- * maps the Unicode char to 8bit equivalent
- * XXX currently only gets lower 8bit from the Unicode char
- * and substitutes a '_' for it if the result would be '\0';
- * something better has to be definitely though out
+ * maps the Unicode char to local character
  */
-wchar
+char *
 ntfs_u28(
 	struct ntfsmount *ntmp, 
 	wchar wc)
 {
-	char *p, *outp, inbuf[3], outbuf[3];
+	char *p, *outp, inbuf[3], outbuf[5];;
 	size_t ilen, olen;
 
+	outp = outbuf;
 	if (ntfs_iconv && ntmp->ntm_ic_u2l) {
-		ilen = olen = 2;
+		ilen = 2;
+		olen = 4;
 
 		inbuf[0] = (char)(wc>>8);
 		inbuf[1] = (char)wc;
 		inbuf[2] = '\0';
 		p = inbuf;
-		outp = outbuf;
 		ntfs_iconv->convchr(ntmp->ntm_ic_u2l, (const char **)&p, &ilen,
 				    &outp, &olen);
-		if (olen == 1) {
-			return ((wchar)(outbuf[0]&0xFF));
-		} else if (olen == 0) {
-			return ((wchar)((outbuf[0]<<8) | (outbuf[1]&0xFF)));
-		}
-		return ('?');
+		if (olen == 4)
+			*outp++ = '?';
+		*outp = '\0';
+		outp = outbuf;
+		return (outp);
 	}
 
 	p = ntmp->ntm_u28[(wc>>8)&0xFF];
-	if (p == NULL)
-		return ('_');
-	return (p[wc&0xFF]&0xFF);
+	outbuf[0] = (p == NULL) ? '_' : p[wc&0xFF] & 0xFF;
+	outbuf[1] = '\0';
+	return (outp);
 }
 
 wchar
 ntfs_82u(
 	struct ntfsmount *ntmp, 
-	wchar wc,
+	const char *c,
 	int *len)
 {
-	char *p, *outp, inbuf[3], outbuf[3];
+	char *outp, outbuf[3];
 	wchar uc;
 	size_t ilen, olen;
 
@@ -2188,13 +2175,8 @@
 		ilen = (size_t)*len;
 		olen = 2;
 
-		inbuf[0] = (char)(wc>>8);
-		inbuf[1] = (char)wc;
-		inbuf[2] = '\0';
-		p = inbuf;
 		outp = outbuf;
-		ntfs_iconv->convchr(ntmp->ntm_ic_l2u, (const char **)&p, &ilen,
-				    &outp, &olen);
+		ntfs_iconv->convchr(ntmp->ntm_ic_l2u, &c, &ilen, &outp, &olen);
 		*len -= (int)ilen;
 		uc = (wchar)((outbuf[0]<<8) | (outbuf[1]&0xFF));
 
@@ -2202,7 +2184,7 @@
 	}
 
 	if (ntmp->ntm_82u != NULL)
-		return (ntmp->ntm_82u[wc&0xFF]);
+		return (ntmp->ntm_82u[*c&0xFF]);
 
 	return ('?');
 }
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/fs/ntfs/ntfs_subr.h
--- a/head/sys/fs/ntfs/ntfs_subr.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/fs/ntfs/ntfs_subr.h	Tue Dec 06 20:26:16 2011 +0200
@@ -25,7 +25,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD$
+ * $FreeBSD: head/sys/fs/ntfs/ntfs_subr.h 228023 2011-11-27 15:43:49Z kevlo $
  */
 
 #define	VA_LOADED		0x0001
@@ -112,8 +112,8 @@
 int ntfs_u28_uninit(struct ntfsmount *ntmp);
 int ntfs_82u_init(struct ntfsmount *ntmp, char *cs_local, char *cs_ntfs);
 int ntfs_82u_uninit(struct ntfsmount *ntmp);
-wchar ntfs_u28(struct ntfsmount *ntmp, wchar wc);
-wchar ntfs_82u(struct ntfsmount *ntmp, wchar wc, int *len);
+char * ntfs_u28(struct ntfsmount *ntmp, wchar wc);
+wchar ntfs_82u(struct ntfsmount *ntmp, const char *c, int *len);
 #define NTFS_U28(ch)		ntfs_u28(ntmp, (ch))
 #define NTFS_82U(ch, len)	ntfs_82u(ntmp, (ch), len)
 #define	NTFS_UASTRCMP(ustr, ustrlen, astr, astrlen)	\
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/fs/ntfs/ntfs_vnops.c
--- a/head/sys/fs/ntfs/ntfs_vnops.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/fs/ntfs/ntfs_vnops.c	Tue Dec 06 20:26:16 2011 +0200
@@ -31,7 +31,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD$
+ * $FreeBSD: head/sys/fs/ntfs/ntfs_vnops.c 228023 2011-11-27 15:43:49Z kevlo $
  *
  */
 
@@ -481,7 +481,7 @@
 	struct uio *uio = ap->a_uio;
 	struct ntfsmount *ntmp = ip->i_mp;
 	int i, j, error = 0;
-	wchar c;
+	char *c;
 	u_int32_t faked = 0, num;
 	int ncookies = 0;
 	struct dirent cde;
@@ -538,11 +538,10 @@
 			if(!ntfs_isnamepermitted(ntmp,iep))
 				continue;
 
-			for(i=0, j=0; i<iep->ie_fnamelen; i++, j++) {
+			for(i=0, j=0; i<iep->ie_fnamelen; i++) {
 				c = NTFS_U28(iep->ie_fname[i]);
-				if (c&0xFF00)
-					cde.d_name[j++] = (char)(c>>8);
-				cde.d_name[j] = (char)c&0xFF;
+				while (*c != '\0')
+					cde.d_name[j++] = *c++;
 			}
 			cde.d_name[j] = '\0';
 			dprintf(("ntfs_readdir: elem: %d, fname:[%s] type: %d, flag: %d, ",
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/fs/nwfs/nwfs_io.c
--- a/head/sys/fs/nwfs/nwfs_io.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/fs/nwfs/nwfs_io.c	Tue Dec 06 20:26:16 2011 +0200
@@ -23,7 +23,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: head/sys/fs/nwfs/nwfs_io.c 222586 2011-06-01 21:00:28Z kib $
+ * $FreeBSD: head/sys/fs/nwfs/nwfs_io.c 228156 2011-11-30 17:39:00Z kib $
  *
  */
 #include <sys/param.h>
@@ -452,7 +452,7 @@
 			    ("nwfs_getpages: page %p is dirty", m));
 		} else {
 			int nvalid = ((size + DEV_BSIZE - 1) - toff) & ~(DEV_BSIZE - 1);
-			vm_page_set_valid(m, 0, nvalid);
+			vm_page_set_valid_range(m, 0, nvalid);
 			KASSERT((m->dirty & vm_page_bits(0, nvalid)) == 0,
 			    ("nwfs_getpages: page %p is dirty", m));
 		}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/fs/smbfs/smbfs_io.c
--- a/head/sys/fs/smbfs/smbfs_io.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/fs/smbfs/smbfs_io.c	Tue Dec 06 20:26:16 2011 +0200
@@ -23,7 +23,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: head/sys/fs/smbfs/smbfs_io.c 222586 2011-06-01 21:00:28Z kib $
+ * $FreeBSD: head/sys/fs/smbfs/smbfs_io.c 228156 2011-11-30 17:39:00Z kib $
  *
  */
 #include <sys/param.h>
@@ -509,7 +509,7 @@
 			 * Read operation filled a partial page.
 			 */
 			m->valid = 0;
-			vm_page_set_valid(m, 0, size - toff);
+			vm_page_set_valid_range(m, 0, size - toff);
 			KASSERT(m->dirty == 0,
 			    ("smbfs_getpages: page %p is dirty", m));
 		} else {
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/geom/geom_vfs.c
--- a/head/sys/geom/geom_vfs.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/geom/geom_vfs.c	Tue Dec 06 20:26:16 2011 +0200
@@ -25,7 +25,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/geom/geom_vfs.c 227015 2011-11-02 09:24:59Z mav $");
+__FBSDID("$FreeBSD: head/sys/geom/geom_vfs.c 228204 2011-12-02 17:09:48Z mav $");
 
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -169,8 +169,10 @@
 	g_topology_assert();
 
 	gp = cp->geom;
+	g_trace(G_T_TOPOLOGY, "g_vfs_orphan(%p(%s))", cp, gp->name);
 	sc = gp->softc;
-	g_trace(G_T_TOPOLOGY, "g_vfs_orphan(%p(%s))", cp, gp->name);
+	if (sc == NULL)
+		return;
 	mtx_lock(&sc->sc_mtx);
 	sc->sc_orphaned = 1;
 	destroy = (sc->sc_active == 0);
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/geom/part/g_part_apm.c
--- a/head/sys/geom/part/g_part_apm.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/geom/part/g_part_apm.c	Tue Dec 06 20:26:16 2011 +0200
@@ -25,7 +25,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/geom/part/g_part_apm.c 221654 2011-05-08 12:16:39Z ae $");
+__FBSDID("$FreeBSD: head/sys/geom/part/g_part_apm.c 228076 2011-11-28 16:07:26Z ae $");
 
 #include <sys/param.h>
 #include <sys/apm.h>
@@ -234,6 +234,12 @@
 		strncpy(entry->ent.ent_name, gpp->gpp_label,
 		    sizeof(entry->ent.ent_name));
 	}
+	if (baseentry->gpe_index >= table->self.ent_pmblkcnt)
+		table->self.ent_pmblkcnt = baseentry->gpe_index + 1;
+	KASSERT(table->self.ent_size >= table->self.ent_pmblkcnt,
+	    ("%s", __func__));
+	KASSERT(table->self.ent_size > baseentry->gpe_index,
+	    ("%s", __func__));
 	return (0);
 }
 
@@ -443,9 +449,9 @@
 
 	table = (struct g_part_apm_table *)basetable;
 
-	basetable->gpt_first = table->self.ent_pmblkcnt + 1;
+	basetable->gpt_first = table->self.ent_size + 1;
 	basetable->gpt_last = table->ddr.ddr_blkcount - 1;
-	basetable->gpt_entries = table->self.ent_pmblkcnt - 1;
+	basetable->gpt_entries = table->self.ent_size - 1;
 
 	for (index = table->self.ent_pmblkcnt - 1; index > 0; index--) {
 		error = apm_read_ent(cp, index + 1, &ent, table->tivo_series1);
@@ -497,67 +503,78 @@
 static int
 g_part_apm_write(struct g_part_table *basetable, struct g_consumer *cp)
 {
-	char buf[512];
+	struct g_provider *pp;
 	struct g_part_entry *baseentry;
 	struct g_part_apm_entry *entry;
 	struct g_part_apm_table *table;
-	int error, index;
+	char *buf, *ptr;
+	uint32_t index;
+	int error;
+	size_t tblsz;
 
+	pp = cp->provider;
 	table = (struct g_part_apm_table *)basetable;
 	/*
 	 * Tivo Series 1 disk partitions are currently read-only.
 	 */
 	if (table->tivo_series1)
 		return (EOPNOTSUPP);
-	bzero(buf, sizeof(buf));
 
-	/* Write the DDR and 'self' entry only when we're newly created. */
+	/* Write the DDR only when we're newly created. */
 	if (basetable->gpt_created) {
+		buf = g_malloc(pp->sectorsize, M_WAITOK | M_ZERO);
 		be16enc(buf, table->ddr.ddr_sig);
 		be16enc(buf + 2, table->ddr.ddr_blksize);
 		be32enc(buf + 4, table->ddr.ddr_blkcount);
-		error = g_write_data(cp, 0, buf, sizeof(buf));
+		error = g_write_data(cp, 0, buf, pp->sectorsize);
+		g_free(buf);
 		if (error)
 			return (error);
 	}
 
-	be16enc(buf, table->self.ent_sig);
-	be16enc(buf + 2, 0);
+	/* Allocate the buffer for all entries */
+	tblsz = table->self.ent_pmblkcnt;
+	buf = g_malloc(tblsz * pp->sectorsize, M_WAITOK | M_ZERO);
+
+	/* Fill the self entry */
+	be16enc(buf, APM_ENT_SIG);
 	be32enc(buf + 4, table->self.ent_pmblkcnt);
-
-	if (basetable->gpt_created) {
-		be32enc(buf + 8, table->self.ent_start);
-		be32enc(buf + 12, table->self.ent_size);
-		bcopy(table->self.ent_name, buf + 16,
-		    sizeof(table->self.ent_name));
-		bcopy(table->self.ent_type, buf + 48,
-		    sizeof(table->self.ent_type));
-		error = g_write_data(cp, 512, buf, sizeof(buf));
-		if (error)
-			return (error);
-	}
+	be32enc(buf + 8, table->self.ent_start);
+	be32enc(buf + 12, table->self.ent_size);
+	bcopy(table->self.ent_name, buf + 16, sizeof(table->self.ent_name));
+	bcopy(table->self.ent_type, buf + 48, sizeof(table->self.ent_type));
 
 	baseentry = LIST_FIRST(&basetable->gpt_entry);
-	for (index = 1; index <= basetable->gpt_entries; index++) {
+	for (index = 1; index < tblsz; index++) {
 		entry = (baseentry != NULL && index == baseentry->gpe_index)
 		    ? (struct g_part_apm_entry *)baseentry : NULL;
+		ptr = buf + index * pp->sectorsize;
+		be16enc(ptr, APM_ENT_SIG);
+		be32enc(ptr + 4, table->self.ent_pmblkcnt);
 		if (entry != NULL && !baseentry->gpe_deleted) {
-			be32enc(buf + 8, entry->ent.ent_start);
-			be32enc(buf + 12, entry->ent.ent_size);
-			bcopy(entry->ent.ent_name, buf + 16,
+			be32enc(ptr + 8, entry->ent.ent_start);
+			be32enc(ptr + 12, entry->ent.ent_size);
+			bcopy(entry->ent.ent_name, ptr + 16,
 			    sizeof(entry->ent.ent_name));
-			bcopy(entry->ent.ent_type, buf + 48,
+			bcopy(entry->ent.ent_type, ptr + 48,
 			    sizeof(entry->ent.ent_type));
 		} else {
-			bzero(buf + 8, 4 + 4 + 32 + 32);
-			strcpy(buf + 48, APM_ENT_TYPE_UNUSED);
+			strcpy(ptr + 48, APM_ENT_TYPE_UNUSED);
 		}
-		error = g_write_data(cp, (index + 1) * 512, buf, sizeof(buf));
-		if (error)
-			return (error);
 		if (entry != NULL)
 			baseentry = LIST_NEXT(baseentry, gpe_entry);
 	}
 
+	for (index = 0; index < tblsz; index += MAXPHYS / pp->sectorsize) {
+		error = g_write_data(cp, (1 + index) * pp->sectorsize,
+		    buf + index * pp->sectorsize,
+		    (tblsz - index > MAXPHYS / pp->sectorsize) ? MAXPHYS:
+		    (tblsz - index) * pp->sectorsize);
+		if (error) {
+			g_free(buf);
+			return (error);
+		}
+	}
+	g_free(buf);
 	return (0);
 }
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/i386/conf/PAE
--- a/head/sys/i386/conf/PAE	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/i386/conf/PAE	Tue Dec 06 20:26:16 2011 +0200
@@ -1,7 +1,7 @@
 #
 # PAE -- Generic kernel configuration file for FreeBSD/i386 PAE
 #
-# $FreeBSD: head/sys/i386/conf/PAE 221329 2011-05-02 16:51:02Z bschmidt $
+# $FreeBSD: head/sys/i386/conf/PAE 228003 2011-11-26 18:02:39Z marius $
 
 include GENERIC
 
@@ -24,7 +24,6 @@
 # than 4 gigabytes of memory.
 
 nodevice	ahb
-nodevice	amd
 nodevice	sym
 nodevice	trm
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/kern/kern_cpuset.c
--- a/head/sys/kern/kern_cpuset.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/kern/kern_cpuset.c	Tue Dec 06 20:26:16 2011 +0200
@@ -29,7 +29,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/kern/kern_cpuset.c 225617 2011-09-16 13:58:51Z kmacy $");
+__FBSDID("$FreeBSD: head/sys/kern/kern_cpuset.c 228275 2011-12-05 10:34:52Z kevlo $");
 
 #include "opt_ddb.h"
 
@@ -900,6 +900,7 @@
 	cpuwhich_t	which;
 	id_t		id;
 	cpusetid_t	*setid;
+};
 #endif
 int
 sys_cpuset_getid(struct thread *td, struct cpuset_getid_args *uap)
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/kern/kern_ffclock.c
--- a/head/sys/kern/kern_ffclock.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/kern/kern_ffclock.c	Tue Dec 06 20:26:16 2011 +0200
@@ -28,7 +28,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/kern/kern_ffclock.c 227776 2011-11-21 01:26:10Z lstewart $");
+__FBSDID("$FreeBSD: head/sys/kern/kern_ffclock.c 228173 2011-12-01 07:19:13Z lstewart $");
 
 #include "opt_ffclock.h"
 
@@ -49,6 +49,8 @@
 
 #ifdef FFCLOCK
 
+FEATURE(ffclock, "Feed-forward clock support");
+
 extern struct ffclock_estimate ffclock_estimate;
 extern struct bintime ffclock_boottime;
 extern int8_t ffclock_updated;
@@ -146,31 +148,33 @@
 }
 
 /*
- * Sysctl for the Feed-Forward Clock.
+ * Create a new kern.sysclock sysctl node, which will be home to some generic
+ * sysclock configuration variables. Feed-forward clock specific variables will
+ * live under the ffclock subnode.
  */
 
-static int ffclock_version = 2;
-SYSCTL_NODE(_kern, OID_AUTO, ffclock, CTLFLAG_RW, 0,
-    "Feed-Forward Clock Support");
-SYSCTL_INT(_kern_ffclock, OID_AUTO, version, CTLFLAG_RD, &ffclock_version, 0,
-    "Version of Feed-Forward Clock Support");
+SYSCTL_NODE(_kern, OID_AUTO, sysclock, CTLFLAG_RW, 0,
+    "System clock related configuration");
+SYSCTL_NODE(_kern_sysclock, OID_AUTO, ffclock, CTLFLAG_RW, 0,
+    "Feed-forward clock configuration");
 
-/*
- * Sysctl to select which clock is read when calling any of the
- * [get]{bin,nano,micro}[up]time() functions.
- */
-char *sysclocks[] = {"feedback", "feed-forward"};
-
+static char *sysclocks[] = {"feedback", "feed-forward"};
+#define	MAX_SYSCLOCK_NAME_LEN 16
 #define	NUM_SYSCLOCKS (sizeof(sysclocks) / sizeof(*sysclocks))
 
-/* Report or change the active timecounter hardware. */
+static int ffclock_version = 2;
+SYSCTL_INT(_kern_sysclock_ffclock, OID_AUTO, version, CTLFLAG_RD,
+    &ffclock_version, 0, "Feed-forward clock kernel version");
+
+/* List available sysclocks. */
 static int
-sysctl_kern_ffclock_choice(SYSCTL_HANDLER_ARGS)
+sysctl_kern_sysclock_available(SYSCTL_HANDLER_ARGS)
 {
 	struct sbuf *s;
 	int clk, error;
 
-	s = sbuf_new_for_sysctl(NULL, NULL, 16 * NUM_SYSCLOCKS, req);
+	s = sbuf_new_for_sysctl(NULL, NULL,
+	    MAX_SYSCLOCK_NAME_LEN * NUM_SYSCLOCKS, req);
 	if (s == NULL)
 		return (ENOMEM);
 
@@ -185,49 +189,51 @@
 	return (error);
 }
 
-SYSCTL_PROC(_kern_ffclock, OID_AUTO, choice, CTLTYPE_STRING | CTLFLAG_RD,
-    0, 0, sysctl_kern_ffclock_choice, "A", "Clock paradigms available");
+SYSCTL_PROC(_kern_sysclock, OID_AUTO, available, CTLTYPE_STRING | CTLFLAG_RD,
+    0, 0, sysctl_kern_sysclock_available, "A",
+    "List of available system clocks");
 
-extern int sysclock_active;
+/*
+ * Return the name of the active system clock if read, or attempt to change
+ * the active system clock to the user specified one if written to. The active
+ * system clock is read when calling any of the [get]{bin,nano,micro}[up]time()
+ * functions.
+ */
+static int
+sysctl_kern_sysclock_active(SYSCTL_HANDLER_ARGS)
+{
+	char newclock[MAX_SYSCLOCK_NAME_LEN];
+	int clk, error;
 
-static int
-sysctl_kern_ffclock_active(SYSCTL_HANDLER_ARGS)
-{
-	char newclock[32];
-	int error;
-
-	switch (sysclock_active) {
-	case SYSCLOCK_FBCK:
-		strlcpy(newclock, sysclocks[SYSCLOCK_FBCK], sizeof(newclock));
-		break;
-	case SYSCLOCK_FFWD:
-		strlcpy(newclock, sysclocks[SYSCLOCK_FFWD], sizeof(newclock));
-		break;
+	if (req->newptr == NULL) {
+		/* Return the name of the current active sysclock. */
+		strlcpy(newclock, sysclocks[sysclock_active], sizeof(newclock));
+		error = sysctl_handle_string(oidp, newclock,
+		    sizeof(newclock), req);
+	} else {
+		/* Change the active sysclock to the user specified one. */
+		error = EINVAL;
+		for (clk = 0; clk < NUM_SYSCLOCKS; clk++) {
+			if (strncmp((char *)req->newptr, sysclocks[clk],
+			    strlen(sysclocks[clk])) == 0) {
+				sysclock_active = clk;
+				error = 0;
+				break;
+			}
+		}
 	}
 
-	error = sysctl_handle_string(oidp, &newclock[0], sizeof(newclock), req);
-	if (error != 0 || req->newptr == NULL)
-		return (error);
-	if (strncmp(newclock, sysclocks[SYSCLOCK_FBCK],
-	    sizeof(sysclocks[SYSCLOCK_FBCK])) == 0)
-		sysclock_active = SYSCLOCK_FBCK;
-	else if (strncmp(newclock, sysclocks[SYSCLOCK_FFWD],
-	    sizeof(sysclocks[SYSCLOCK_FFWD])) == 0)
-		sysclock_active = SYSCLOCK_FFWD;
-	else
-		return (EINVAL);
-
 	return (error);
 }
 
-SYSCTL_PROC(_kern_ffclock, OID_AUTO, active, CTLTYPE_STRING | CTLFLAG_RW,
-    0, 0, sysctl_kern_ffclock_active, "A", "Kernel clock selected");
+SYSCTL_PROC(_kern_sysclock, OID_AUTO, active, CTLTYPE_STRING | CTLFLAG_RW,
+    0, 0, sysctl_kern_sysclock_active, "A",
+    "Name of the active system clock which is currently serving time");
 
-int sysctl_kern_ffclock_ffcounter_bypass = 0;
-
-SYSCTL_INT(_kern_ffclock, OID_AUTO, ffcounter_bypass, CTLFLAG_RW,
+static int sysctl_kern_ffclock_ffcounter_bypass = 0;
+SYSCTL_INT(_kern_sysclock_ffclock, OID_AUTO, ffcounter_bypass, CTLFLAG_RW,
     &sysctl_kern_ffclock_ffcounter_bypass, 0,
-    "Use reliable hardware timecounter as the Feed-Forward Counter");
+    "Use reliable hardware timecounter as the feed-forward counter");
 
 /*
  * High level functions to access the Feed-Forward Clock.
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/kern/kern_proc.c
--- a/head/sys/kern/kern_proc.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/kern/kern_proc.c	Tue Dec 06 20:26:16 2011 +0200
@@ -30,7 +30,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/kern/kern_proc.c 227874 2011-11-23 08:11:04Z trociny $");
+__FBSDID("$FreeBSD: head/sys/kern/kern_proc.c 228302 2011-12-06 06:40:14Z trociny $");
 
 #include "opt_compat.h"
 #include "opt_ddb.h"
@@ -54,6 +54,7 @@
 #include <sys/proc.h>
 #include <sys/ptrace.h>
 #include <sys/refcount.h>
+#include <sys/resourcevar.h>
 #include <sys/sbuf.h>
 #include <sys/sysent.h>
 #include <sys/sched.h>
@@ -1767,7 +1768,7 @@
 	int *name = (int*) arg1;
 	u_int namelen = arg2;
 	struct proc *p;
-	size_t vsize;
+	size_t vsize, size;
 	char **auxv;
 	int error;
 
@@ -1781,7 +1782,8 @@
 		PROC_UNLOCK(p);
 		return (ESRCH);
 	}
-	if ((error = p_cansee(curthread, p)) != 0) {
+	error = p_candebug(curthread, p);
+	if (error != 0) {
 		PROC_UNLOCK(p);
 		return (error);
 	}
@@ -1792,16 +1794,18 @@
 	_PHOLD(p);
 	PROC_UNLOCK(p);
 	error = get_proc_vector(curthread, p, &auxv, &vsize, PROC_AUX);
-	PRELE(p);
 	if (error == 0) {
 #ifdef COMPAT_FREEBSD32
 		if (SV_PROC_FLAG(p, SV_ILP32) != 0)
-			error = SYSCTL_OUT(req, auxv, vsize *
-			    sizeof(Elf32_Auxinfo));
+			size = vsize * sizeof(Elf32_Auxinfo);
 		else
 #endif
-		error = SYSCTL_OUT(req, auxv, vsize * sizeof(Elf_Auxinfo));
+		size = vsize * sizeof(Elf_Auxinfo);
+		PRELE(p);
+		error = SYSCTL_OUT(req, auxv, size);
 		free(auxv, M_TEMP);
+	} else {
+		PRELE(p);
 	}
 	return (error);
 }
@@ -2389,6 +2393,94 @@
 	return (error);
 }
 
+/*
+ * This sysctl allows a process to retrieve the resource limits for
+ * another process.
+ */
+static int
+sysctl_kern_proc_rlimit(SYSCTL_HANDLER_ARGS)
+{
+	int *name = (int*) arg1;
+	u_int namelen = arg2;
+	struct plimit *limp;
+	struct proc *p;
+	int error = 0;
+
+	if (namelen != 1)
+		return (EINVAL);
+
+	p = pfind((pid_t)name[0]);
+	if (p == NULL)
+		return (ESRCH);
+
+	if ((error = p_cansee(curthread, p)) != 0) {
+		PROC_UNLOCK(p);
+		return (error);
+	}
+
+	/*
+	 * Check the request size.  We alow sizes smaller rlimit array for
+	 * backward binary compatibility: the number of resource limits may
+	 * grow.
+	 */
+	if (sizeof(limp->pl_rlimit) < req->oldlen) {
+		PROC_UNLOCK(p);
+		return (EINVAL);
+	}
+
+	limp = lim_hold(p->p_limit);
+	PROC_UNLOCK(p);
+	error = SYSCTL_OUT(req, limp->pl_rlimit, req->oldlen);
+	lim_free(limp);
+	return (error);
+}
+
+/*
+ * This sysctl allows a process to retrieve ps_strings structure location of
+ * another process.
+ */
+static int
+sysctl_kern_proc_ps_strings(SYSCTL_HANDLER_ARGS)
+{
+	int *name = (int*) arg1;
+	u_int namelen = arg2;
+	struct proc *p;
+	vm_offset_t ps_strings;
+	int error;
+#ifdef COMPAT_FREEBSD32
+	uint32_t ps_strings32;
+#endif
+
+	if (namelen != 1)
+		return (EINVAL);
+
+	p = pfind((pid_t)name[0]);
+	if (p == NULL)
+		return (ESRCH);
+	error = p_candebug(curthread, p);
+	if (error != 0) {
+		PROC_UNLOCK(p);
+		return (error);
+	}
+#ifdef COMPAT_FREEBSD32
+	if ((req->flags & SCTL_MASK32) != 0) {
+		/*
+		 * We return 0 if the 32 bit emulation request is for a 64 bit
+		 * process.
+		 */
+		ps_strings32 = SV_PROC_FLAG(p, SV_ILP32) != 0 ?
+		    PTROUT(p->p_sysent->sv_psstrings) : 0;
+		PROC_UNLOCK(p);
+		error = SYSCTL_OUT(req, &ps_strings32, sizeof(ps_strings32));
+		return (error);
+	}
+#endif
+	ps_strings = p->p_sysent->sv_psstrings;
+	PROC_UNLOCK(p);
+	error = SYSCTL_OUT(req, &ps_strings, sizeof(ps_strings));
+	return (error);
+}
+
 SYSCTL_NODE(_kern, KERN_PROC, proc, CTLFLAG_RD,  0, "Process table");
 
 SYSCTL_PROC(_kern_proc, KERN_PROC_ALL, all, CTLFLAG_RD|CTLTYPE_STRUCT|
@@ -2484,3 +2576,10 @@
 
 static SYSCTL_NODE(_kern_proc, KERN_PROC_GROUPS, groups, CTLFLAG_RD |
 	CTLFLAG_MPSAFE, sysctl_kern_proc_groups, "Process groups");
+
+static SYSCTL_NODE(_kern_proc, KERN_PROC_RLIMIT, rlimit, CTLFLAG_RD |
+	CTLFLAG_MPSAFE, sysctl_kern_proc_rlimit, "Process resource limits");
+
+static SYSCTL_NODE(_kern_proc, KERN_PROC_PS_STRINGS, ps_strings,
+	CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_MPSAFE,
+	sysctl_kern_proc_ps_strings, "Process ps_strings location");
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/kern/kern_resource.c
--- a/head/sys/kern/kern_resource.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/kern/kern_resource.c	Tue Dec 06 20:26:16 2011 +0200
@@ -35,7 +35,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/kern/kern_resource.c 227315 2011-11-07 21:09:04Z trociny $");
+__FBSDID("$FreeBSD: head/sys/kern/kern_resource.c 228207 2011-12-02 19:59:46Z jhb $");
 
 #include "opt_compat.h"
 
@@ -488,8 +488,9 @@
 	sched_class(td, rtp->type);	/* XXX fix */
 	oldpri = td->td_user_pri;
 	sched_user_prio(td, newpri);
-	if (curthread == td)
-		sched_prio(curthread, td->td_user_pri); /* XXX dubious */
+	if (td->td_user_pri != oldpri && (td == curthread ||
+	    td->td_priority == oldpri || td->td_user_pri >= PRI_MAX_REALTIME))
+		sched_prio(td, td->td_user_pri);
 	if (TD_ON_UPILOCK(td) && oldpri != newpri) {
 		critical_enter();
 		thread_unlock(td);
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/kern/kern_switch.c
--- a/head/sys/kern/kern_switch.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/kern/kern_switch.c	Tue Dec 06 20:26:16 2011 +0200
@@ -26,7 +26,7 @@
 
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/sys/kern/kern_switch.c 228265 2011-12-04 21:27:41Z avg $");
 
 #include "opt_sched.h"
 
@@ -200,7 +200,7 @@
 
 	if (td->td_critnest == 1) {
 		td->td_critnest = 0;
-		if (td->td_owepreempt) {
+		if (td->td_owepreempt && !kdb_active) {
 			td->td_critnest = 1;
 			thread_lock(td);
 			td->td_critnest--;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/kern/kern_synch.c
--- a/head/sys/kern/kern_synch.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/kern/kern_synch.c	Tue Dec 06 20:26:16 2011 +0200
@@ -35,7 +35,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/kern/kern_synch.c 227749 2011-11-20 08:36:18Z hselasky $");
+__FBSDID("$FreeBSD: head/sys/kern/kern_synch.c 228234 2011-12-03 15:51:15Z hselasky $");
 
 #include "opt_ktrace.h"
 #include "opt_sched.h"
@@ -328,7 +328,8 @@
  * pause() delays the calling thread by the given number of system ticks.
  * During cold bootup, pause() uses the DELAY() function instead of
  * the tsleep() function to do the waiting. The "timo" argument must be
- * greater than zero.
+ * greater than or equal to zero. A "timo" value of zero is equivalent
+ * to a "timo" value of one.
  */
 int
 pause(const char *wmesg, int timo)
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/kern/kern_tc.c
--- a/head/sys/kern/kern_tc.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/kern/kern_tc.c	Tue Dec 06 20:26:16 2011 +0200
@@ -14,7 +14,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/kern/kern_tc.c 227789 2011-11-21 13:34:29Z lstewart $");
+__FBSDID("$FreeBSD: head/sys/kern/kern_tc.c 228123 2011-11-29 08:33:40Z lstewart $");
 
 #include "opt_ntp.h"
 #include "opt_ffclock.h"
@@ -178,7 +178,7 @@
  */
 
 #ifdef FFCLOCK
-static void
+void
 fbclock_binuptime(struct bintime *bt)
 {
 	struct timehands *th;
@@ -192,51 +192,51 @@
 	} while (gen == 0 || gen != th->th_generation);
 }
 
-static void
+void
 fbclock_nanouptime(struct timespec *tsp)
 {
 	struct bintime bt;
 
-	binuptime(&bt);
+	fbclock_binuptime(&bt);
 	bintime2timespec(&bt, tsp);
 }
 
-static void
+void
 fbclock_microuptime(struct timeval *tvp)
 {
 	struct bintime bt;
 
-	binuptime(&bt);
+	fbclock_binuptime(&bt);
 	bintime2timeval(&bt, tvp);
 }
 
-static void
+void
 fbclock_bintime(struct bintime *bt)
 {
 
-	binuptime(bt);
+	fbclock_binuptime(bt);
 	bintime_add(bt, &boottimebin);
 }
 
-static void
+void
 fbclock_nanotime(struct timespec *tsp)
 {
 	struct bintime bt;
 
-	bintime(&bt);
+	fbclock_bintime(&bt);
 	bintime2timespec(&bt, tsp);
 }
 
-static void
+void
 fbclock_microtime(struct timeval *tvp)
 {
 	struct bintime bt;
 
-	bintime(&bt);
+	fbclock_bintime(&bt);
 	bintime2timeval(&bt, tvp);
 }
 
-static void
+void
 fbclock_getbinuptime(struct bintime *bt)
 {
 	struct timehands *th;
@@ -249,7 +249,7 @@
 	} while (gen == 0 || gen != th->th_generation);
 }
 
-static void
+void
 fbclock_getnanouptime(struct timespec *tsp)
 {
 	struct timehands *th;
@@ -262,7 +262,7 @@
 	} while (gen == 0 || gen != th->th_generation);
 }
 
-static void
+void
 fbclock_getmicrouptime(struct timeval *tvp)
 {
 	struct timehands *th;
@@ -275,7 +275,7 @@
 	} while (gen == 0 || gen != th->th_generation);
 }
 
-static void
+void
 fbclock_getbintime(struct bintime *bt)
 {
 	struct timehands *th;
@@ -289,7 +289,7 @@
 	bintime_add(bt, &boottimebin);
 }
 
-static void
+void
 fbclock_getnanotime(struct timespec *tsp)
 {
 	struct timehands *th;
@@ -302,7 +302,7 @@
 	} while (gen == 0 || gen != th->th_generation);
 }
 
-static void
+void
 fbclock_getmicrotime(struct timeval *tvp)
 {
 	struct timehands *th;
@@ -470,38 +470,6 @@
 int8_t ffclock_updated;			/* New estimates are available. */
 struct mtx ffclock_mtx;			/* Mutex on ffclock_estimate. */
 
-struct sysclock_ops {
-	int active;
-	void (*binuptime) (struct bintime *bt);
-	void (*nanouptime) (struct timespec *tsp);
-	void (*microuptime) (struct timeval *tvp);
-	void (*bintime) (struct bintime *bt);
-	void (*nanotime) (struct timespec *tsp);
-	void (*microtime) (struct timeval *tvp);
-	void (*getbinuptime) (struct bintime *bt);
-	void (*getnanouptime) (struct timespec *tsp);
-	void (*getmicrouptime) (struct timeval *tvp);
-	void (*getbintime) (struct bintime *bt);
-	void (*getnanotime) (struct timespec *tsp);
-	void (*getmicrotime) (struct timeval *tvp);
-};
-
-static struct sysclock_ops sysclock = {
-	.active = SYSCLOCK_FBCK,
-	.binuptime = fbclock_binuptime,
-	.nanouptime = fbclock_nanouptime,
-	.microuptime = fbclock_microuptime,
-	.bintime = fbclock_bintime,
-	.nanotime = fbclock_nanotime,
-	.microtime = fbclock_microtime,
-	.getbinuptime = fbclock_getbinuptime,
-	.getnanouptime = fbclock_getnanouptime,
-	.getmicrouptime = fbclock_getmicrouptime,
-	.getbintime = fbclock_getbintime,
-	.getnanotime = fbclock_getnanotime,
-	.getmicrotime = fbclock_getmicrotime
-};
-
 struct fftimehands {
 	struct ffclock_estimate	cest;
 	struct bintime		tick_time;
@@ -794,46 +762,6 @@
 	fftimehands = ffth;
 }
 
-static void
-change_sysclock(int new_sysclock)
-{
-
-	sysclock.active = new_sysclock;
-
-	switch (sysclock.active) {
-	case SYSCLOCK_FBCK:
-		sysclock.binuptime = fbclock_binuptime;
-		sysclock.nanouptime = fbclock_nanouptime;
-		sysclock.microuptime = fbclock_microuptime;
-		sysclock.bintime = fbclock_bintime;
-		sysclock.nanotime = fbclock_nanotime;
-		sysclock.microtime = fbclock_microtime;
-		sysclock.getbinuptime = fbclock_getbinuptime;
-		sysclock.getnanouptime = fbclock_getnanouptime;
-		sysclock.getmicrouptime = fbclock_getmicrouptime;
-		sysclock.getbintime = fbclock_getbintime;
-		sysclock.getnanotime = fbclock_getnanotime;
-		sysclock.getmicrotime = fbclock_getmicrotime;
-		break;
-	case SYSCLOCK_FFWD:
-		sysclock.binuptime = ffclock_binuptime;
-		sysclock.nanouptime = ffclock_nanouptime;
-		sysclock.microuptime = ffclock_microuptime;
-		sysclock.bintime = ffclock_bintime;
-		sysclock.nanotime = ffclock_nanotime;
-		sysclock.microtime = ffclock_microtime;
-		sysclock.getbinuptime = ffclock_getbinuptime;
-		sysclock.getnanouptime = ffclock_getnanouptime;
-		sysclock.getmicrouptime = ffclock_getmicrouptime;
-		sysclock.getbintime = ffclock_getbintime;
-		sysclock.getnanotime = ffclock_getnanotime;
-		sysclock.getmicrotime = ffclock_getmicrotime;
-		break;
-	default:
-		break;
-	}
-}
-
 /*
  * Retrieve feed-forward counter and time of last kernel tick.
  */
@@ -949,84 +877,84 @@
 binuptime(struct bintime *bt)
 {
 
-	sysclock.binuptime(bt);
+	binuptime_fromclock(bt, sysclock_active);
 }
 
 void
 nanouptime(struct timespec *tsp)
 {
 
-	sysclock.nanouptime(tsp);
+	nanouptime_fromclock(tsp, sysclock_active);
 }
 
 void
 microuptime(struct timeval *tvp)
 {
 
-	sysclock.microuptime(tvp);
+	microuptime_fromclock(tvp, sysclock_active);
 }
 
 void
 bintime(struct bintime *bt)
 {
 
-	sysclock.bintime(bt);
+	bintime_fromclock(bt, sysclock_active);
 }
 
 void
 nanotime(struct timespec *tsp)
 {
 
-	sysclock.nanotime(tsp);
+	nanotime_fromclock(tsp, sysclock_active);
 }
 
 void
 microtime(struct timeval *tvp)
 {
 
-	sysclock.microtime(tvp);
+	microtime_fromclock(tvp, sysclock_active);
 }
 
 void
 getbinuptime(struct bintime *bt)
 {
 
-	sysclock.getbinuptime(bt);
+	getbinuptime_fromclock(bt, sysclock_active);
 }
 
 void
 getnanouptime(struct timespec *tsp)
 {
 
-	sysclock.getnanouptime(tsp);
+	getnanouptime_fromclock(tsp, sysclock_active);
 }
 
 void
 getmicrouptime(struct timeval *tvp)
 {
 
-	sysclock.getmicrouptime(tvp);
+	getmicrouptime_fromclock(tvp, sysclock_active);
 }
 
 void
 getbintime(struct bintime *bt)
 {
 
-	sysclock.getbintime(bt);
+	getbintime_fromclock(bt, sysclock_active);
 }
 
 void
 getnanotime(struct timespec *tsp)
 {
 
-	sysclock.getnanotime(tsp);
+	getnanotime_fromclock(tsp, sysclock_active);
 }
 
 void
 getmicrotime(struct timeval *tvp)
 {
 
-	sysclock.getmicrouptime(tvp);
+	getmicrouptime_fromclock(tvp, sysclock_active);
 }
 #endif /* FFCLOCK */
 
@@ -1268,11 +1196,6 @@
 	scale /= th->th_counter->tc_frequency;
 	th->th_scale = scale * 2;
 
-#ifdef FFCLOCK
-	if (sysclock_active != sysclock.active)
-		change_sysclock(sysclock_active);
-#endif
-
 	/*
 	 * Now that the struct timehands is again consistent, set the new
 	 * generation number, making sure to not make it zero.
@@ -1641,7 +1564,6 @@
 
 #ifdef FFCLOCK
 	ffclock_init();
-	change_sysclock(sysclock_active);
 #endif
 	/* warm up new timecounter (again) and get rolling. */
 	(void)timecounter->tc_get_timecount(timecounter);
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/kern/kern_thr.c
--- a/head/sys/kern/kern_thr.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/kern/kern_thr.c	Tue Dec 06 20:26:16 2011 +0200
@@ -25,7 +25,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/kern/kern_thr.c 227674 2011-11-18 19:14:42Z pho $");
+__FBSDID("$FreeBSD: head/sys/kern/kern_thr.c 228221 2011-12-03 12:35:13Z pho $");
 
 #include "opt_compat.h"
 #include "opt_posix.h"
@@ -450,8 +450,7 @@
 
 	tsp = NULL;
 	if (uap->timeout != NULL) {
-		error = copyin((const void *)uap->timeout, (void *)&ts,
-		    sizeof(struct timespec));
+		error = umtx_copyin_timeout(uap->timeout, &ts);
 		if (error != 0)
 			return (error);
 		tsp = &ts;
@@ -474,9 +473,6 @@
 	}
 
 	if (tsp != NULL) {
-		if (tsp->tv_sec < 0 || tsp->tv_nsec < 0 ||
-		    tsp->tv_nsec > 1000000000)
-			return (EINVAL);
 		if (tsp->tv_sec == 0 && tsp->tv_nsec == 0)
 			error = EWOULDBLOCK;
 		else {
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/kern/kern_umtx.c
--- a/head/sys/kern/kern_umtx.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/kern/kern_umtx.c	Tue Dec 06 20:26:16 2011 +0200
@@ -26,7 +26,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/kern/kern_umtx.c 227309 2011-11-07 15:43:11Z ed $");
+__FBSDID("$FreeBSD: head/sys/kern/kern_umtx.c 228219 2011-12-03 12:30:58Z pho $");
 
 #include "opt_compat.h"
 #include <sys/param.h>
@@ -2898,6 +2898,21 @@
 	return do_unlock_umtx(td, uap->umtx, td->td_tid);
 }
 
+inline int
+umtx_copyin_timeout(const void *addr, struct timespec *tsp)
+{
+	int error;
+
+	error = copyin(addr, tsp, sizeof(struct timespec));
+	if (error == 0) {
+		if (tsp->tv_sec < 0 ||
+		    tsp->tv_nsec >= 1000000000 ||
+		    tsp->tv_nsec < 0)
+			error = EINVAL;
+	}
+	return (error);
+}
+
 static int
 __umtx_op_lock_umtx(struct thread *td, struct _umtx_op_args *uap)
 {
@@ -2908,13 +2923,9 @@
 	if (uap->uaddr2 == NULL)
 		ts = NULL;
 	else {
-		error = copyin(uap->uaddr2, &timeout, sizeof(timeout));
+		error = umtx_copyin_timeout(uap->uaddr2, &timeout);
 		if (error != 0)
 			return (error);
-		if (timeout.tv_nsec >= 1000000000 ||
-		    timeout.tv_nsec < 0) {
-			return (EINVAL);
-		}
 		ts = &timeout;
 	}
 	return (do_lock_umtx(td, uap->obj, uap->val, ts));
@@ -2935,12 +2946,9 @@
 	if (uap->uaddr2 == NULL)
 		ts = NULL;
 	else {
-		error = copyin(uap->uaddr2, &timeout, sizeof(timeout));
+		error = umtx_copyin_timeout(uap->uaddr2, &timeout);
 		if (error != 0)
 			return (error);
-		if (timeout.tv_nsec >= 1000000000 ||
-		    timeout.tv_nsec < 0)
-			return (EINVAL);
 		ts = &timeout;
 	}
 	return do_wait(td, uap->obj, uap->val, ts, 0, 0);
@@ -2955,12 +2963,9 @@
 	if (uap->uaddr2 == NULL)
 		ts = NULL;
 	else {
-		error = copyin(uap->uaddr2, &timeout, sizeof(timeout));
+		error = umtx_copyin_timeout(uap->uaddr2, &timeout);
 		if (error != 0)
 			return (error);
-		if (timeout.tv_nsec >= 1000000000 ||
-		    timeout.tv_nsec < 0)
-			return (EINVAL);
 		ts = &timeout;
 	}
 	return do_wait(td, uap->obj, uap->val, ts, 1, 0);
@@ -2975,12 +2980,9 @@
 	if (uap->uaddr2 == NULL)
 		ts = NULL;
 	else {
-		error = copyin(uap->uaddr2, &timeout, sizeof(timeout));
+		error = umtx_copyin_timeout(uap->uaddr2, &timeout);
 		if (error != 0)
 			return (error);
-		if (timeout.tv_nsec >= 1000000000 ||
-		    timeout.tv_nsec < 0)
-			return (EINVAL);
 		ts = &timeout;
 	}
 	return do_wait(td, uap->obj, uap->val, ts, 1, 1);
@@ -3034,14 +3036,9 @@
 	if (uap->uaddr2 == NULL)
 		ts = NULL;
 	else {
-		error = copyin(uap->uaddr2, &timeout,
-		    sizeof(timeout));
+		error = umtx_copyin_timeout(uap->uaddr2, &timeout);
 		if (error != 0)
 			return (error);
-		if (timeout.tv_nsec >= 1000000000 ||
-		    timeout.tv_nsec < 0) {
-			return (EINVAL);
-		}
 		ts = &timeout;
 	}
 	return do_lock_umutex(td, uap->obj, ts, 0);
@@ -3063,14 +3060,9 @@
 	if (uap->uaddr2 == NULL)
 		ts = NULL;
 	else {
-		error = copyin(uap->uaddr2, &timeout,
-		    sizeof(timeout));
+		error = umtx_copyin_timeout(uap->uaddr2, &timeout);
 		if (error != 0)
 			return (error);
-		if (timeout.tv_nsec >= 1000000000 ||
-		    timeout.tv_nsec < 0) {
-			return (EINVAL);
-		}
 		ts = &timeout;
 	}
 	return do_lock_umutex(td, uap->obj, ts, _UMUTEX_WAIT);
@@ -3104,14 +3096,9 @@
 	if (uap->uaddr2 == NULL)
 		ts = NULL;
 	else {
-		error = copyin(uap->uaddr2, &timeout,
-		    sizeof(timeout));
+		error = umtx_copyin_timeout(uap->uaddr2, &timeout);
 		if (error != 0)
 			return (error);
-		if (timeout.tv_nsec >= 1000000000 ||
-		    timeout.tv_nsec < 0) {
-			return (EINVAL);
-		}
 		ts = &timeout;
 	}
 	return (do_cv_wait(td, uap->obj, uap->uaddr1, ts, uap->val));
@@ -3139,14 +3126,9 @@
 	if (uap->uaddr2 == NULL) {
 		error = do_rw_rdlock(td, uap->obj, uap->val, 0);
 	} else {
-		error = copyin(uap->uaddr2, &timeout,
-		    sizeof(timeout));
+		error = umtx_copyin_timeout(uap->uaddr2, &timeout);
 		if (error != 0)
 			return (error);
-		if (timeout.tv_nsec >= 1000000000 ||
-		    timeout.tv_nsec < 0) {
-			return (EINVAL);
-		}
 		error = do_rw_rdlock2(td, uap->obj, uap->val, &timeout);
 	}
 	return (error);
@@ -3162,14 +3144,9 @@
 	if (uap->uaddr2 == NULL) {
 		error = do_rw_wrlock(td, uap->obj, 0);
 	} else {
-		error = copyin(uap->uaddr2, &timeout,
-		    sizeof(timeout));
+		error = umtx_copyin_timeout(uap->uaddr2, &timeout);
 		if (error != 0)
 			return (error);
-		if (timeout.tv_nsec >= 1000000000 ||
-		    timeout.tv_nsec < 0) {
-			return (EINVAL);
-		}
 
 		error = do_rw_wrlock2(td, uap->obj, &timeout);
 	}
@@ -3192,14 +3169,9 @@
 	if (uap->uaddr2 == NULL)
 		ts = NULL;
 	else {
-		error = copyin(uap->uaddr2, &timeout,
-		    sizeof(timeout));
+		error = umtx_copyin_timeout(uap->uaddr2, &timeout);
 		if (error != 0)
 			return (error);
-		if (timeout.tv_nsec >= 1000000000 ||
-		    timeout.tv_nsec < 0) {
-			return (EINVAL);
-		}
 		ts = &timeout;
 	}
 	return (do_sem_wait(td, uap->obj, ts));
@@ -3267,15 +3239,21 @@
 };
 
 static inline int
-copyin_timeout32(void *addr, struct timespec *tsp)
+umtx_copyin_timeout32(void *addr, struct timespec *tsp)
 {
 	struct timespec32 ts32;
 	int error;
 
 	error = copyin(addr, &ts32, sizeof(struct timespec32));
 	if (error == 0) {
-		tsp->tv_sec = ts32.tv_sec;
-		tsp->tv_nsec = ts32.tv_nsec;
+		if (ts32.tv_sec < 0 ||
+		    ts32.tv_nsec >= 1000000000 ||
+		    ts32.tv_nsec < 0)
+			error = EINVAL;
+		else {
+			tsp->tv_sec = ts32.tv_sec;
+			tsp->tv_nsec = ts32.tv_nsec;
+		}
 	}
 	return (error);
 }
@@ -3290,13 +3268,9 @@
 	if (uap->uaddr2 == NULL)
 		ts = NULL;
 	else {
-		error = copyin_timeout32(uap->uaddr2, &timeout);
+		error = umtx_copyin_timeout32(uap->uaddr2, &timeout);
 		if (error != 0)
 			return (error);
-		if (timeout.tv_nsec >= 1000000000 ||
-		    timeout.tv_nsec < 0) {
-			return (EINVAL);
-		}
 		ts = &timeout;
 	}
 	return (do_lock_umtx32(td, uap->obj, uap->val, ts));
@@ -3317,12 +3291,9 @@
 	if (uap->uaddr2 == NULL)
 		ts = NULL;
 	else {
-		error = copyin_timeout32(uap->uaddr2, &timeout);
+		error = umtx_copyin_timeout32(uap->uaddr2, &timeout);
 		if (error != 0)
 			return (error);
-		if (timeout.tv_nsec >= 1000000000 ||
-		    timeout.tv_nsec < 0)
-			return (EINVAL);
 		ts = &timeout;
 	}
 	return do_wait(td, uap->obj, uap->val, ts, 1, 0);
@@ -3338,12 +3309,9 @@
 	if (uap->uaddr2 == NULL)
 		ts = NULL;
 	else {
-		error = copyin_timeout32(uap->uaddr2, &timeout);
+		error = umtx_copyin_timeout32(uap->uaddr2, &timeout);
 		if (error != 0)
 			return (error);
-		if (timeout.tv_nsec >= 1000000000 ||
-		    timeout.tv_nsec < 0)
-			return (EINVAL);
 		ts = &timeout;
 	}
 	return do_lock_umutex(td, uap->obj, ts, 0);
@@ -3359,12 +3327,9 @@
 	if (uap->uaddr2 == NULL)
 		ts = NULL;
 	else {
-		error = copyin_timeout32(uap->uaddr2, &timeout);
+		error = umtx_copyin_timeout32(uap->uaddr2, &timeout);
 		if (error != 0)
 			return (error);
-		if (timeout.tv_nsec >= 1000000000 ||
-		    timeout.tv_nsec < 0)
-			return (EINVAL);
 		ts = &timeout;
 	}
 	return do_lock_umutex(td, uap->obj, ts, _UMUTEX_WAIT);
@@ -3380,12 +3345,9 @@
 	if (uap->uaddr2 == NULL)
 		ts = NULL;
 	else {
-		error = copyin_timeout32(uap->uaddr2, &timeout);
+		error = umtx_copyin_timeout32(uap->uaddr2, &timeout);
 		if (error != 0)
 			return (error);
-		if (timeout.tv_nsec >= 1000000000 ||
-		    timeout.tv_nsec < 0)
-			return (EINVAL);
 		ts = &timeout;
 	}
 	return (do_cv_wait(td, uap->obj, uap->uaddr1, ts, uap->val));
@@ -3401,13 +3363,9 @@
 	if (uap->uaddr2 == NULL) {
 		error = do_rw_rdlock(td, uap->obj, uap->val, 0);
 	} else {
-		error = copyin_timeout32(uap->uaddr2, &timeout);
+		error = umtx_copyin_timeout32(uap->uaddr2, &timeout);
 		if (error != 0)
 			return (error);
-		if (timeout.tv_nsec >= 1000000000 ||
-		    timeout.tv_nsec < 0) {
-			return (EINVAL);
-		}
 		error = do_rw_rdlock2(td, uap->obj, uap->val, &timeout);
 	}
 	return (error);
@@ -3423,13 +3381,9 @@
 	if (uap->uaddr2 == NULL) {
 		error = do_rw_wrlock(td, uap->obj, 0);
 	} else {
-		error = copyin_timeout32(uap->uaddr2, &timeout);
+		error = umtx_copyin_timeout32(uap->uaddr2, &timeout);
 		if (error != 0)
 			return (error);
-		if (timeout.tv_nsec >= 1000000000 ||
-		    timeout.tv_nsec < 0) {
-			return (EINVAL);
-		}
 
 		error = do_rw_wrlock2(td, uap->obj, &timeout);
 	}
@@ -3445,12 +3399,9 @@
 	if (uap->uaddr2 == NULL)
 		ts = NULL;
 	else {
-		error = copyin_timeout32(uap->uaddr2, &timeout);
+		error = umtx_copyin_timeout32(uap->uaddr2, &timeout);
 		if (error != 0)
 			return (error);
-		if (timeout.tv_nsec >= 1000000000 ||
-		    timeout.tv_nsec < 0)
-			return (EINVAL);
 		ts = &timeout;
 	}
 	return do_wait(td, uap->obj, uap->val, ts, 1, 1);
@@ -3466,12 +3417,9 @@
 	if (uap->uaddr2 == NULL)
 		ts = NULL;
 	else {
-		error = copyin_timeout32(uap->uaddr2, &timeout);
+		error = umtx_copyin_timeout32(uap->uaddr2, &timeout);
 		if (error != 0)
 			return (error);
-		if (timeout.tv_nsec >= 1000000000 ||
-		    timeout.tv_nsec < 0)
-			return (EINVAL);
 		ts = &timeout;
 	}
 	return (do_sem_wait(td, uap->obj, ts));
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/kern/subr_blist.c
--- a/head/sys/kern/subr_blist.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/kern/subr_blist.c	Tue Dec 06 20:26:16 2011 +0200
@@ -29,7 +29,7 @@
  *
  *	This module implements a general bitmap allocator/deallocator.  The
  *	allocator eats around 2 bits per 'block'.  The module does not 
- *	try to interpret the meaning of a 'block' other then to return 
+ *	try to interpret the meaning of a 'block' other than to return 
  *	SWAPBLK_NONE on an allocation failure.
  *
  *	A radix tree is used to maintain the bitmap.  Two radix constants are
@@ -57,7 +57,7 @@
  *	the memory subsystem.  In contrast, the rlist code may allocate memory 
  *	on an rlist_free() call.  The non-blocking features of the blist code
  *	are used to great advantage in the swap code (vm/nswap_pager.c).  The
- *	rlist code uses a little less overall memory then the blist code (but
+ *	rlist code uses a little less overall memory than the blist code (but
  *	due to swap interleaving not all that much less), but the blist code 
  *	scales much, much better.
  *
@@ -72,7 +72,7 @@
  *	to cover the number of blocks requested at creation time even if it
  *	must be encompassed in larger root-node radix.
  *
- *	NOTE: the allocator cannot currently allocate more then 
+ *	NOTE: the allocator cannot currently allocate more than 
  *	BLIST_BMAP_RADIX blocks per call.  It will panic with 'allocation too 
  *	large' if you try.  This is an area that could use improvement.  The 
  *	radix is large enough that this restriction does not effect the swap 
@@ -84,7 +84,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/sys/kern/subr_blist.c 228233 2011-12-03 15:41:37Z eadler $");
 
 #ifdef _KERNEL
 
@@ -152,7 +152,7 @@
  * blist_create() - create a blist capable of handling up to the specified
  *		    number of blocks
  *
- *	blocks - must be greater then 0
+ *	blocks - must be greater than 0
  * 	flags  - malloc flags
  *
  *	The smallest blist consists of a single leaf node capable of 
@@ -841,7 +841,7 @@
  *
  *	Initialize our meta structures and bitmaps and calculate the exact
  *	amount of space required to manage 'count' blocks - this space may
- *	be considerably less then the calculated radix due to the large
+ *	be considerably less than the calculated radix due to the large
  *	RADIX values we use.
  */
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/kern/subr_bus.c
--- a/head/sys/kern/subr_bus.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/kern/subr_bus.c	Tue Dec 06 20:26:16 2011 +0200
@@ -25,7 +25,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/kern/subr_bus.c 227849 2011-11-22 21:56:55Z hselasky $");
+__FBSDID("$FreeBSD: head/sys/kern/subr_bus.c 228211 2011-12-02 22:03:27Z marius $");
 
 #include "opt_bus.h"
 
@@ -1139,7 +1139,7 @@
 			    dev->parent->devclass == busclass) {
 				if ((error = device_detach(dev)) != 0)
 					return (error);
-				device_set_driver(dev, NULL);
+				(void)device_set_driver(dev, NULL);
 				BUS_PROBE_NOMATCH(dev->parent, dev);
 				devnomatch(dev);
 				dev->flags |= DF_DONENOMATCH;
@@ -2017,19 +2017,23 @@
 		for (dl = first_matching_driver(dc, child);
 		     dl;
 		     dl = next_matching_driver(dc, child, dl)) {
-
 			/* If this driver's pass is too high, then ignore it. */
 			if (dl->pass > bus_current_pass)
 				continue;
 
 			PDEBUG(("Trying %s", DRIVERNAME(dl->driver)));
-			device_set_driver(child, dl->driver);
+			result = device_set_driver(child, dl->driver);
+			if (result == ENOMEM)
+				return (result);
+			else if (result != 0)
+				continue;
 			if (!hasclass) {
-				if (device_set_devclass(child, dl->driver->name)) {
-					printf("driver bug: Unable to set devclass (devname: %s)\n",
-					    (child ? device_get_name(child) :
-						"no device"));
-					device_set_driver(child, NULL);
+				if (device_set_devclass(child,
+				    dl->driver->name) != 0) {
+					printf("driver bug: Unable to set "
+					    "devclass (devname: %s)\n",
+					    device_get_name(child));
+					(void)device_set_driver(child, NULL);
 					continue;
 				}
 			}
@@ -2043,7 +2047,7 @@
 			/* Reset flags and devclass before the next probe. */
 			child->devflags = 0;
 			if (!hasclass)
-				device_set_devclass(child, NULL);
+				(void)device_set_devclass(child, NULL);
 
 			/*
 			 * If the driver returns SUCCESS, there can be
@@ -2060,7 +2064,7 @@
 			 * certainly doesn't match.
 			 */
 			if (result > 0) {
-				device_set_driver(child, NULL);
+				(void)device_set_driver(child, NULL);
 				continue;
 			}
 
@@ -2123,7 +2127,9 @@
 			if (result != 0)
 				return (result);
 		}
-		device_set_driver(child, best->driver);
+		result = device_set_driver(child, best->driver);
+		if (result != 0)
+			return (result);
 		resource_int_value(best->driver->name, child->unit,
 		    "flags", &child->devflags);
 
@@ -2732,8 +2738,8 @@
 		    dev->driver->name, dev->unit, error);
 		/* Unset the class; set in device_probe_child */
 		if (dev->devclass == NULL)
-			device_set_devclass(dev, NULL);
-		device_set_driver(dev, NULL);
+			(void)device_set_devclass(dev, NULL);
+		(void)device_set_driver(dev, NULL);
 		device_sysctl_fini(dev);
 		dev->state = DS_NOTPRESENT;
 		return (error);
@@ -2786,7 +2792,7 @@
 		devclass_delete_device(dev->devclass, dev);
 
 	dev->state = DS_NOTPRESENT;
-	device_set_driver(dev, NULL);
+	(void)device_set_driver(dev, NULL);
 	device_set_desc(dev, NULL);
 	device_sysctl_fini(dev);
 
@@ -4623,7 +4629,6 @@
 	print_driver_short(driver, indent);
 }
 
-
 static void
 print_driver_list(driver_list_t drivers, int indent)
 {
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/kern/sys_pipe.c
--- a/head/sys/kern/sys_pipe.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/kern/sys_pipe.c	Tue Dec 06 20:26:16 2011 +0200
@@ -89,7 +89,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/kern/sys_pipe.c 226042 2011-10-05 16:56:06Z kib $");
+__FBSDID("$FreeBSD: head/sys/kern/sys_pipe.c 228306 2011-12-06 11:24:03Z kib $");
 
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -569,12 +569,7 @@
 		/* If we're not backing this pipe, no need to do anything. */
 		error = 0;
 	}
-	if (error == 0) {
-		pipe->pipe_ino = alloc_unr(pipeino_unr);
-		if (pipe->pipe_ino == -1)
-			/* pipeclose will clear allocated kva */
-			error = ENOMEM;
-	}
+	pipe->pipe_ino = -1;
 	return (error);
 }
 
@@ -1398,16 +1393,40 @@
 	struct ucred *active_cred;
 	struct thread *td;
 {
-	struct pipe *pipe = fp->f_data;
+	struct pipe *pipe;
+	int new_unr;
 #ifdef MAC
 	int error;
+#endif
 
+	pipe = fp->f_data;
 	PIPE_LOCK(pipe);
+#ifdef MAC
 	error = mac_pipe_check_stat(active_cred, pipe->pipe_pair);
+	if (error) {
+		PIPE_UNLOCK(pipe);
+		return (error);
+	}
+#endif
+	/*
+	 * Lazily allocate an inode number for the pipe.  Most pipe
+	 * users do not call fstat(2) on the pipe, which means that
+	 * postponing the inode allocation until it is must be
+	 * returned to userland is useful.  If alloc_unr failed,
+	 * assign st_ino zero instead of returning an error.
+	 * Special pipe_ino values:
+	 *  -1 - not yet initialized;
+	 *  0  - alloc_unr failed, return 0 as st_ino forever.
+	 */
+	if (pipe->pipe_ino == (ino_t)-1) {
+		new_unr = alloc_unr(pipeino_unr);
+		if (new_unr != -1)
+			pipe->pipe_ino = new_unr;
+		else
+			pipe->pipe_ino = 0;
+	}
 	PIPE_UNLOCK(pipe);
-	if (error)
-		return (error);
-#endif
+
 	bzero(ub, sizeof(*ub));
 	ub->st_mode = S_IFIFO;
 	ub->st_blksize = PAGE_SIZE;
@@ -1554,8 +1573,8 @@
 	} else
 		PIPE_UNLOCK(cpipe);
 
-	if (ino > 0)
-		free_unr(pipeino_unr, cpipe->pipe_ino);
+	if (ino != 0 && ino != (ino_t)-1)
+		free_unr(pipeino_unr, ino);
 }
 
 /*ARGSUSED*/
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/kern/uipc_shm.c
--- a/head/sys/kern/uipc_shm.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/kern/uipc_shm.c	Tue Dec 06 20:26:16 2011 +0200
@@ -49,7 +49,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/kern/uipc_shm.c 225617 2011-09-16 13:58:51Z kmacy $");
+__FBSDID("$FreeBSD: head/sys/kern/uipc_shm.c 228156 2011-11-30 17:39:00Z kib $");
 
 #include "opt_capsicum.h"
 
@@ -301,7 +301,7 @@
 			 * have been zeroed.  Some of these valid bits may
 			 * have already been set.
 			 */
-			vm_page_set_valid(m, base, size);
+			vm_page_set_valid_range(m, base, size);
 
 			/*
 			 * Round "base" to the next block boundary so that the
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/kern/vfs_bio.c
--- a/head/sys/kern/vfs_bio.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/kern/vfs_bio.c	Tue Dec 06 20:26:16 2011 +0200
@@ -39,7 +39,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/kern/vfs_bio.c 226843 2011-10-27 16:39:17Z alc $");
+__FBSDID("$FreeBSD: head/sys/kern/vfs_bio.c 228156 2011-11-30 17:39:00Z kib $");
 
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -3499,7 +3499,7 @@
 	 * entire page.
 	 */
 	if (eoff > off)
-		vm_page_set_valid(m, off & PAGE_MASK, eoff - off);
+		vm_page_set_valid_range(m, off & PAGE_MASK, eoff - off);
 }
 
 /*
@@ -3662,7 +3662,7 @@
 		m = bp->b_pages[i];
 		if (n > size)
 			n = size;
-		vm_page_set_valid(m, base & PAGE_MASK, n);
+		vm_page_set_valid_range(m, base & PAGE_MASK, n);
 		base += n;
 		size -= n;
 		n = PAGE_SIZE;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/kern/vfs_syscalls.c
--- a/head/sys/kern/vfs_syscalls.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/kern/vfs_syscalls.c	Tue Dec 06 20:26:16 2011 +0200
@@ -35,7 +35,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/kern/vfs_syscalls.c 227691 2011-11-19 06:35:15Z ed $");
+__FBSDID("$FreeBSD: head/sys/kern/vfs_syscalls.c 227952 2011-11-24 20:34:06Z kib $");
 
 #include "opt_capsicum.h"
 #include "opt_compat.h"
@@ -4344,7 +4344,20 @@
 		fp = fp_fromcap;
 	}
 #endif /* CAPABILITIES */
-	if (fp->f_vnode == NULL) {
+
+	/*
+	 * The file could be not of the vnode type, or it may be not
+	 * yet fully initialized, in which case the f_vnode pointer
+	 * may be set, but f_ops is still badfileops.  E.g.,
+	 * devfs_open() transiently create such situation to
+	 * facilitate csw d_fdopen().
+	 *
+	 * Dupfdopen() handling in kern_openat() installs the
+	 * half-baked file into the process descriptor table, allowing
+	 * other thread to dereference it. Guard against the race by
+	 * checking f_ops.
+	 */
+	if (fp->f_vnode == NULL || fp->f_ops == &badfileops) {
 		fdrop(fp, curthread);
 		return (EINVAL);
 	}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/mips/atheros/ar71xx_chip.c
--- a/head/sys/mips/atheros/ar71xx_chip.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/mips/atheros/ar71xx_chip.c	Tue Dec 06 20:26:16 2011 +0200
@@ -25,7 +25,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/mips/atheros/ar71xx_chip.c 223562 2011-06-26 10:07:48Z kevlo $");
+__FBSDID("$FreeBSD: head/sys/mips/atheros/ar71xx_chip.c 228018 2011-11-27 11:15:59Z ray $");
 
 #include "opt_ddb.h"
 
@@ -150,34 +150,54 @@
 {
 	uint32_t pll;
 
-	switch(IFM_SUBTYPE(speed)) {
-	case IFM_10_T:
-		pll = PLL_ETH_INT_CLK_10;
+	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("%s%d: invalid speed %d\n",
+			    __func__, unit, speed);
+			return;
+	}
+	switch (unit) {
+	case 0:
+		ar71xx_write_pll(AR71XX_PLL_SEC_CONFIG,
+		    AR71XX_PLL_ETH_INT0_CLK, pll,
+		    AR71XX_PLL_ETH0_SHIFT);
 		break;
-	case IFM_100_TX:
-		pll = PLL_ETH_INT_CLK_100;
-		break;
-	case IFM_1000_T:
-		pll = PLL_ETH_INT_CLK_1000;
+	case 1:
+		ar71xx_write_pll(AR71XX_PLL_SEC_CONFIG,
+		    AR71XX_PLL_ETH_INT1_CLK, pll,
+		    AR71XX_PLL_ETH1_SHIFT);
 		break;
 	default:
-		printf("ar71xx_chip_set_pll_ge%d: invalid media 0x%08x\n",
-		    unit, speed);
+		printf("%s: invalid PLL set for arge unit: %d\n",
+		    __func__, unit);
 		return;
 	}
-
-	if (unit == 0)
-		ar71xx_write_pll(AR71XX_PLL_SEC_CONFIG,
-		    AR71XX_PLL_ETH_INT0_CLK, pll, AR71XX_PLL_ETH0_SHIFT);
-	else
-		ar71xx_write_pll(AR71XX_PLL_SEC_CONFIG,
-		    AR71XX_PLL_ETH_INT1_CLK, pll, AR71XX_PLL_ETH1_SHIFT);
 }
 
 static void
 ar71xx_chip_ddr_flush_ge(int unit)
 {
-	ar71xx_ddr_flush((unit == 0)?AR71XX_WB_FLUSH_GE0:AR71XX_WB_FLUSH_GE1);
+	switch (unit) {
+	case 0:
+		ar71xx_ddr_flush(AR71XX_WB_FLUSH_GE0);
+		break;
+	case 1:
+		ar71xx_ddr_flush(AR71XX_WB_FLUSH_GE1);
+		break;
+	default:
+		printf("%s: invalid DDR flush for arge unit: %d\n",
+		    __func__, unit);
+		return;
+	}
 }
 
 static void
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/mips/atheros/ar71xx_cpudef.h
--- a/head/sys/mips/atheros/ar71xx_cpudef.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/mips/atheros/ar71xx_cpudef.h	Tue Dec 06 20:26:16 2011 +0200
@@ -24,7 +24,7 @@
  * SUCH DAMAGE.
  */
 
-/* $FreeBSD: head/sys/mips/atheros/ar71xx_cpudef.h 221198 2011-04-29 06:25:11Z adrian $ */
+/* $FreeBSD: head/sys/mips/atheros/ar71xx_cpudef.h 228018 2011-11-27 11:15:59Z ray $ */
 
 #ifndef	__AR71XX_CPUDEF_H__
 #define	__AR71XX_CPUDEF_H__
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/mips/atheros/ar71xx_machdep.c
--- a/head/sys/mips/atheros/ar71xx_machdep.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/mips/atheros/ar71xx_machdep.c	Tue Dec 06 20:26:16 2011 +0200
@@ -25,7 +25,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/mips/atheros/ar71xx_machdep.c 223562 2011-06-26 10:07:48Z kevlo $");
+__FBSDID("$FreeBSD: head/sys/mips/atheros/ar71xx_machdep.c 227924 2011-11-24 07:32:52Z adrian $");
 
 #include "opt_ddb.h"
 
@@ -168,8 +168,8 @@
     __register_t a2 __unused, __register_t a3 __unused)
 {
 	uint64_t platform_counter_freq;
-	int argc, i;
-	char **argv, **envp;
+	int argc = 0, i;
+	char **argv = NULL, **envp = NULL;
 	vm_offset_t kernend;
 
 	/* 
@@ -184,9 +184,18 @@
 	/* Initialize pcpu stuff */
 	mips_pcpu0_init();
 
+	/*
+	 * Until some more sensible abstractions for uboot/redboot
+	 * environment handling, we have to make this a compile-time
+	 * hack.  The existing code handles the uboot environment
+	 * very incorrectly so we should just ignore initialising
+	 * the relevant pointers.
+	 */
+#ifndef	AR71XX_ENV_UBOOT
 	argc = a0;
 	argv = (char**)a1;
 	envp = (char**)a2;
+#endif
 	/* 
 	 * Protect ourselves from garbage in registers 
 	 */
@@ -255,6 +264,9 @@
 	printf("  a2 = %08x\n", a2);
 	printf("  a3 = %08x\n", a3);
 
+	/*
+	 * XXX this code is very redboot specific.
+	 */
 	printf("Cmd line:");
 	if (MIPS_IS_VALID_PTR(argv)) {
 		for (i = 0; i < argc; i++) {
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/mips/atheros/ar724x_chip.c
--- a/head/sys/mips/atheros/ar724x_chip.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/mips/atheros/ar724x_chip.c	Tue Dec 06 20:26:16 2011 +0200
@@ -25,7 +25,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/mips/atheros/ar724x_chip.c 223562 2011-06-26 10:07:48Z kevlo $");
+__FBSDID("$FreeBSD: head/sys/mips/atheros/ar724x_chip.c 228018 2011-11-27 11:15:59Z ray $");
 
 #include "opt_ddb.h"
 
@@ -133,8 +133,7 @@
 {
 	uint32_t pll;
 
-	printf("%s(arge%d, %#x)\n", __func__, unit, speed);
-
+	/* XXX move it */
 	if (ar71xx_soc == AR71XX_SOC_AR7242) {
 		if (unit == 0) {
 			/* 7242 with RTL8309 */
@@ -164,16 +163,55 @@
 		return;
 	}
 
-	ar71xx_write_pll(AR71XX_PLL_SEC_CONFIG, AR71XX_PLL_ETH_INT0_CLK, pll,
-	    (unit == 0)?AR71XX_PLL_ETH0_SHIFT:AR71XX_PLL_ETH1_SHIFT);
+	switch (unit) {
+	case 0:
+		/* TODO */
+		ar71xx_write_pll(AR71XX_PLL_SEC_CONFIG, AR71XX_PLL_ETH_INT0_CLK, pll,
+		    AR71XX_PLL_ETH0_SHIFT);
+		break;
+	case 1:
+		/* TODO */
+		ar71xx_write_pll(AR71XX_PLL_SEC_CONFIG, AR71XX_PLL_ETH_INT1_CLK, pll,
+		    AR71XX_PLL_ETH1_SHIFT);
+		break;
+	default:
+		printf("%s: invalid PLL set for arge unit: %d\n",
+		    __func__, unit);
+		return;
+	}
 }
 
 
 static void
+<<<<<<< .mine
 ar724x_chip_set_mii_mode(int unit, int mode, int speed)
+||||||| .r227904
+ar724x_chip_set_pll_ge1(int speed)
+=======
+ar724x_chip_ddr_flush_ge(int unit)
+>>>>>>> .r228310
 {
+<<<<<<< .mine
 	uint32_t pll;
+||||||| .r227904
+}
+=======
+	switch (unit) {
+	case 0:
+		ar71xx_ddr_flush(AR724X_DDR_REG_FLUSH_GE0);
+		break;
+	case 1:
+		ar71xx_ddr_flush(AR724X_DDR_REG_FLUSH_GE1);
+		break;
+	default:
+		printf("%s: invalid DDR flush for arge unit: %d\n",
+		    __func__, unit);
+		return;
+	}
+}
+>>>>>>> .r228310
 
+<<<<<<< .mine
 	printf("%s(%d)\n", __func__, speed);
 
 	if (ar71xx_soc == AR71XX_SOC_AR7242) {
@@ -199,6 +237,23 @@
 }
 
 static void
+||||||| .r227904
+static void
+ar724x_chip_ddr_flush_ge0(void)
+{
+	ar71xx_ddr_flush(AR724X_DDR_REG_FLUSH_GE0);
+}
+
+static void
+ar724x_chip_ddr_flush_ge1(void)
+{
+	ar71xx_ddr_flush(AR724X_DDR_REG_FLUSH_GE1);
+}
+
+static void
+=======
+static void
+>>>>>>> .r228310
 ar724x_chip_ddr_flush_ip2(void)
 {
 	ar71xx_ddr_flush(AR724X_DDR_REG_FLUSH_PCIE);
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/mips/atheros/ar91xx_chip.c
--- a/head/sys/mips/atheros/ar91xx_chip.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/mips/atheros/ar91xx_chip.c	Tue Dec 06 20:26:16 2011 +0200
@@ -25,7 +25,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/mips/atheros/ar91xx_chip.c 223562 2011-06-26 10:07:48Z kevlo $");
+__FBSDID("$FreeBSD: head/sys/mips/atheros/ar91xx_chip.c 228018 2011-11-27 11:15:59Z ray $");
 
 #include "opt_ddb.h"
 
@@ -123,34 +123,54 @@
 {
 	uint32_t pll;
 
-	switch(IFM_SUBTYPE(speed)) {
-	case IFM_10_T:
-		pll = AR91XX_PLL_VAL_10;
+	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("%s%d: invalid speed %d\n",
+			    __func__, unit, speed);
+			return;
+	}
+	switch (unit) {
+	case 0:
+		ar71xx_write_pll(AR91XX_PLL_REG_ETH_CONFIG,
+		    AR91XX_PLL_REG_ETH0_INT_CLOCK, pll,
+		    AR91XX_ETH0_PLL_SHIFT);
 		break;
-	case IFM_100_TX:
-		pll = AR91XX_PLL_VAL_100;
-		break;
-	case IFM_1000_T:
-		pll = AR91XX_PLL_VAL_1000;
+	case 1:
+		ar71xx_write_pll(AR91XX_PLL_REG_ETH_CONFIG,
+		    AR91XX_PLL_REG_ETH1_INT_CLOCK, pll,
+		    AR91XX_ETH1_PLL_SHIFT);
 		break;
 	default:
-		printf("ar91xx_chip_set_pll_ge%d: invalid media 0x%08x\n",
-		    unit, speed);
+		printf("%s: invalid PLL set for arge unit: %d\n",
+		    __func__, unit);
 		return;
 	}
-	if (unit == 0)
-		ar71xx_write_pll(AR91XX_PLL_REG_ETH_CONFIG,
-		    AR91XX_PLL_REG_ETH0_INT_CLOCK, pll, AR91XX_ETH0_PLL_SHIFT);
-	else
-		ar71xx_write_pll(AR91XX_PLL_REG_ETH_CONFIG,
-		    AR91XX_PLL_REG_ETH1_INT_CLOCK, pll, AR91XX_ETH1_PLL_SHIFT);
 }
 
 static void
 ar91xx_chip_ddr_flush_ge(int unit)
 {
-	ar71xx_ddr_flush((unit == 0)?AR91XX_DDR_REG_FLUSH_GE0:
-	    AR91XX_DDR_REG_FLUSH_GE1);
+	switch (unit) {
+	case 0:
+		ar71xx_ddr_flush(AR91XX_DDR_REG_FLUSH_GE0);
+		break;
+	case 1:
+		ar71xx_ddr_flush(AR91XX_DDR_REG_FLUSH_GE1);
+		break;
+	default:
+		printf("%s: invalid DDR flush for arge unit: %d\n",
+		    __func__, unit);
+		return;
+	}
 }
 
 static void
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/mips/atheros/if_arge.c
--- a/head/sys/mips/atheros/if_arge.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/mips/atheros/if_arge.c	Tue Dec 06 20:26:16 2011 +0200
@@ -26,7 +26,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/mips/atheros/if_arge.c 227843 2011-11-22 21:28:20Z marius $");
+__FBSDID("$FreeBSD: head/sys/mips/atheros/if_arge.c 228064 2011-11-28 13:42:59Z ray $");
 
 /*
  * AR71XX gigabit ethernet driver
@@ -177,6 +177,16 @@
 
 MTX_SYSINIT(miibus_mtx, &miibus_mtx, "arge mii lock", MTX_DEF);
 
+/*
+ * Flushes all 
+ */
+static void
+arge_flush_ddr(struct arge_softc *sc)
+{
+
+	ar71xx_device_flush_ddr_ge(sc->arge_mac_unit);
+}
+
 static int 
 arge_probe(device_t dev)
 {
@@ -908,7 +918,7 @@
 	ARGE_WRITE(sc, AR71XX_MAC_FIFO_TX_THRESHOLD, fifo_tx);
 
 	/* set PLL registers */
-	ar71xx_device_set_pll_ge(sc->arge_mac_unit, media);
+	ar71xx_device_set_pll_ge(sc->arge_mac_unit, if_speed);
 }
 
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/mips/cavium/files.octeon1
--- a/head/sys/mips/cavium/files.octeon1	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/mips/cavium/files.octeon1	Tue Dec 06 20:26:16 2011 +0200
@@ -46,12 +46,14 @@
 
 mips/cavium/usb/octusb.c			optional usb octusb
 mips/cavium/usb/octusb_octeon.c			optional usb octusb
+contrib/octeon-sdk/cvmx-usb.c			optional usb octusb
+
+contrib/octeon-sdk/cvmx-usb.c			optional usb cndotg
+dev/usb/controller/dotg_octeon.c		optional usb cndotg
+dev/usb/controller/dotg_cn50xx.c		optional usb cndotg
 
 dev/cfi/cfi_bus_ciu.c				optional cfi
 
-contrib/octeon-sdk/cvmx-usb.c			optional usb dotg
-#octusb
-
 # XXX Some files could be excluded in some configurations.  Making them
 #     optional but on in the default config would seem reasonable.
 contrib/octeon-sdk/cvmx-cmd-queue.c		standard
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/mips/cavium/octe/ethernet-rgmii.c
--- a/head/sys/mips/cavium/octe/ethernet-rgmii.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/mips/cavium/octe/ethernet-rgmii.c	Tue Dec 06 20:26:16 2011 +0200
@@ -216,6 +216,15 @@
 	int rid;
 
 	cvm_oct_common_init(ifp);
+
+//	char mac[6] = {
+//		cvmx_sysinfo_get()->mac_addr_base[0],
+//		cvmx_sysinfo_get()->mac_addr_base[1],
+//		cvmx_sysinfo_get()->mac_addr_base[2],
+//		cvmx_sysinfo_get()->mac_addr_base[3],
+//		cvmx_sysinfo_get()->mac_addr_base[4],
+//		cvmx_sysinfo_get()->mac_addr_base[5] };
+//	mac[5] += cvm_oct_mac_addr_offset++;
 	priv->open = cvm_oct_common_open;
 	priv->stop = cvm_oct_common_stop;
 	priv->stop(ifp);
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/mips/cavium/octe/octe.c
--- a/head/sys/mips/cavium/octe/octe.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/mips/cavium/octe/octe.c	Tue Dec 06 20:26:16 2011 +0200
@@ -145,7 +145,7 @@
 
 	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
 
-	if (priv->phy_id != -1) {
+	if (priv->phy_id != -1 && 0) {
 		if (priv->phy_device == NULL) {
 			error = mii_attach(dev, &priv->miibus, ifp,
 			    octe_mii_medchange, octe_mii_medstat,
@@ -190,7 +190,18 @@
 		mtx_init(&priv->tx_free_queue[qos].ifq_mtx, ifp->if_xname, "octe tx free queue", MTX_DEF);
 		IFQ_SET_MAXLEN(&priv->tx_free_queue[qos], MAX_OUT_QUEUE_DEPTH);
 	}
+	priv->mac[0] = 0x00;
+	priv->mac[1] = 0xDE;
+	priv->mac[2] = 0xAD;
+	priv->mac[3] = 0x20;
+	priv->mac[4] = 0x75;
+	priv->mac[5] = 0x00;
 
+	printf("\tMAC: %02x:%02x:%02x:%02x:%02x:%02x\n",
+	    priv->mac[0], priv->mac[1],
+	    priv->mac[2], priv->mac[3],
+	    priv->mac[4], priv->mac[5]
+	    );
 	ether_ifattach(ifp, priv->mac);
 
 	ifp->if_transmit = octe_transmit;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/mips/cavium/octeon_machdep.c
--- a/head/sys/mips/cavium/octeon_machdep.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/mips/cavium/octeon_machdep.c	Tue Dec 06 20:26:16 2011 +0200
@@ -23,10 +23,10 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD$
+ * $FreeBSD: head/sys/mips/cavium/octeon_machdep.c 228088 2011-11-28 19:28:29Z gonzo $
  */
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/sys/mips/cavium/octeon_machdep.c 228088 2011-11-28 19:28:29Z gonzo $");
 
 #include <sys/param.h>
 #include <sys/conf.h>
@@ -569,6 +569,8 @@
 					octeon_bootinfo->board_rev_major,
 					octeon_bootinfo->board_rev_minor,
 					octeon_bootinfo->eclock_hz);
+	memcpy(cvmx_sysinfo_get()->mac_addr_base, octeon_bootinfo->mac_addr_base, 6);
+	cvmx_sysinfo_get()->mac_addr_count = octeon_bootinfo->mac_addr_count;
 }
 
 static void
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/mips/conf/AR91XX_BASE
--- a/head/sys/mips/conf/AR91XX_BASE	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/mips/conf/AR91XX_BASE	Tue Dec 06 20:26:16 2011 +0200
@@ -7,7 +7,7 @@
 # override the default options (adding devices as needed) and adding
 # hints as needed (for example, the GPIO and LAN PHY.)
 #
-# $FreeBSD: head/sys/mips/conf/AR91XX_BASE 227780 2011-11-21 06:45:12Z adrian $
+# $FreeBSD: head/sys/mips/conf/AR91XX_BASE 227920 2011-11-24 04:34:04Z adrian $
 #
 
 machine         mips mipseb
@@ -29,7 +29,7 @@
 options		SCHED_4BSD		#4BSD scheduler
 options		INET			#InterNETworking
 options		INET6			#InterNETworking
-options		NFSCL			#Network Filesystem Client
+#options		NFSCL			#Network Filesystem Client
 options		PSEUDOFS		#Pseudo-filesystem framework
 options		_KPOSIX_PRIORITY_SCHEDULING #Posix P1003_1B real-time extensions
 
@@ -39,10 +39,11 @@
 options		INVARIANT_SUPPORT
 options		WITNESS
 options		WITNESS_SKIPSPIN
-options         FFS                     #Berkeley Fast Filesystem
-options         SOFTUPDATES             #Enable FFS soft updates support
-options         UFS_ACL                 #Support for access control lists
-options         UFS_DIRHASH             #Improve performance on big directories
+options		FFS                     #Berkeley Fast Filesystem
+#options		SOFTUPDATES             #Enable FFS soft updates support
+#options		UFS_ACL                 #Support for access control lists
+#options		UFS_DIRHASH             #Improve performance on big directories
+options		NO_FFS_SNAPSHOT		# We don't require snapshot support
 
 # Wireless NIC cards
 options		IEEE80211_DEBUG
@@ -62,7 +63,19 @@
 options		ATH_DIAGAPI
 option		ATH_ENABLE_11N
 
-device		ath_hal
+# Don't bother compiling the whole HAL - AH_SUPPORT_AR9130 breaks the
+# rest of the 11n chipset support at the moment and the pre-AR5212
+# HALs aren't required.
+# device		ath_hal
+
+# The AR9130 code requires AR5416; and AR5416 requires the AR5212 code.
+device		ath_ar5212
+device		ath_ar5416
+device		ath_ar9130
+# This is needed so at least one RF backend is present, or the current
+# HAL setup won't compile.  Remove this once the 11n chip RF backends
+# are converted over to be in the linker set.
+device		ath_rf5111
 
 options		AH_DEBUG
 option		AH_SUPPORT_AR5416
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/mips/conf/AR91XX_BASE.hints
--- a/head/sys/mips/conf/AR91XX_BASE.hints	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/mips/conf/AR91XX_BASE.hints	Tue Dec 06 20:26:16 2011 +0200
@@ -4,7 +4,7 @@
 # then override the default options (adding devices as needed) and adding
 # hints as needed (for example, the GPIO and LAN PHY.)
 
-# $FreeBSD: head/sys/mips/conf/AR91XX_BASE.hints 220295 2011-04-03 13:19:58Z adrian $
+# $FreeBSD: head/sys/mips/conf/AR91XX_BASE.hints 227919 2011-11-24 04:23:42Z adrian $
 
 hint.apb.0.at="nexus0"
 hint.apb.0.irq=4
@@ -32,6 +32,7 @@
 hint.arge.1.msize=0x1000
 hint.arge.1.irq=3
 
+# XXX The ath device hangs off of the AHB, rather than the Nexus.
 hint.ath.0.at="nexus0"
 hint.ath.0.maddr=0x180c0000
 hint.ath.0.msize=0x30000
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/mips/conf/OCTEON1
--- a/head/sys/mips/conf/OCTEON1	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/mips/conf/OCTEON1	Tue Dec 06 20:26:16 2011 +0200
@@ -24,7 +24,7 @@
 makeoptions	LDSCRIPT_NAME=ldscript.mips.octeon1
 
 # Don't build any modules yet.
-makeoptions	MODULES_OVERRIDE=""
+makeoptions	MODULES_OVERRIDE="wlan_acl wlan_amrr wlan_ccmp wlan_rssadapt wlan_tkip wlan_wep wlan_xauth"
 makeoptions	KERNLOADADDR=0xffffffff80100000
 
 include		"../cavium/std.octeon1"
@@ -34,8 +34,8 @@
 #makeoptions	DEBUG=-g		#Build kernel with gdb(1) debug symbols
 
 # Board-specific support that cannot be auto-detected at runtime.
-options 	OCTEON_VENDOR_LANNER		# Support for Lanner boards.
-#options 	OCTEON_BOARD_CAPK_0100ND	# Support for CAPK-0100nd.
+options 	OCTEON_VENDOR_D_LINK		# Support for Lanner boards.
+options 	OCTEON_BOARD_DSR_1000N		# Support for CAPK-0100nd.
 
 # XXX This option is very nearly irrelevant.
 options 	ISA_MIPS64
@@ -45,11 +45,11 @@
 options 	INET			# InterNETworking
 options 	INET6			# IPv6 communications protocols
 options 	SCTP			# Stream Control Transmission Protocol
-#options 	FFS			# Berkeley Fast Filesystem
-#options 	SOFTUPDATES		# Enable FFS soft updates support
-#options 	UFS_ACL			# Support for access control lists
-#options 	UFS_DIRHASH		# Improve performance on big directories
-#options 	UFS_GJOURNAL		# Enable gjournal-based UFS journaling
+options 	FFS			# Berkeley Fast Filesystem
+options 	SOFTUPDATES		# Enable FFS soft updates support
+options 	UFS_ACL			# Support for access control lists
+options 	UFS_DIRHASH		# Improve performance on big directories
+options 	UFS_GJOURNAL		# Enable gjournal-based UFS journaling
 options 	MD_ROOT			# MD is a potential root device
 options 	NFSCL			# Network Filesystem Client
 options 	NFSD			# Network Filesystem Server
@@ -82,6 +82,7 @@
 options 	KDB			# Enable kernel debugger support.
 options 	DDB			# Support DDB.
 #options 	GDB			# Support remote GDB.
+options 	ALT_BREAK_TO_DEBUGGER
 options 	DEADLKRES		# Enable the deadlock resolver
 options 	INVARIANTS		# Enable calls of extra sanity checking
 options 	INVARIANT_SUPPORT	# Extra sanity checks of internal structures, required by INVARIANTS
@@ -212,9 +213,12 @@
 
 # PCI Ethernet NICs that use the common MII bus controller code.
 # NOTE: Be sure to keep the 'device miibus' line in order to use these NICs!
-device		mii			#bus		# MII bus support
+device		miibus		# MII bus support
+
+#device		mii			#bus		# MII bus support
 device		switch
-device		bcm5325_switch
+device		switch_bcm5325
+
 #x#device		ae		# Attansic/Atheros L2 FastEthernet
 #x#device		age		# Attansic/Atheros L1 Gigabit Ethernet
 #x#device		alc		# Atheros AR8131/AR8132 Ethernet
@@ -255,14 +259,16 @@
 device		wlan_ccmp	# 802.11 CCMP support
 device		wlan_tkip	# 802.11 TKIP support
 device		wlan_amrr	# AMRR transmit rate control algorithm
-#x#device		an		# Aironet 4500/4800 802.11 wireless NICs.
+device		wlan_xauth
 device		ath		# Atheros NIC's
 device		ath_pci		# pci/cardbus chip support
 device		ath_hal
+options		ATH_ENABLE_11N
+options		AH_DEBUG
+options		ATH_DEBUG
+options		AH_AR5416_INTERRUPT_MITIGATION
 options 	AH_SUPPORT_AR5416	# enable AR5416 tx/rx descriptors
 device		ath_rate_sample	# SampleRate tx rate control for ath
-#x#device		ral		# Ralink Technology RT2500 wireless NICs.
-#x#device		wi		# WaveLAN/Intersil/Symbol 802.11 wireless NICs.
 
 # Pseudo devices.
 device		loop		# Network loopback
@@ -289,11 +295,13 @@
 device		bpf		# Berkeley packet filter
 
 # USB support
-options 	USB_DEBUG	# enable debug msgs
-#x#device		octusb		# Cavium Octeon on-board USB interface (USB 2.0)
-device		uhci		# UHCI PCI->USB interface
-device		ohci		# OHCI PCI->USB interface
-device		ehci		# EHCI PCI->USB interface (USB 2.0)
+#options 	USB_DEBUG	# enable debug msgs
+#x#
+device		cndotg
+#device		octusb		# Cavium Octeon on-board USB interface (USB 2.0)
+#device		uhci		# UHCI PCI->USB interface
+#device		ohci		# OHCI PCI->USB interface
+#device		ehci		# EHCI PCI->USB interface (USB 2.0)
 device		usb		# USB Bus (required)
 #device		udbp		# USB Double Bulk Pipe devices
 device		uhid		# "Human Interface Devices"
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/mips/conf/OCTEON1.hints
--- a/head/sys/mips/conf/OCTEON1.hints	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/mips/conf/OCTEON1.hints	Tue Dec 06 20:26:16 2011 +0200
@@ -12,12 +12,19 @@
 hint.uart.0.maddr="0x1"
 hint.uart.0.flags="0x1"
 
-hint.switch.0.iface="octe0"
+hint.miibus.0.phymask="0x00000001"
+hint.miibus.0.phy0="switch"
+# miibus1 at switch0
+hint.miibus.2.phymask="0x00000020"
+hint.miibus.2.phy5="plumbphy"
+hint.miibus.3.phymask="0x00000100"
+
+#hint.switch.0.iface="octe0"
 hint.switch.0.driver="bcm5325_switch"
-hint.switch.1.iface="octe1"
-hint.switch.1.driver="bcm5325_switch"
-hint.switch.2.iface="octe2"
-hint.switch.2.driver="bcm5325_switch"
+#hint.switch.1.iface="octe1"
+#hint.switch.1.driver="bcm5325_switch"
+#hint.switch.2.iface="octe2"
+#hint.switch.2.driver="bcm5325_switch"
 
 
 #phys_mapped_flash:
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/mips/conf/PB92
--- a/head/sys/mips/conf/PB92	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/mips/conf/PB92	Tue Dec 06 20:26:16 2011 +0200
@@ -2,7 +2,7 @@
 # PB92 -- Kernel configuration file for FreeBSD/mips for Atheros PB92 reference
 #         board (AR7242)
 #
-# $FreeBSD: head/sys/mips/conf/PB92 221753 2011-05-11 00:52:41Z gonzo $
+# $FreeBSD: head/sys/mips/conf/PB92 227918 2011-11-24 04:21:19Z adrian $
 #
 
 ident		PB92
@@ -31,11 +31,11 @@
 options		ALQ
 
 # Debugging for use in -current
-#options		DEADLKRES
-#options		INVARIANTS
-#options		INVARIANT_SUPPORT
-#options		WITNESS
-#options		WITNESS_SKIPSPIN
+options		DEADLKRES
+options		INVARIANTS
+options		INVARIANT_SUPPORT
+options		WITNESS
+options		WITNESS_SKIPSPIN
 options         FFS                     #Berkeley Fast Filesystem
 #options         SOFTUPDATES             #Enable FFS soft updates support
 #options         UFS_ACL                 #Support for access control lists
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/mips/conf/TP-WN1043ND
--- a/head/sys/mips/conf/TP-WN1043ND	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/mips/conf/TP-WN1043ND	Tue Dec 06 20:26:16 2011 +0200
@@ -1,7 +1,7 @@
 #
 # TP-1043ND -- Kernel configuration file for the TP-Link WR-1043ND
 #
-# $FreeBSD: head/sys/mips/conf/TP-WN1043ND 220295 2011-04-03 13:19:58Z adrian $
+# $FreeBSD: head/sys/mips/conf/TP-WN1043ND 227925 2011-11-24 07:33:41Z adrian $
 #
 
 # Include the default AR913x parameters common to all AR913x SoC users.
@@ -20,11 +20,16 @@
 options		GEOM_PART_BSD
 options		GEOM_PART_MBR
 
-# Just make sure the thing boots off of the first attached SCSI device for now!
-#options		ROOTDEVNAME=\"ufs:da0a\"
-# Or an MDROOT for testing.
-options		MD_ROOT
-options		MD_ROOT_SIZE=5120
+# Enable the uboot environment stuff rather then the
+# redboot stuff.
+options		AR71XX_ENV_UBOOT
+
+# uzip - to boot natively from flash
 device		geom_uzip
 options		GEOM_UZIP
-options		ROOTDEVNAME=\"ufs:/dev/md0.uzip\"
+
+# Used for the static uboot partition map
+device          geom_map
+
+# Boot off of the rootfs, as defined in the geom_map setup.
+options		ROOTDEVNAME=\"ufs:map/rootfs.uzip\"
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/mips/conf/TP-WN1043ND.hints
--- a/head/sys/mips/conf/TP-WN1043ND.hints	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/mips/conf/TP-WN1043ND.hints	Tue Dec 06 20:26:16 2011 +0200
@@ -1,7 +1,7 @@
 #
 # This file adds to the values in AR91XX_BASE.hints.
 #
-# $FreeBSD: head/sys/mips/conf/TP-WN1043ND.hints 220295 2011-04-03 13:19:58Z adrian $
+# $FreeBSD: head/sys/mips/conf/TP-WN1043ND.hints 227938 2011-11-24 15:12:57Z adrian $
 
 # Hard-code the PHY for now, until there's switch phy support.
 hint.arge.0.phymask=0x000c
@@ -17,3 +17,61 @@
 
 # Where the ART is
 hint.ath.0.eepromaddr=0x1fff1000
+
+#
+# Define a slightly custom flash layout.
+
+# The default flash layout:
+#
+# 128k: uboot
+# 1024k: kernel
+# 4096k: rootfs
+# 2816: unknown
+# 64k: board config?
+# 64k: ART
+#
+# from printenv:
+# bootargs=console=ttyS0,115200 root=31:02 rootfstype=jffs2 init=/sbin/init
+#    mtdparts=ar9100-nor0:128k(u-boot),1024k(kernel),4096k(rootfs),64k(art)
+
+# This isn't a lot of space!
+# So:
+# 128k: uboot
+# 2048k: kernel
+# 5888k: rootfs
+# 64k: config
+# 64k: ART
+
+hint.map.0.at="flash/spi0"
+hint.map.0.start=0x00000000
+hint.map.0.end=0x000200000
+hint.map.0.name="uboot"
+hint.map.0.readonly=1
+
+hint.map.1.at="flash/spi0"
+hint.map.1.start=0x00020000
+hint.map.1.end=0x00220000
+hint.map.1.name="kernel"
+hint.map.1.readonly=1
+
+hint.map.2.at="flash/spi0"
+hint.map.2.start=0x00220000
+hint.map.2.end=0x007e0000
+hint.map.2.name="rootfs"
+hint.map.2.readonly=1
+
+hint.map.3.at="flash/spi0"
+hint.map.3.start=0x007e0000
+hint.map.3.end=0x007f0000
+hint.map.3.name="cfg"
+hint.map.3.readonly=0
+
+# This is radio calibration section.  It is (or should be!) unique
+# for each board, to take into account thermal and electrical differences
+# as well as the regulatory compliance data.
+#
+hint.map.4.at="flash/spi0"
+hint.map.4.start=0x007f0000
+hint.map.4.end=0x00800000
+hint.map.4.name="art"
+hint.map.4.readonly=1
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/mips/conf/XLPN32
--- a/head/sys/mips/conf/XLPN32	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/mips/conf/XLPN32	Tue Dec 06 20:26:16 2011 +0200
@@ -15,7 +15,7 @@
 # If you are in doubt as to the purpose or necessity of a line, check first 
 # in NOTES.
 #
-# $FreeBSD: head/sys/mips/conf/XLPN32 227663 2011-11-18 11:18:59Z jchandra $
+# $FreeBSD: head/sys/mips/conf/XLPN32 228273 2011-12-05 03:18:40Z jchandra $
 
 machine 	mips mipsn32eb
 ident           XLPN32
@@ -26,5 +26,11 @@
 
 include		"std.XLP"
 
+nooption 	DDB
+nooption 	KDB
+nooption 	GDB
+nooption 	BREAK_TO_DEBUGGER
+nooption 	ALT_BREAK_TO_DEBUGGER
+
 makeoptions	TRAMPLOADADDR=0xffffffff85000000
 makeoptions	TRAMP_ARCH_FLAGS="-mabi=64 -march=mips64"
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/mips/mips/bus_space_generic.c
--- a/head/sys/mips/mips/bus_space_generic.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/mips/mips/bus_space_generic.c	Tue Dec 06 20:26:16 2011 +0200
@@ -109,7 +109,7 @@
 	generic_bs_r_1,
 	generic_bs_r_2,
 	generic_bs_r_4,
-	NULL,
+	generic_bs_r_8,
 
 	/* read multiple */
 	generic_bs_rm_1,
@@ -127,7 +127,7 @@
 	generic_bs_w_1,
 	generic_bs_w_2,
 	generic_bs_w_4,
-	NULL,
+	generic_bs_w_8,
 
 	/* write multiple */
 	generic_bs_wm_1,
@@ -203,24 +203,30 @@
 #define rd8(a) cvmx_read64_uint8(a)
 #define rd16(a) cvmx_read64_uint16(a)
 #define rd32(a) cvmx_read64_uint32(a)
+#define rd64(a) cvmx_read64_uint64(a)
 #define wr8(a, v) cvmx_write64_uint8(a, v)
 #define wr16(a, v) cvmx_write64_uint16(a, v)
 #define wr32(a, v) cvmx_write64_uint32(a, v)
+#define wr64(a, v) cvmx_write64_uint64(a, v)
 #elif defined(CPU_SB1) && _BYTE_ORDER == _BIG_ENDIAN
 #include <mips/sibyte/sb_bus_space.h>
 #define rd8(a) sb_big_endian_read8(a)
 #define rd16(a) sb_big_endian_read16(a)
 #define rd32(a) sb_big_endian_read32(a)
+#define rd64(a) NULL
 #define wr8(a, v) sb_big_endian_write8(a, v)
 #define wr16(a, v) sb_big_endian_write16(a, v)
 #define wr32(a, v) sb_big_endian_write32(a, v)
+#define wr64(a, v) NULL
 #else
 #define rd8(a) readb(a)
 #define rd16(a) readw(a)
 #define rd32(a) readl(a)
+#define rd64(a) readd(a)
 #define wr8(a, v) writeb(a, v)
 #define wr16(a, v) writew(a, v)
 #define wr32(a, v) writel(a, v)
+#define wr64(a, v) writed(a, v)
 #endif
 
 /* generic bus_space tag */
@@ -279,6 +285,13 @@
 	return (rd32(handle + offset));
 }
 
+uint64_t
+generic_bs_r_8(void *t, bus_space_handle_t handle,
+    bus_size_t offset)
+{
+
+	return (uint64_t)(rd64(handle + offset));
+}
 
 void
 generic_bs_rm_1(void *t, bus_space_handle_t bsh,
@@ -379,6 +392,14 @@
 	wr32(bsh + offset, value);
 }
 
+void
+generic_bs_w_8(void *t, bus_space_handle_t bsh,
+    bus_size_t offset, uint64_t value)
+{
+
+	wr64(bsh + offset, value);
+}
+
 /*
  * Write `count' 1, 2, 4, or 8 byte quantities from the buffer
  * provided to bus space described by tag/handle/offset.
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/mips/mips/db_trace.c
--- a/head/sys/mips/mips/db_trace.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/mips/mips/db_trace.c	Tue Dec 06 20:26:16 2011 +0200
@@ -6,7 +6,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/sys/mips/mips/db_trace.c 228091 2011-11-28 19:48:04Z gonzo $");
 
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -30,7 +30,7 @@
 
 /*
  * A function using a stack frame has the following instruction as the first
- * one: addiu sp,sp,-<frame_size>
+ * one: [d]addiu sp,sp,-<frame_size>
  *
  * We make use of this to detect starting address of a function. This works
  * better than using 'j ra' instruction to signify end of the previous
@@ -39,7 +39,8 @@
  *
  * XXX the abi does not require that the addiu instruction be the first one.
  */
-#define	MIPS_START_OF_FUNCTION(ins)	(((ins) & 0xffff8000) == 0x27bd8000)
+#define	MIPS_START_OF_FUNCTION(ins)	((((ins) & 0xffff8000) == 0x27bd8000) \
+	|| (((ins) & 0xffff8000) == 0x67bd8000))
 
 /*
  * MIPS ABI 3.0 requires that all functions return using the 'j ra' instruction
@@ -329,6 +330,8 @@
 
 		case OP_ADDI:
 		case OP_ADDIU:
+		case OP_DADDI:
+		case OP_DADDIU:
 			/* look for stack pointer adjustment */
 			if (i.IType.rs != 29 || i.IType.rt != 29)
 				break;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/mips/nlm/hal/cpucontrol.h
--- a/head/sys/mips/nlm/hal/cpucontrol.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/mips/nlm/hal/cpucontrol.h	Tue Dec 06 20:26:16 2011 +0200
@@ -26,7 +26,7 @@
  * THE POSSIBILITY OF SUCH DAMAGE.
  *
  * NETLOGIC_BSD
- * $FreeBSD: head/sys/mips/nlm/hal/cpucontrol.h 227722 2011-11-19 14:06:15Z jchandra $
+ * $FreeBSD: head/sys/mips/nlm/hal/cpucontrol.h 228271 2011-12-05 02:56:08Z jchandra $
  */
 
 #ifndef __NLM_HAL_CPUCONTROL_H__
@@ -44,6 +44,8 @@
 #define	CPU_BLOCKID_MAP		10
 
 #define	LSU_DEFEATURE		0x304
+#define	LSU_DEBUG_ADDR		0x305
+#define	LSU_DEBUG_DATA0		0x306
 #define	LSU_CERRLOG_REGID	0x09
 #define	SCHED_DEFEATURE		0x700
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/mips/nlm/xlp_machdep.c
--- a/head/sys/mips/nlm/xlp_machdep.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/mips/nlm/xlp_machdep.c	Tue Dec 06 20:26:16 2011 +0200
@@ -28,7 +28,7 @@
  * NETLOGIC_BSD */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/mips/nlm/xlp_machdep.c 227783 2011-11-21 08:12:36Z jchandra $");
+__FBSDID("$FreeBSD: head/sys/mips/nlm/xlp_machdep.c 228272 2011-12-05 03:10:01Z jchandra $");
 
 #include "opt_ddb.h"
 #include "opt_platform.h"
@@ -278,7 +278,7 @@
 	phandle_t chosen;
 	ihandle_t mask;
 
-	dtbp = (void *)arg;
+	dtbp = (void *)(intptr_t)arg;
 #if defined(FDT_DTB_STATIC)
 	/*
 	 * In case the device tree blob was not passed as argument try
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/modules/Makefile
--- a/head/sys/modules/Makefile	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/modules/Makefile	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-# $FreeBSD: head/sys/modules/Makefile 227662 2011-11-18 11:10:14Z philip $
+# $FreeBSD: head/sys/modules/Makefile 227982 2011-11-25 19:29:21Z marius $
 
 .include <bsd.own.mk>
 
@@ -22,7 +22,6 @@
 	alc \
 	ale \
 	alq \
-	${_amd} \
 	${_amdsbwd} \
 	${_amdtemp} \
 	amr \
@@ -413,7 +412,6 @@
 _3dfx_linux=	3dfx_linux
 _agp=		agp
 _aic=		aic
-_amd=		amd
 _an=		an
 _aout=		aout
 _apm=		apm
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/modules/acpi/acpi/Makefile
--- a/head/sys/modules/acpi/acpi/Makefile	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/modules/acpi/acpi/Makefile	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-# $FreeBSD: head/sys/modules/acpi/acpi/Makefile 220663 2011-04-15 18:34:27Z jkim $
+# $FreeBSD: head/sys/modules/acpi/acpi/Makefile 228110 2011-11-28 23:36:48Z jkim $
 
 .if !defined(FORCE_BUILD)
 .error "The ACPI module is deprecated, set FORCE_BUILD to force it"
@@ -35,7 +35,7 @@
 SRCS+=	dbcmds.c dbdisply.c dbexec.c dbfileio.c dbhistry.c dbinput.c dbmethod.c
 SRCS+=	dbnames.c dbstats.c dbutils.c dbxface.c
 SRCS+=	dmbuffer.c dmnames.c dmopcode.c dmobject.c dmresrc.c dmresrcl.c
-SRCS+=	dmresrcs.c dmutils.c dmwalk.c
+SRCS+=	dmresrcl2.c dmresrcs.c dmutils.c dmwalk.c
 SRCS+=	dsargs.c dscontrol.c dsfield.c dsinit.c dsmethod.c dsmthdat.c
 SRCS+=	dsobject.c dsopcode.c dsutils.c dswexec.c dswload.c dswload2.c
 SRCS+=	dswscope.c dswstate.c
@@ -53,11 +53,12 @@
 SRCS+=	psargs.c psloop.c psopcode.c psparse.c psscope.c pstree.c psutils.c
 SRCS+=	pswalk.c psxface.c
 SRCS+=	rsaddr.c rscalc.c rscreate.c rsdump.c rsinfo.c rsio.c rsirq.c rslist.c
-SRCS+=	rsmemory.c rsmisc.c rsutils.c rsxface.c
+SRCS+=	rsmemory.c rsmisc.c rsserial.c rsutils.c rsxface.c
 SRCS+=	tbfadt.c tbfind.c tbinstal.c tbutils.c tbxface.c tbxfroot.c
 SRCS+=	utalloc.c utcache.c utcopy.c utdebug.c utdecode.c utdelete.c uteval.c
 SRCS+=	utglobal.c utids.c utinit.c utlock.c utmath.c utmisc.c utmutex.c
 SRCS+=	utobject.c utosi.c utresrc.c utstate.c utxface.c utxferror.c
+#SRCS+=	utxfmutex.c
 
 # OSPM layer and core hardware drivers
 SRCS+=	acpi.c acpi_button.c acpi_isab.c acpi_package.c acpi_pci.c acpi_pcib.c
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/modules/amd/Makefile
--- a/head/sys/modules/amd/Makefile	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,10 +0,0 @@
-# $FreeBSD$
-
-.PATH: ${.CURDIR}/../../dev/amd
-
-KMOD=	amd
-SRCS=	amd.c
-SRCS+=	opt_scsi.h opt_cam.h
-SRCS+=	device_if.h bus_if.h pci_if.h
-
-.include <bsd.kmod.mk>
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/modules/cam/Makefile
--- a/head/sys/modules/cam/Makefile	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/modules/cam/Makefile	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-# $FreeBSD: head/sys/modules/cam/Makefile 221071 2011-04-26 17:01:49Z mav $
+# $FreeBSD: head/sys/modules/cam/Makefile 228026 2011-11-27 16:17:17Z marius $
 
 S=	${.CURDIR}/../..
 
@@ -16,8 +16,11 @@
 SRCS+=	opt_sa.h
 SRCS+=	opt_ses.h
 SRCS+=	device_if.h bus_if.h vnode_if.h
-SRCS+=	cam.c cam_periph.c cam_queue.c
-SRCS+=	cam_sim.c cam_xpt.c
+SRCS+=	cam.c
+.if exists($S/${MACHINE}/${MACHINE}/cam_machdep.c)
+SRCS+=	cam_machdep.c
+.endif
+SRCS+=	cam_periph.c cam_queue.c cam_sim.c cam_xpt.c
 SRCS+=	scsi_all.c scsi_cd.c scsi_ch.c
 SRCS+=	scsi_da.c
 SRCS+=	scsi_pass.c
@@ -32,7 +35,7 @@
 SRCS+=	ata_xpt.c
 SRCS+=	ata_da.c
 .if exists($S/${MACHINE}/${MACHINE}/ata_machdep.c)
-SRCS+=  ata_machdep.c
+SRCS+=	ata_machdep.c
 .endif
 SRCS+=	ata_pmp.c
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/net/bpf.c
--- a/head/sys/net/bpf.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/net/bpf.c	Tue Dec 06 20:26:16 2011 +0200
@@ -1,17 +1,12 @@
 /*-
  * Copyright (c) 1990, 1991, 1993
- *	The Regents of the University of California.
- * Copyright (c) 2011 The FreeBSD Foundation.
- * All rights reserved.
+ *	The Regents of the University of California.  All rights reserved.
  *
  * This code is derived from the Stanford/CMU enet packet filter,
  * (net/enet.c) distributed as part of 4.3BSD, and code contributed
  * to Berkeley by Steven McCanne and Van Jacobson both of Lawrence
  * Berkeley Laboratory.
  *
- * Portions of this software were developed by Julien Ridoux at the University
- * of Melbourne 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:
@@ -40,11 +35,10 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/net/bpf.c 227778 2011-11-21 04:17:24Z lstewart $");
+__FBSDID("$FreeBSD: head/sys/net/bpf.c 228132 2011-11-29 12:55:26Z lstewart $");
 
 #include "opt_bpf.h"
 #include "opt_compat.h"
-#include "opt_ffclock.h"
 #include "opt_netgraph.h"
 
 #include <sys/types.h>
@@ -61,9 +55,6 @@
 #include <sys/signalvar.h>
 #include <sys/filio.h>
 #include <sys/sockio.h>
-#ifdef FFCLOCK
-#include <sys/timeffc.h>
-#endif
 #include <sys/ttycom.h>
 #include <sys/uio.h>
 
@@ -99,13 +90,8 @@
 
 #define PRINET  26			/* interruptible */
 
-#ifdef FFCLOCK
-#define SIZEOF_BPF_HDR(type)	\
-    (offsetof(type, ffcount_stamp) + sizeof(((type *)0)->ffcount_stamp))
-#else
 #define	SIZEOF_BPF_HDR(type)	\
     (offsetof(type, bh_hdrlen) + sizeof(((type *)0)->bh_hdrlen))
-#endif
 
 #ifdef COMPAT_FREEBSD32
 #include <sys/mount.h>
@@ -125,9 +111,6 @@
 	uint32_t	bh_datalen;	/* original length of packet */
 	uint16_t	bh_hdrlen;	/* length of bpf header (this struct
 					   plus alignment padding) */
-#ifdef FFCLOCK
-	ffcounter	ffcount_stamp;	/* ffcounter timestamp of packet */
-#endif
 };
 #endif
 
@@ -168,16 +151,9 @@
 static void	bpf_timed_out(void *);
 static __inline void
 		bpf_wakeup(struct bpf_d *);
-#ifdef FFCLOCK
-static void	catchpacket(struct bpf_d *, u_char *, unsigned int,
-		    unsigned int, void (*)(struct bpf_d *, caddr_t,
-		    unsigned int, void *, unsigned int), struct bintime *,
-		    ffcounter *);
-#else
 static void	catchpacket(struct bpf_d *, u_char *, u_int, u_int,
 		    void (*)(struct bpf_d *, caddr_t, u_int, void *, u_int),
 		    struct bintime *);
-#endif
 static void	reset_d(struct bpf_d *);
 static int	 bpf_setf(struct bpf_d *, struct bpf_program *, u_long cmd);
 static int	bpf_getdltlist(struct bpf_d *, struct bpf_dltlist *);
@@ -196,12 +172,6 @@
     &bpf_zerocopy_enable, 0, "Enable new zero-copy BPF buffer sessions");
 static SYSCTL_NODE(_net_bpf, OID_AUTO, stats, CTLFLAG_MPSAFE | CTLFLAG_RW,
     bpf_stats_sysctl, "bpf statistics portal");
-#ifdef FFCLOCK
-static int bpf_ffclock_tstamp = 0;
-SYSCTL_INT(_net_bpf, OID_AUTO, ffclock_tstamp, CTLFLAG_RW,
-    &bpf_ffclock_tstamp, 0,
-    "Set BPF to timestamp using Feed-Forward clock by default");
-#endif
 
 static	d_open_t	bpfopen;
 static	d_read_t	bpfread;
@@ -728,15 +698,6 @@
 	callout_init_mtx(&d->bd_callout, &d->bd_mtx, 0);
 	knlist_init_mtx(&d->bd_sel.si_note, &d->bd_mtx);
 
-#ifdef FFCLOCK
-	/*
-	 * Set the timestamping mode for this device, i.e. which clock is used.
-	 * The default option is to use the feedback/ntpd system clock.
-	 */
-	if (bpf_ffclock_tstamp)
-		d->bd_tstamp = d->bd_tstamp | BPF_T_FFCLOCK;
-#endif
-
 	return (0);
 }
 
@@ -1815,13 +1776,8 @@
 	return (BPF_TSTAMP_NORMAL);
 }
 
-#ifdef FFCLOCK
-static int
-bpf_gettime(struct bintime *bt, ffcounter *ffcount, int tstype, struct mbuf *m)
-#else
 static int
 bpf_gettime(struct bintime *bt, int tstype, struct mbuf *m)
-#endif
 {
 	struct m_tag *tag;
 	int quality;
@@ -1837,31 +1793,11 @@
 			return (BPF_TSTAMP_EXTERN);
 		}
 	}
-	if (quality == BPF_TSTAMP_NORMAL) {
-#ifdef FFCLOCK
-		if ((tstype & BPF_T_FFCLOCK) == 0) {
-			ffclock_read_counter(ffcount);
-#endif
-			binuptime(bt);
-#ifdef FFCLOCK
-		} else {
-			if ((tstype & BPF_T_MONOTONIC) == 0)
-				ffclock_abstime(ffcount, bt, NULL,
-				    (FFCLOCK_LERP | FFCLOCK_LEAPSEC));
-			else
-				ffclock_abstime(ffcount, bt, NULL,
-				    (FFCLOCK_LERP | FFCLOCK_UPTIME));
-		}
-#endif
-	} else {
-#ifdef FFCLOCK
-		if ((tstype & BPF_T_FFCLOCK) == BPF_T_FFCLOCK)
-			ffclock_abstime(ffcount, bt, NULL,
-			    (FFCLOCK_LERP | FFCLOCK_LEAPSEC | FFCLOCK_FAST));
-		else
-#endif
-			getbinuptime(bt);
-	}
+	if (quality == BPF_TSTAMP_NORMAL)
+		binuptime(bt);
+	else
+		getbinuptime(bt);
+
 	return (quality);
 }
 
@@ -1881,9 +1817,6 @@
 #endif
 	u_int slen;
 	int gottime;
-#ifdef FFCLOCK
-	ffcounter ffcount;
-#endif
 
 	gottime = BPF_TSTAMP_NONE;
 	BPFIF_LOCK(bp);
@@ -1905,24 +1838,13 @@
 		slen = bpf_filter(d->bd_rfilter, pkt, pktlen, pktlen);
 		if (slen != 0) {
 			d->bd_fcount++;
-			if (gottime < bpf_ts_quality(d->bd_tstamp)) {
-#ifdef FFCLOCK
-				gottime = bpf_gettime(&bt, &ffcount,
-				    d->bd_tstamp, NULL);
-#else
+			if (gottime < bpf_ts_quality(d->bd_tstamp))
 				gottime = bpf_gettime(&bt, d->bd_tstamp, NULL);
-#endif
-			}
 #ifdef MAC
 			if (mac_bpfdesc_check_receive(d, bp->bif_ifp) == 0)
 #endif
-#ifdef FFCLOCK
-				catchpacket(d, pkt, pktlen, slen,
-				    bpf_append_bytes, &bt, &ffcount);
-#else
 				catchpacket(d, pkt, pktlen, slen,
 				    bpf_append_bytes, &bt);
-#endif
 		}
 		BPFD_UNLOCK(d);
 	}
@@ -1946,9 +1868,6 @@
 #endif
 	u_int pktlen, slen;
 	int gottime;
-#ifdef FFCLOCK
-	ffcounter ffcount;
-#endif
 
 	/* Skip outgoing duplicate packets. */
 	if ((m->m_flags & M_PROMISC) != 0 && m->m_pkthdr.rcvif == NULL) {
@@ -1976,24 +1895,12 @@
 		if (slen != 0) {
 			d->bd_fcount++;
 			if (gottime < bpf_ts_quality(d->bd_tstamp))
-			{
-#ifdef FFCLOCK
-				gottime = bpf_gettime(&bt, &ffcount,
-				    d->bd_tstamp, m);
-#else
 				gottime = bpf_gettime(&bt, d->bd_tstamp, m);
-#endif
-			}
 #ifdef MAC
 			if (mac_bpfdesc_check_receive(d, bp->bif_ifp) == 0)
 #endif
-#ifdef FFCLOCK
-				catchpacket(d, (u_char *)m, pktlen, slen,
-				    bpf_append_mbuf, &bt, &ffcount);
-#else
 				catchpacket(d, (u_char *)m, pktlen, slen,
 				    bpf_append_mbuf, &bt);
-#endif
 		}
 		BPFD_UNLOCK(d);
 	}
@@ -2012,9 +1919,6 @@
 	struct bpf_d *d;
 	u_int pktlen, slen;
 	int gottime;
-#ifdef FFCLOCK
-	ffcounter ffcount;
-#endif
 
 	/* Skip outgoing duplicate packets. */
 	if ((m->m_flags & M_PROMISC) != 0 && m->m_pkthdr.rcvif == NULL) {
@@ -2044,24 +1948,12 @@
 		if (slen != 0) {
 			d->bd_fcount++;
 			if (gottime < bpf_ts_quality(d->bd_tstamp))
-			{
-#ifdef FFCLOCK
-				gottime = bpf_gettime(&bt, &ffcount,
-				    d->bd_tstamp, m);
-#else
 				gottime = bpf_gettime(&bt, d->bd_tstamp, m);
-#endif
-			}
 #ifdef MAC
 			if (mac_bpfdesc_check_receive(d, bp->bif_ifp) == 0)
 #endif
-#ifdef FFCLOCK
-				catchpacket(d, (u_char *)m, pktlen, slen,
-				    bpf_append_mbuf, &bt, &ffcount);
-#else
 				catchpacket(d, (u_char *)&mb, pktlen, slen,
 				    bpf_append_mbuf, &bt);
-#endif
 		}
 		BPFD_UNLOCK(d);
 	}
@@ -2110,17 +2002,11 @@
 	struct timeval tsm;
 	struct timespec tsn;
 
-#ifdef FFCLOCK
-	if ((tstype & BPF_T_FFCLOCK) == 0) {
-#endif
-		if ((tstype & BPF_T_MONOTONIC) == 0) {
-			bt2 = *bt;
-			bintime_add(&bt2, &boottimebin);
-			bt = &bt2;
-		}
-#ifdef FFCLOCK
+	if ((tstype & BPF_T_MONOTONIC) == 0) {
+		bt2 = *bt;
+		bintime_add(&bt2, &boottimebin);
+		bt = &bt2;
 	}
-#endif
 	switch (BPF_T_FORMAT(tstype)) {
 	case BPF_T_MICROTIME:
 		bintime2timeval(bt, &tsm);
@@ -2146,17 +2032,10 @@
  * bpf_append_mbuf is passed in to copy mbuf chains.  In the latter case,
  * pkt is really an mbuf.
  */
-#ifdef FFCLOCK
-static void
-catchpacket(struct bpf_d *d, u_char *pkt, unsigned int pktlen,
-    unsigned int snaplen, void (*cpfn)(struct bpf_d *, caddr_t, unsigned int,
-    void *, unsigned int), struct bintime *bt, ffcounter *ffcount)
-#else
 static void
 catchpacket(struct bpf_d *d, u_char *pkt, u_int pktlen, u_int snaplen,
     void (*cpfn)(struct bpf_d *, caddr_t, u_int, void *, u_int),
     struct bintime *bt)
-#endif
 {
 	struct bpf_xhdr hdr;
 #ifndef BURN_BRIDGES
@@ -2244,9 +2123,6 @@
 		if (d->bd_compat32) {
 			bzero(&hdr32_old, sizeof(hdr32_old));
 			if (do_timestamp) {
-#ifdef FFCLOCK
-				hdr32_old.ffcount_stamp = *ffcount;
-#endif
 				hdr32_old.bh_tstamp.tv_sec = ts.bt_sec;
 				hdr32_old.bh_tstamp.tv_usec = ts.bt_frac;
 			}
@@ -2260,9 +2136,6 @@
 #endif
 		bzero(&hdr_old, sizeof(hdr_old));
 		if (do_timestamp) {
-#ifdef FFCLOCK
-			hdr_old.ffcount_stamp = *ffcount;
-#endif
 			hdr_old.bh_tstamp.tv_sec = ts.bt_sec;
 			hdr_old.bh_tstamp.tv_usec = ts.bt_frac;
 		}
@@ -2281,12 +2154,7 @@
 	 */
 	bzero(&hdr, sizeof(hdr));
 	if (do_timestamp)
-	{
-#ifdef FFCLOCK
-		hdr.ffcount_stamp = *ffcount;
-#endif
 		bpf_bintime2ts(bt, &hdr.bh_tstamp, tstype);
-	}
 	hdr.bh_datalen = pktlen;
 	hdr.bh_hdrlen = hdrlen;
 	hdr.bh_caplen = caplen;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/net/bpf.h
--- a/head/sys/net/bpf.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/net/bpf.h	Tue Dec 06 20:26:16 2011 +0200
@@ -1,17 +1,12 @@
 /*-
  * Copyright (c) 1990, 1991, 1993
- *	The Regents of the University of California.
- * Copyright (c) 2011 The FreeBSD Foundation
- * All rights reserved.
+ *	The Regents of the University of California.  All rights reserved.
  *
  * This code is derived from the Stanford/CMU enet packet filter,
  * (net/enet.c) distributed as part of 4.3BSD, and code contributed
  * to Berkeley by Steven McCanne and Van Jacobson both of Lawrence
  * Berkeley Laboratory.
  *
- * Portions of this software were developed by Julien Ridoux at the University
- * of Melbourne 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:
@@ -39,7 +34,7 @@
  *      @(#)bpf.h	8.1 (Berkeley) 6/10/93
  *	@(#)bpf.h	1.34 (LBL)     6/16/96
  *
- * $FreeBSD: head/sys/net/bpf.h 227778 2011-11-21 04:17:24Z lstewart $
+ * $FreeBSD: head/sys/net/bpf.h 228132 2011-11-29 12:55:26Z lstewart $
  */
 
 #ifndef _NET_BPF_H_
@@ -175,21 +170,11 @@
 #define	BPF_T_MONOTONIC		0x0200
 #define	BPF_T_MONOTONIC_FAST	(BPF_T_FAST | BPF_T_MONOTONIC)
 #define	BPF_T_FLAG_MASK		0x0300
-#ifdef FFCLOCK
-#define	BPF_T_FFCLOCK		0x8000
-#define	BPF_T_CLOCK_MASK	0x8000
-#endif
 #define	BPF_T_FORMAT(t)		((t) & BPF_T_FORMAT_MASK)
 #define	BPF_T_FLAG(t)		((t) & BPF_T_FLAG_MASK)
-#ifdef FFCLOCK
-#define	BPF_T_VALID(t)						\
-    ((t) == BPF_T_NONE || (BPF_T_FORMAT(t) != BPF_T_NONE &&	\
-    ((t) & ~(BPF_T_FORMAT_MASK | BPF_T_FLAG_MASK | BPF_T_CLOCK_MASK)) == 0))
-#else
 #define	BPF_T_VALID(t)						\
     ((t) == BPF_T_NONE || (BPF_T_FORMAT(t) != BPF_T_NONE &&	\
     ((t) & ~(BPF_T_FORMAT_MASK | BPF_T_FLAG_MASK)) == 0))
-#endif
 
 #define	BPF_T_MICROTIME_FAST		(BPF_T_MICROTIME | BPF_T_FAST)
 #define	BPF_T_NANOTIME_FAST		(BPF_T_NANOTIME | BPF_T_FAST)
@@ -214,9 +199,6 @@
 	bpf_u_int32	bh_datalen;	/* original length of packet */
 	u_short		bh_hdrlen;	/* length of bpf header (this struct
 					   plus alignment padding) */
-#ifdef FFCLOCK
-	ffcounter	ffcount_stamp;	/* feed-forward counter timestamp */
-#endif
 };
 /* Obsolete */
 struct bpf_hdr {
@@ -225,9 +207,6 @@
 	bpf_u_int32	bh_datalen;	/* original length of packet */
 	u_short		bh_hdrlen;	/* length of bpf header (this struct
 					   plus alignment padding) */
-#ifdef FFCLOCK
-	ffcounter	ffcount_stamp;	/* feed-forward counter timestamp */
-#endif
 };
 #ifdef _KERNEL
 #define	MTAG_BPF		0x627066
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/net/if_clone.c
--- a/head/sys/net/if_clone.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/net/if_clone.c	Tue Dec 06 20:26:16 2011 +0200
@@ -27,7 +27,7 @@
  * SUCH DAMAGE.
  *
  *	@(#)if.c	8.5 (Berkeley) 1/9/95
- * $FreeBSD$
+ * $FreeBSD: head/sys/net/if_clone.c 228071 2011-11-28 14:44:59Z glebius $
  */
 
 #include <sys/param.h>
@@ -282,33 +282,34 @@
 /*
  * Register a network interface cloner.
  */
-void
+int
 if_clone_attach(struct if_clone *ifc)
 {
-	int len, maxclone;
+	struct if_clone *ifc1;
 
-	/*
-	 * Compute bitmap size and allocate it.
-	 */
-	maxclone = ifc->ifc_maxunit + 1;
-	len = maxclone >> 3;
-	if ((len << 3) < maxclone)
-		len++;
-	ifc->ifc_units = malloc(len, M_CLONE, M_WAITOK | M_ZERO);
-	ifc->ifc_bmlen = len;
+	KASSERT(ifc->ifc_name != NULL, ("%s: no name\n", __func__));
+
 	IF_CLONE_LOCK_INIT(ifc);
 	IF_CLONE_ADDREF(ifc);
+	ifc->ifc_unrhdr = new_unrhdr(0, ifc->ifc_maxunit, &ifc->ifc_mtx);
+	LIST_INIT(&ifc->ifc_iflist);
 
 	IF_CLONERS_LOCK();
+	LIST_FOREACH(ifc1, &V_if_cloners, ifc_list)
+		if (strcmp(ifc->ifc_name, ifc1->ifc_name) == 0) {
+			IF_CLONERS_UNLOCK();
+			IF_CLONE_REMREF(ifc);
+			return (EEXIST);
+		}
 	LIST_INSERT_HEAD(&V_if_cloners, ifc, ifc_list);
 	V_if_cloners_count++;
 	IF_CLONERS_UNLOCK();
 
-	LIST_INIT(&ifc->ifc_iflist);
-
 	if (ifc->ifc_attach != NULL)
 		(*ifc->ifc_attach)(ifc);
 	EVENTHANDLER_INVOKE(if_clone_event, ifc);
+
+	return (0);
 }
 
 /*
@@ -338,16 +339,12 @@
 static void
 if_clone_free(struct if_clone *ifc)
 {
-	for (int bytoff = 0; bytoff < ifc->ifc_bmlen; bytoff++) {
-		KASSERT(ifc->ifc_units[bytoff] == 0x00,
-		    ("ifc_units[%d] is not empty", bytoff));
-	}
 
 	KASSERT(LIST_EMPTY(&ifc->ifc_iflist),
 	    ("%s: ifc_iflist not empty", __func__));
 
 	IF_CLONE_LOCK_DESTROY(ifc);
-	free(ifc->ifc_units, M_CLONE);
+	delete_unrhdr(ifc->ifc_unrhdr);
 }
 
 /*
@@ -441,73 +438,40 @@
 int
 ifc_alloc_unit(struct if_clone *ifc, int *unit)
 {
-	int wildcard, bytoff, bitoff;
-	int err = 0;
+	char name[IFNAMSIZ];
+	int wildcard;
 
-	IF_CLONE_LOCK(ifc);
-
-	bytoff = bitoff = 0;
 	wildcard = (*unit < 0);
-	/*
-	 * Find a free unit if none was given.
-	 */
+retry:
 	if (wildcard) {
-		while ((bytoff < ifc->ifc_bmlen)
-		    && (ifc->ifc_units[bytoff] == 0xff))
-			bytoff++;
-		if (bytoff >= ifc->ifc_bmlen) {
-			err = ENOSPC;
-			goto done;
-		}
-		while ((ifc->ifc_units[bytoff] & (1 << bitoff)) != 0)
-			bitoff++;
-		*unit = (bytoff << 3) + bitoff;
+		*unit = alloc_unr(ifc->ifc_unrhdr);
+		if (*unit == -1)
+			return (ENOSPC);
+	} else {
+		*unit = alloc_unr_specific(ifc->ifc_unrhdr, *unit);
+		if (*unit == -1)
+			return (EEXIST);
 	}
 
-	if (*unit > ifc->ifc_maxunit) {
-		err = ENOSPC;
-		goto done;
+	snprintf(name, IFNAMSIZ, "%s%d", ifc->ifc_name, *unit);
+	if (ifunit(name) != NULL) {
+		if (wildcard)
+			goto retry;	/* XXXGL: yep, it's a unit leak */
+		else
+			return (EEXIST);
 	}
 
-	if (!wildcard) {
-		bytoff = *unit >> 3;
-		bitoff = *unit - (bytoff << 3);
-	}
+	IF_CLONE_ADDREF(ifc);
 
-	if((ifc->ifc_units[bytoff] & (1 << bitoff)) != 0) {
-		err = EEXIST;
-		goto done;
-	}
-	/*
-	 * Allocate the unit in the bitmap.
-	 */
-	KASSERT((ifc->ifc_units[bytoff] & (1 << bitoff)) == 0,
-	    ("%s: bit is already set", __func__));
-	ifc->ifc_units[bytoff] |= (1 << bitoff);
-	IF_CLONE_ADDREF_LOCKED(ifc);
-
-done:
-	IF_CLONE_UNLOCK(ifc);
-	return (err);
+	return (0);
 }
 
 void
 ifc_free_unit(struct if_clone *ifc, int unit)
 {
-	int bytoff, bitoff;
 
-
-	/*
-	 * Compute offset in the bitmap and deallocate the unit.
-	 */
-	bytoff = unit >> 3;
-	bitoff = unit - (bytoff << 3);
-
-	IF_CLONE_LOCK(ifc);
-	KASSERT((ifc->ifc_units[bytoff] & (1 << bitoff)) != 0,
-	    ("%s: bit is already cleared", __func__));
-	ifc->ifc_units[bytoff] &= ~(1 << bitoff);
-	IF_CLONE_REMREF_LOCKED(ifc);	/* releases lock */
+	free_unr(ifc->ifc_unrhdr, unit);
+	IF_CLONE_REMREF(ifc);
 }
 
 void
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/net/if_clone.h
--- a/head/sys/net/if_clone.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/net/if_clone.h	Tue Dec 06 20:26:16 2011 +0200
@@ -27,7 +27,7 @@
  * SUCH DAMAGE.
  *
  *	From: @(#)if.h	8.1 (Berkeley) 6/10/93
- * $FreeBSD$
+ * $FreeBSD: head/sys/net/if_clone.h 228071 2011-11-28 14:44:59Z glebius $
  */
 
 #ifndef	_NET_IF_CLONE_H_
@@ -37,7 +37,15 @@
 
 #define IFC_CLONE_INITIALIZER(name, data, maxunit,			\
     attach, match, create, destroy)					\
-    { { 0 }, name, maxunit, NULL, 0, data, attach, match, create, destroy }
+    {									\
+	.ifc_name = name,						\
+	.ifc_maxunit = maxunit,						\
+	.ifc_data = data,						\
+	.ifc_attach = attach,						\
+	.ifc_match = match,						\
+	.ifc_create = create,						\
+	.ifc_destroy = destroy,						\
+    }
 
 /*
  * Structure describing a `cloning' interface.
@@ -52,10 +60,7 @@
 	LIST_ENTRY(if_clone) ifc_list;	/* (e) On list of cloners */
 	const char *ifc_name;		/* (c) Name of device, e.g. `gif' */
 	int ifc_maxunit;		/* (c) Maximum unit number */
-	unsigned char *ifc_units;	/* (i) Bitmap to handle units. */
-					/*     Considered private, access */
-					/*     via ifc_(alloc|free)_unit(). */
-	int ifc_bmlen;			/* (c) Bitmap length. */
+	struct unrhdr *ifc_unrhdr;	/* (c) alloc_unr(9) header */
 	void *ifc_data;			/* (*) Data for ifc_* functions. */
 
 	/* (c) Driver specific cloning functions.  Called with no locks held. */
@@ -65,12 +70,12 @@
 	int	(*ifc_destroy)(struct if_clone *, struct ifnet *);
 
 	long ifc_refcnt;		/* (i) Refrence count. */
-	struct mtx ifc_mtx;		/* Muted to protect members. */
+	struct mtx ifc_mtx;		/* Mutex to protect members. */
 	LIST_HEAD(, ifnet) ifc_iflist;	/* (i) List of cloned interfaces */
 };
 
 void	if_clone_init(void);
-void	if_clone_attach(struct if_clone *);
+int	if_clone_attach(struct if_clone *);
 void	if_clone_detach(struct if_clone *);
 void	vnet_if_clone_init(void);
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/net/if_vlan.c
--- a/head/sys/net/if_vlan.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/net/if_vlan.c	Tue Dec 06 20:26:16 2011 +0200
@@ -34,13 +34,12 @@
  * we need to pretend to be enough of an Ethernet implementation
  * to make arp work.  The way we do this is by telling everyone
  * that we are an Ethernet, and then catch the packets that
- * ether_output() left on our output queue when it calls
- * if_start(), rewrite them for use by the real outgoing interface,
- * and ask it to send them.
+ * ether_output() sends to us via if_transmit(), rewrite them for
+ * use by the real outgoing interface, and ask it to send them.
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/net/if_vlan.c 227459 2011-11-11 22:57:52Z brooks $");
+__FBSDID("$FreeBSD: head/sys/net/if_vlan.c 228089 2011-11-28 19:35:08Z jhb $");
 
 #include "opt_vlan.h"
 
@@ -183,14 +182,15 @@
 #endif
 static	void trunk_destroy(struct ifvlantrunk *trunk);
 
-static	void vlan_start(struct ifnet *ifp);
 static	void vlan_init(void *foo);
 static	void vlan_input(struct ifnet *ifp, struct mbuf *m);
 static	int vlan_ioctl(struct ifnet *ifp, u_long cmd, caddr_t addr);
+static	void vlan_qflush(struct ifnet *ifp);
 static	int vlan_setflag(struct ifnet *ifp, int flag, int status,
     int (*func)(struct ifnet *, int));
 static	int vlan_setflags(struct ifnet *ifp, int status);
 static	int vlan_setmulti(struct ifnet *ifp);
+static	int vlan_transmit(struct ifnet *ifp, struct mbuf *m);
 static	void vlan_unconfig(struct ifnet *ifp);
 static	void vlan_unconfig_locked(struct ifnet *ifp);
 static	int vlan_config(struct ifvlan *ifv, struct ifnet *p, uint16_t tag);
@@ -944,9 +944,9 @@
 	/* NB: mtu is not set here */
 
 	ifp->if_init = vlan_init;
-	ifp->if_start = vlan_start;
+	ifp->if_transmit = vlan_transmit;
+	ifp->if_qflush = vlan_qflush;
 	ifp->if_ioctl = vlan_ioctl;
-	ifp->if_snd.ifq_maxlen = ifqmaxlen;
 	ifp->if_flags = VLAN_IFFLAGS;
 	ether_ifattach(ifp, eaddr);
 	/* Now undo some of the damage... */
@@ -1005,99 +1005,95 @@
 }
 
 /*
- * The if_start method for vlan(4) interface. It doesn't
- * raises the IFF_DRV_OACTIVE flag, since it is called
- * only from IFQ_HANDOFF() macro in ether_output_frame().
- * If the interface queue is full, and vlan_start() is
- * not called, the queue would never get emptied and
- * interface would stall forever.
+ * The if_transmit method for vlan(4) interface.
  */
-static void
-vlan_start(struct ifnet *ifp)
+static int
+vlan_transmit(struct ifnet *ifp, struct mbuf *m)
 {
 	struct ifvlan *ifv;
 	struct ifnet *p;
-	struct mbuf *m;
 	int error;
 
 	ifv = ifp->if_softc;
 	p = PARENT(ifv);
 
-	for (;;) {
-		IF_DEQUEUE(&ifp->if_snd, m);
-		if (m == NULL)
-			break;
-		BPF_MTAP(ifp, m);
+	BPF_MTAP(ifp, m);
 
-		/*
-		 * Do not run parent's if_start() if the parent is not up,
-		 * or parent's driver will cause a system crash.
-		 */
-		if (!UP_AND_RUNNING(p)) {
+	/*
+	 * Do not run parent's if_transmit() if the parent is not up,
+	 * or parent's driver will cause a system crash.
+	 */
+	if (!UP_AND_RUNNING(p)) {
+		m_freem(m);
+		ifp->if_collisions++;
+		return (0);
+	}
+
+	/*
+	 * Pad the frame to the minimum size allowed if told to.
+	 * This option is in accord with IEEE Std 802.1Q, 2003 Ed.,
+	 * paragraph C.4.4.3.b.  It can help to work around buggy
+	 * bridges that violate paragraph C.4.4.3.a from the same
+	 * document, i.e., fail to pad short frames after untagging.
+	 * E.g., a tagged frame 66 bytes long (incl. FCS) is OK, but
+	 * untagging it will produce a 62-byte frame, which is a runt
+	 * and requires padding.  There are VLAN-enabled network
+	 * devices that just discard such runts instead or mishandle
+	 * them somehow.
+	 */
+	if (soft_pad && p->if_type == IFT_ETHER) {
+		static char pad[8];	/* just zeros */
+		int n;
+
+		for (n = ETHERMIN + ETHER_HDR_LEN - m->m_pkthdr.len;
+		     n > 0; n -= sizeof(pad))
+			if (!m_append(m, min(n, sizeof(pad)), pad))
+				break;
+
+		if (n > 0) {
+			if_printf(ifp, "cannot pad short frame\n");
+			ifp->if_oerrors++;
 			m_freem(m);
-			ifp->if_collisions++;
-			continue;
+			return (0);
 		}
+	}
 
-		/*
-		 * Pad the frame to the minimum size allowed if told to.
-		 * This option is in accord with IEEE Std 802.1Q, 2003 Ed.,
-		 * paragraph C.4.4.3.b.  It can help to work around buggy
-		 * bridges that violate paragraph C.4.4.3.a from the same
-		 * document, i.e., fail to pad short frames after untagging.
-		 * E.g., a tagged frame 66 bytes long (incl. FCS) is OK, but
-		 * untagging it will produce a 62-byte frame, which is a runt
-		 * and requires padding.  There are VLAN-enabled network
-		 * devices that just discard such runts instead or mishandle
-		 * them somehow.
-		 */
-		if (soft_pad && p->if_type == IFT_ETHER) {
-			static char pad[8];	/* just zeros */
-			int n;
+	/*
+	 * If underlying interface can do VLAN tag insertion itself,
+	 * just pass the packet along. However, we need some way to
+	 * tell the interface where the packet came from so that it
+	 * knows how to find the VLAN tag to use, so we attach a
+	 * packet tag that holds it.
+	 */
+	if (p->if_capenable & IFCAP_VLAN_HWTAGGING) {
+		m->m_pkthdr.ether_vtag = ifv->ifv_tag;
+		m->m_flags |= M_VLANTAG;
+	} else {
+		m = ether_vlanencap(m, ifv->ifv_tag);
+		if (m == NULL) {
+			if_printf(ifp, "unable to prepend VLAN header\n");
+			ifp->if_oerrors++;
+			return (0);
+		}
+	}
 
-			for (n = ETHERMIN + ETHER_HDR_LEN - m->m_pkthdr.len;
-			     n > 0; n -= sizeof(pad))
-				if (!m_append(m, min(n, sizeof(pad)), pad))
-					break;
+	/*
+	 * Send it, precisely as ether_output() would have.
+	 */
+	error = (p->if_transmit)(p, m);
+	if (!error)
+		ifp->if_opackets++;
+	else
+		ifp->if_oerrors++;
+	return (error);
+}
 
-			if (n > 0) {
-				if_printf(ifp, "cannot pad short frame\n");
-				ifp->if_oerrors++;
-				m_freem(m);
-				continue;
-			}
-		}
-
-		/*
-		 * If underlying interface can do VLAN tag insertion itself,
-		 * just pass the packet along. However, we need some way to
-		 * tell the interface where the packet came from so that it
-		 * knows how to find the VLAN tag to use, so we attach a
-		 * packet tag that holds it.
-		 */
-		if (p->if_capenable & IFCAP_VLAN_HWTAGGING) {
-			m->m_pkthdr.ether_vtag = ifv->ifv_tag;
-			m->m_flags |= M_VLANTAG;
-		} else {
-			m = ether_vlanencap(m, ifv->ifv_tag);
-			if (m == NULL) {
-				if_printf(ifp,
-				    "unable to prepend VLAN header\n");
-				ifp->if_oerrors++;
-				continue;
-			}
-		}
-
-		/*
-		 * Send it, precisely as ether_output() would have.
-		 * We are already running at splimp.
-		 */
-		error = (p->if_transmit)(p, m);
-		if (!error)
-			ifp->if_opackets++;
-		else
-			ifp->if_oerrors++;
-	}
+/*
+ * The ifp->if_qflush entry point for vlan(4) is a no-op.
+ */
+static void
+vlan_qflush(struct ifnet *ifp __unused)
+{
 }
 
 static void
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/net/netmap.h
--- a/head/sys/net/netmap.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/net/netmap.h	Tue Dec 06 20:26:16 2011 +0200
@@ -31,8 +31,8 @@
  */
 
 /*
- * $FreeBSD: head/sys/net/netmap.h 227614 2011-11-17 12:17:39Z luigi $
- * $Id: netmap.h 9662 2011-11-16 13:18:06Z luigi $
+ * $FreeBSD: head/sys/net/netmap.h 228276 2011-12-05 12:06:53Z luigi $
+ * $Id: netmap.h 9753 2011-11-28 15:10:43Z luigi $
  *
  * This header contains the definitions of the constants and the
  * structures needed by the ``netmap'' module, both kernel and
@@ -186,13 +186,6 @@
 
 	const uint16_t	nr_buf_size;
 	uint16_t	flags;
-	/*
-	 * When a ring is reinitialized, the kernel sets kflags.
-	 * On exit from a syscall, if the flag is found set, we
-	 * also reinitialize the nr_* variables. The kflag is then
-	 * unconditionally copied to nr_flags and cleared.
-	 */
-#define	NR_REINIT	0x0001		/* ring reinitialized! */
 #define	NR_TIMESTAMP	0x0002		/* set timestamp on *sync() */
 
 	struct timeval	ts;		/* time of last *sync() */
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/netinet/in.c
--- a/head/sys/netinet/in.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/netinet/in.c	Tue Dec 06 20:26:16 2011 +0200
@@ -31,7 +31,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/netinet/in.c 227831 2011-11-22 19:39:27Z glebius $");
+__FBSDID("$FreeBSD: head/sys/netinet/in.c 228062 2011-11-28 13:30:14Z glebius $");
 
 #include "opt_mpath.h"
 
@@ -376,7 +376,7 @@
 	switch (cmd) {
 	case SIOCAIFADDR:
 	case SIOCDIFADDR:
-		if (ifra->ifra_addr.sin_len == AF_INET) {
+		if (ifra->ifra_addr.sin_family == AF_INET) {
 			struct in_ifaddr *oia;
 
 			IN_IFADDR_RLOCK();
@@ -533,7 +533,8 @@
 		goto out;
 
 	case SIOCSIFNETMASK:
-		ia->ia_sockmask = *(struct sockaddr_in *)&ifr->ifr_addr;
+		ia->ia_sockmask.sin_addr = ((struct sockaddr_in *)
+		    &ifr->ifr_addr)->sin_addr;
 		ia->ia_subnetmask = ntohl(ia->ia_sockmask.sin_addr.s_addr);
 		goto out;
 
@@ -541,10 +542,7 @@
 		maskIsNew = 0;
 		hostIsNew = 1;
 		error = 0;
-		if (ifra->ifra_addr.sin_len == 0) {
-			ifra->ifra_addr = ia->ia_addr;
-			hostIsNew = 0;
-		} else if (ifra->ifra_addr.sin_addr.s_addr ==
+		if (ifra->ifra_addr.sin_addr.s_addr ==
 			    ia->ia_addr.sin_addr.s_addr)
 			hostIsNew = 0;
 		if (ifra->ifra_mask.sin_len) {
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/netinet/sctp_header.h
--- a/head/sys/netinet/sctp_header.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/netinet/sctp_header.h	Tue Dec 06 20:26:16 2011 +0200
@@ -33,7 +33,7 @@
 /* $KAME: sctp_header.h,v 1.14 2005/03/06 16:04:17 itojun Exp $	 */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/netinet/sctp_header.h 224641 2011-08-03 20:21:00Z tuexen $");
+__FBSDID("$FreeBSD: head/sys/netinet/sctp_header.h 228031 2011-11-27 17:51:13Z tuexen $");
 
 #ifndef __sctp_header_h__
 #define __sctp_header_h__
@@ -81,8 +81,7 @@
 /* supported address type */
 struct sctp_supported_addr_param {
 	struct sctp_paramhdr ph;/* type=SCTP_SUPPORTED_ADDRTYPE */
-	uint16_t addr_type[SCTP_ARRAY_MIN_LEN];	/* array of supported address
-						 * types */
+	uint16_t addr_type[2];	/* array of supported address types */
 }                         SCTP_PACKED;
 
 /* ECN parameter */
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/netinet/sctp_output.c
--- a/head/sys/netinet/sctp_output.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/netinet/sctp_output.c	Tue Dec 06 20:26:16 2011 +0200
@@ -33,7 +33,7 @@
 /* $KAME: sctp_output.c,v 1.46 2005/03/06 16:04:17 itojun Exp $	 */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/netinet/sctp_output.c 227755 2011-11-20 15:00:45Z tuexen $");
+__FBSDID("$FreeBSD: head/sys/netinet/sctp_output.c 228031 2011-11-27 17:51:13Z tuexen $");
 
 #include <netinet/sctp_os.h>
 #include <sys/proc.h>
@@ -4680,24 +4680,24 @@
 #ifdef INET6
 #ifdef INET
 	/* we support 2 types: IPv4/IPv6 */
-	sup_addr->ph.param_length = htons(sizeof(*sup_addr) + sizeof(uint16_t));
+	sup_addr->ph.param_length = htons(sizeof(struct sctp_paramhdr) + 2 * sizeof(uint16_t));
 	sup_addr->addr_type[0] = htons(SCTP_IPV4_ADDRESS);
 	sup_addr->addr_type[1] = htons(SCTP_IPV6_ADDRESS);
 #else
 	/* we support 1 type: IPv6 */
-	sup_addr->ph.param_length = htons(sizeof(*sup_addr) + sizeof(uint8_t));
+	sup_addr->ph.param_length = htons(sizeof(struct sctp_paramhdr) + sizeof(uint16_t));
 	sup_addr->addr_type[0] = htons(SCTP_IPV6_ADDRESS);
 	sup_addr->addr_type[1] = htons(0);	/* this is the padding */
 #endif
 #else
 	/* we support 1 type: IPv4 */
-	sup_addr->ph.param_length = htons(sizeof(*sup_addr) + sizeof(uint8_t));
+	sup_addr->ph.param_length = htons(sizeof(struct sctp_paramhdr) + sizeof(uint16_t));
 	sup_addr->addr_type[0] = htons(SCTP_IPV4_ADDRESS);
 	sup_addr->addr_type[1] = htons(0);	/* this is the padding */
 #endif
-	SCTP_BUF_LEN(m) += sizeof(*sup_addr) + sizeof(uint16_t);
+	SCTP_BUF_LEN(m) += sizeof(struct sctp_supported_addr_param);
 	/* adaptation layer indication parameter */
-	ali = (struct sctp_adaptation_layer_indication *)((caddr_t)sup_addr + sizeof(*sup_addr) + sizeof(uint16_t));
+	ali = (struct sctp_adaptation_layer_indication *)((caddr_t)sup_addr + sizeof(struct sctp_supported_addr_param));
 	ali->ph.param_type = htons(SCTP_ULP_ADAPTATION);
 	ali->ph.param_length = htons(sizeof(*ali));
 	ali->indication = ntohl(inp->sctp_ep.adaptation_layer_indicator);
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/netinet/sctp_pcb.c
--- a/head/sys/netinet/sctp_pcb.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/netinet/sctp_pcb.c	Tue Dec 06 20:26:16 2011 +0200
@@ -33,7 +33,7 @@
 /* $KAME: sctp_pcb.c,v 1.38 2005/03/06 16:04:18 itojun Exp $	 */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/netinet/sctp_pcb.c 227755 2011-11-20 15:00:45Z tuexen $");
+__FBSDID("$FreeBSD: head/sys/netinet/sctp_pcb.c 228102 2011-11-28 20:48:35Z tuexen $");
 
 #include <netinet/sctp_os.h>
 #include <sys/proc.h>
@@ -6895,11 +6895,6 @@
 	return (1);
 }
 
-
-static sctp_assoc_t reneged_asoc_ids[256];
-static uint8_t reneged_at = 0;
-
-
 static void
 sctp_drain_mbufs(struct sctp_inpcb *inp, struct sctp_tcb *stcb)
 {
@@ -7004,8 +6999,6 @@
 		/* sa_ignore NO_NULL_CHK */
 		sctp_send_sack(stcb, SCTP_SO_NOT_LOCKED);
 		sctp_chunk_output(stcb->sctp_ep, stcb, SCTP_OUTPUT_FROM_DRAIN, SCTP_SO_NOT_LOCKED);
-		reneged_asoc_ids[reneged_at] = sctp_get_associd(stcb);
-		reneged_at++;
 	}
 	/*
 	 * Another issue, in un-setting the TSN's in the mapping array we
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/netinet/sctp_uio.h
--- a/head/sys/netinet/sctp_uio.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/netinet/sctp_uio.h	Tue Dec 06 20:26:16 2011 +0200
@@ -32,7 +32,7 @@
 
 /* $KAME: sctp_uio.h,v 1.11 2005/03/06 16:04:18 itojun Exp $	 */
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/netinet/sctp_uio.h 227755 2011-11-20 15:00:45Z tuexen $");
+__FBSDID("$FreeBSD: head/sys/netinet/sctp_uio.h 227931 2011-11-24 10:58:48Z tuexen $");
 
 #ifndef __sctp_uio_h__
 #define __sctp_uio_h__
@@ -521,8 +521,8 @@
 #define SPP_IPV4_TOS            SPP_DSCP
 
 struct sctp_paddrthlds {
+	struct sockaddr_storage spt_address;
 	sctp_assoc_t spt_assoc_id;
-	struct sockaddr_storage spt_address;
 	uint16_t spt_pathmaxrxt;
 	uint16_t spt_pathpfthld;
 };
@@ -672,8 +672,8 @@
 };
 
 struct sctp_udpencaps {
+	struct sockaddr_storage sue_address;
 	sctp_assoc_t sue_assoc_id;
-	struct sockaddr_storage sue_address;
 	uint16_t sue_port;
 };
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/netinet/tcp_reass.c
--- a/head/sys/netinet/tcp_reass.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/netinet/tcp_reass.c	Tue Dec 06 20:26:16 2011 +0200
@@ -30,7 +30,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/netinet/tcp_reass.c 227309 2011-11-07 15:43:11Z ed $");
+__FBSDID("$FreeBSD: head/sys/netinet/tcp_reass.c 228016 2011-11-27 02:32:08Z lstewart $");
 
 #include "opt_inet.h"
 #include "opt_inet6.h"
@@ -233,23 +233,28 @@
 	 * when the zone is exhausted. Otherwise we may get stuck.
 	 */
 	te = uma_zalloc(V_tcp_reass_zone, M_NOWAIT);
-	if (te == NULL && th->th_seq != tp->rcv_nxt) {
-		TCPSTAT_INC(tcps_rcvmemdrop);
-		m_freem(m);
-		*tlenp = 0;
-		if ((s = tcp_log_addrs(&tp->t_inpcb->inp_inc, th, NULL, NULL))) {
-			log(LOG_DEBUG, "%s; %s: global zone limit reached, "
-			    "segment dropped\n", s, __func__);
-			free(s, M_TCPLOG);
-		}
-		return (0);
-	} else if (th->th_seq == tp->rcv_nxt) {
-		bzero(&tqs, sizeof(struct tseg_qent));
-		te = &tqs;
-		if ((s = tcp_log_addrs(&tp->t_inpcb->inp_inc, th, NULL, NULL))) {
-			log(LOG_DEBUG, "%s; %s: global zone limit reached, "
-			    "using stack for missing segment\n", s, __func__);
-			free(s, M_TCPLOG);
+	if (te == NULL) {
+		if (th->th_seq != tp->rcv_nxt) {
+			TCPSTAT_INC(tcps_rcvmemdrop);
+			m_freem(m);
+			*tlenp = 0;
+			if ((s = tcp_log_addrs(&tp->t_inpcb->inp_inc, th, NULL,
+			    NULL))) {
+				log(LOG_DEBUG, "%s; %s: global zone limit "
+				    "reached, segment dropped\n", s, __func__);
+				free(s, M_TCPLOG);
+			}
+			return (0);
+		} else {
+			bzero(&tqs, sizeof(struct tseg_qent));
+			te = &tqs;
+			if ((s = tcp_log_addrs(&tp->t_inpcb->inp_inc, th, NULL,
+			    NULL))) {
+				log(LOG_DEBUG,
+				    "%s; %s: global zone limit reached, using "
+				    "stack for missing segment\n", s, __func__);
+				free(s, M_TCPLOG);
+			}
 		}
 	}
 	tp->t_segqlen++;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/netipsec/xform_ah.c
--- a/head/sys/netipsec/xform_ah.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/netipsec/xform_ah.c	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-/*	$FreeBSD: head/sys/netipsec/xform_ah.c 221129 2011-04-27 19:28:42Z bz $	*/
+/*	$FreeBSD: head/sys/netipsec/xform_ah.c 228010 2011-11-26 23:15:28Z pjd $	*/
 /*	$OpenBSD: ip_ah.c,v 1.63 2001/06/26 06:18:58 angelos Exp $ */
 /*-
  * The authors of this code are John Ioannidis (ji at tla.org),
@@ -770,10 +770,8 @@
 		if (sav->tdb_cryptoid != 0)
 			sav->tdb_cryptoid = crp->crp_sid;
 
-		if (crp->crp_etype == EAGAIN) {
-			error = crypto_dispatch(crp);
-			return error;
-		}
+		if (crp->crp_etype == EAGAIN)
+			return (crypto_dispatch(crp));
 
 		V_ahstat.ahs_noxform++;
 		DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
@@ -1137,7 +1135,6 @@
 	struct secasvar *sav;
 	struct mbuf *m;
 	caddr_t ptr;
-	int err;
 
 	tc = (struct tdb_crypto *) crp->crp_opaque;
 	IPSEC_ASSERT(tc != NULL, ("null opaque data area!"));
@@ -1164,8 +1161,7 @@
 
 		if (crp->crp_etype == EAGAIN) {
 			IPSECREQUEST_UNLOCK(isr);
-			error = crypto_dispatch(crp);
-			return error;
+			return (crypto_dispatch(crp));
 		}
 
 		V_ahstat.ahs_noxform++;
@@ -1208,10 +1204,10 @@
 #endif
 
 	/* NB: m is reclaimed by ipsec_process_done. */
-	err = ipsec_process_done(m, isr);
+	error = ipsec_process_done(m, isr);
 	KEY_FREESAV(&sav);
 	IPSECREQUEST_UNLOCK(isr);
-	return err;
+	return error;
 bad:
 	if (sav)
 		KEY_FREESAV(&sav);
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/netipsec/xform_esp.c
--- a/head/sys/netipsec/xform_esp.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/netipsec/xform_esp.c	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-/*	$FreeBSD: head/sys/netipsec/xform_esp.c 221129 2011-04-27 19:28:42Z bz $	*/
+/*	$FreeBSD: head/sys/netipsec/xform_esp.c 228014 2011-11-26 23:57:03Z pjd $	*/
 /*	$OpenBSD: ip_esp.c,v 1.69 2001/06/26 06:18:59 angelos Exp $ */
 /*-
  * The authors of this code are John Ioannidis (ji at tla.org),
@@ -85,9 +85,6 @@
 SYSCTL_VNET_STRUCT(_net_inet_esp, IPSECCTL_STATS,
 	stats,		CTLFLAG_RD,	&VNET_NAME(espstat),	espstat, "");
 
-static VNET_DEFINE(int, esp_max_ivlen);	/* max iv length over all algorithms */
-#define	V_esp_max_ivlen	VNET(esp_max_ivlen)
-
 static int esp_input_cb(struct cryptop *op);
 static int esp_output_cb(struct cryptop *crp);
 
@@ -147,7 +144,7 @@
 		 * + sizeof (next header field)
 		 * + max icv supported.
 		 */
-		size = sizeof (struct newesp) + V_esp_max_ivlen + 9 + 16;
+		size = sizeof (struct newesp) + EALG_MAX_BLOCK_LEN + 9 + 16;
 	}
 	return size;
 }
@@ -196,10 +193,6 @@
 	 */
 	sav->ivlen = (txform == &enc_xform_null ? 0 : txform->blocksize);
 	sav->iv = (caddr_t) malloc(sav->ivlen, M_XDATA, M_WAITOK);
-	if (sav->iv == NULL) {
-		DPRINTF(("%s: no memory for IV\n", __func__));
-		return EINVAL;
-	}
 	key_randomfill(sav->iv, sav->ivlen);	/*XXX*/
 
 	/*
@@ -496,10 +489,8 @@
 		if (sav->tdb_cryptoid != 0)
 			sav->tdb_cryptoid = crp->crp_sid;
 
-		if (crp->crp_etype == EAGAIN) {
-			error = crypto_dispatch(crp);
-			return error;
-		}
+		if (crp->crp_etype == EAGAIN)
+			return (crypto_dispatch(crp));
 
 		V_espstat.esps_noxform++;
 		DPRINTF(("%s: crypto error %d\n", __func__, crp->crp_etype));
@@ -678,7 +669,7 @@
 {
 	struct enc_xform *espx;
 	struct auth_hash *esph;
-	int hlen, rlen, plen, padding, blks, alen, i, roff;
+	int hlen, rlen, padding, blks, alen, i, roff;
 	struct mbuf *mo = (struct mbuf *) NULL;
 	struct tdb_crypto *tc;
 	struct secasvar *sav;
@@ -710,7 +701,6 @@
 
 	/* XXX clamp padding length a la KAME??? */
 	padding = ((blks - ((rlen + 2) % blks)) % blks) + 2;
-	plen = rlen + padding;		/* Padded payload length. */
 
 	if (esph)
 		switch (esph->type) {
@@ -921,7 +911,7 @@
 	struct ipsecrequest *isr;
 	struct secasvar *sav;
 	struct mbuf *m;
-	int err, error;
+	int error;
 
 	tc = (struct tdb_crypto *) crp->crp_opaque;
 	IPSEC_ASSERT(tc != NULL, ("null opaque data area!"));
@@ -948,8 +938,7 @@
 
 		if (crp->crp_etype == EAGAIN) {
 			IPSECREQUEST_UNLOCK(isr);
-			error = crypto_dispatch(crp);
-			return error;
+			return (crypto_dispatch(crp));
 		}
 
 		V_espstat.esps_noxform++;
@@ -1004,10 +993,10 @@
 #endif
 
 	/* NB: m is reclaimed by ipsec_process_done. */
-	err = ipsec_process_done(m, isr);
+	error = ipsec_process_done(m, isr);
 	KEY_FREESAV(&sav);
 	IPSECREQUEST_UNLOCK(isr);
-	return err;
+	return error;
 bad:
 	if (sav)
 		KEY_FREESAV(&sav);
@@ -1028,20 +1017,7 @@
 static void
 esp_attach(void)
 {
-#define	MAXIV(xform)					\
-	if (xform.blocksize > V_esp_max_ivlen)		\
-		V_esp_max_ivlen = xform.blocksize	\
-
-	MAXIV(enc_xform_des);		/* SADB_EALG_DESCBC */
-	MAXIV(enc_xform_3des);		/* SADB_EALG_3DESCBC */
-	MAXIV(enc_xform_rijndael128);	/* SADB_X_EALG_AES */
-	MAXIV(enc_xform_blf);		/* SADB_X_EALG_BLOWFISHCBC */
-	MAXIV(enc_xform_cast5);		/* SADB_X_EALG_CAST128CBC */
-	MAXIV(enc_xform_skipjack);	/* SADB_X_EALG_SKIPJACK */
-	MAXIV(enc_xform_null);		/* SADB_EALG_NULL */
-	MAXIV(enc_xform_camellia);	/* SADB_X_EALG_CAMELLIACBC */
 
 	xform_register(&esp_xformsw);
-#undef MAXIV
 }
 SYSINIT(esp_xform_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE, esp_attach, NULL);
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/nfsclient/nfs_bio.c
--- a/head/sys/nfsclient/nfs_bio.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/nfsclient/nfs_bio.c	Tue Dec 06 20:26:16 2011 +0200
@@ -33,7 +33,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/nfsclient/nfs_bio.c 224733 2011-08-09 15:29:58Z jhb $");
+__FBSDID("$FreeBSD: head/sys/nfsclient/nfs_bio.c 228156 2011-11-30 17:39:00Z kib $");
 
 #include "opt_kdtrace.h"
 
@@ -206,7 +206,7 @@
 			 * Read operation filled a partial page.
 			 */
 			m->valid = 0;
-			vm_page_set_valid(m, 0, size - toff);
+			vm_page_set_valid_range(m, 0, size - toff);
 			KASSERT(m->dirty == 0,
 			    ("nfs_getpages: page %p is dirty", m));
 		} else {
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/nfsserver/nfs_serv.c
--- a/head/sys/nfsserver/nfs_serv.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/nfsserver/nfs_serv.c	Tue Dec 06 20:26:16 2011 +0200
@@ -33,7 +33,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/nfsserver/nfs_serv.c 225356 2011-09-03 00:28:53Z rmacklem $");
+__FBSDID("$FreeBSD: head/sys/nfsserver/nfs_serv.c 228185 2011-12-01 18:46:28Z jhb $");
 
 /*
  * nfs version 2 and 3 server calls to vnode ops
@@ -107,14 +107,15 @@
 
 #define MAX_COMMIT_COUNT	(1024 * 1024)
 
-#define NUM_HEURISTIC		1017
+#define	MAX_REORDERED_RPC	16
+#define NUM_HEURISTIC		1031
 #define NHUSE_INIT		64
 #define NHUSE_INC		16
 #define NHUSE_MAX		2048
 
 static struct nfsheur {
 	struct vnode *nh_vp;	/* vp to match (unreferenced pointer) */
-	off_t nh_nextr;		/* next offset for sequential detection */
+	off_t nh_nextoff;	/* next offset for sequential detection */
 	int nh_use;		/* use count for selection */
 	int nh_seqcount;	/* heuristic */
 } nfsheur[NUM_HEURISTIC];
@@ -187,6 +188,63 @@
 }
 
 /*
+ * Heuristic to detect sequential operation.
+ */
+static struct nfsheur *
+nfsrv_sequential_heuristic(struct uio *uio, struct vnode *vp)
+{
+	struct nfsheur *nh;
+	int hi, try;
+
+	/* Locate best candidate. */
+	try = 32;
+	hi = ((int)(vm_offset_t)vp / sizeof(struct vnode)) % NUM_HEURISTIC;
+	nh = &nfsheur[hi];
+	while (try--) {
+		if (nfsheur[hi].nh_vp == vp) {
+			nh = &nfsheur[hi];
+			break;
+		}
+		if (nfsheur[hi].nh_use > 0)
+			--nfsheur[hi].nh_use;
+		hi = (hi + 1) % NUM_HEURISTIC;
+		if (nfsheur[hi].nh_use < nh->nh_use)
+			nh = &nfsheur[hi];
+	}
+
+	/* Initialize hint if this is a new file. */
+	if (nh->nh_vp != vp) {
+		nh->nh_vp = vp;
+		nh->nh_nextoff = uio->uio_offset;
+		nh->nh_use = NHUSE_INIT;
+		if (uio->uio_offset == 0)
+			nh->nh_seqcount = 4;
+		else
+			nh->nh_seqcount = 1;
+	}
+
+	/* Calculate heuristic. */
+	if ((uio->uio_offset == 0 && nh->nh_seqcount > 0) ||
+	    uio->uio_offset == nh->nh_nextoff) {
+		/* See comments in vfs_vnops.c:sequential_heuristic(). */
+		nh->nh_seqcount += howmany(uio->uio_resid, 16384);
+		if (nh->nh_seqcount > IO_SEQMAX)
+			nh->nh_seqcount = IO_SEQMAX;
+	} else if (qabs(uio->uio_offset - nh->nh_nextoff) <= MAX_REORDERED_RPC *
+	    imax(vp->v_mount->mnt_stat.f_iosize, uio->uio_resid)) {
+		/* Probably a reordered RPC, leave seqcount alone. */
+	} else if (nh->nh_seqcount > 1) {
+		nh->nh_seqcount /= 2;
+	} else {
+		nh->nh_seqcount = 0;
+	}
+	nh->nh_use += NHUSE_INC;
+	if (nh->nh_use > NHUSE_MAX)
+		nh->nh_use = NHUSE_MAX;
+	return (nh);
+}
+
+/*
  * nfs v3 access service
  */
 int
@@ -843,7 +901,6 @@
 	/*
 	 * Calculate byte count to read
 	 */
-
 	if (off >= vap->va_size)
 		cnt = 0;
 	else if ((off + reqlen) > vap->va_size)
@@ -851,61 +908,6 @@
 	else
 		cnt = reqlen;
 
-	/*
-	 * Calculate seqcount for heuristic
-	 */
-
-	{
-		int hi;
-		int try = 32;
-
-		/*
-		 * Locate best candidate
-		 */
-
-		hi = ((int)(vm_offset_t)vp / sizeof(struct vnode)) % NUM_HEURISTIC;
-		nh = &nfsheur[hi];
-
-		while (try--) {
-			if (nfsheur[hi].nh_vp == vp) {
-				nh = &nfsheur[hi];
-				break;
-			}
-			if (nfsheur[hi].nh_use > 0)
-				--nfsheur[hi].nh_use;
-			hi = (hi + 1) % NUM_HEURISTIC;
-			if (nfsheur[hi].nh_use < nh->nh_use)
-				nh = &nfsheur[hi];
-		}
-
-		if (nh->nh_vp != vp) {
-			nh->nh_vp = vp;
-			nh->nh_nextr = off;
-			nh->nh_use = NHUSE_INIT;
-			if (off == 0)
-				nh->nh_seqcount = 4;
-			else
-				nh->nh_seqcount = 1;
-		}
-
-		/*
-		 * Calculate heuristic
-		 */
-
-		if ((off == 0 && nh->nh_seqcount > 0) || off == nh->nh_nextr) {
-			if (++nh->nh_seqcount > IO_SEQMAX)
-				nh->nh_seqcount = IO_SEQMAX;
-		} else if (nh->nh_seqcount > 1) {
-			nh->nh_seqcount = 1;
-		} else {
-			nh->nh_seqcount = 0;
-		}
-		nh->nh_use += NHUSE_INC;
-		if (nh->nh_use > NHUSE_MAX)
-			nh->nh_use = NHUSE_MAX;
-		ioflag |= nh->nh_seqcount << IO_SEQSHIFT;
-        }
-
 	nfsm_reply(NFSX_POSTOPORFATTR(v3) + 3 * NFSX_UNSIGNED+nfsm_rndup(cnt));
 	if (v3) {
 		tl = nfsm_build(u_int32_t *, NFSX_V3FATTR + 4 * NFSX_UNSIGNED);
@@ -963,9 +965,11 @@
 		uiop->uio_resid = len;
 		uiop->uio_rw = UIO_READ;
 		uiop->uio_segflg = UIO_SYSSPACE;
+		nh = nfsrv_sequential_heuristic(uiop, vp);
+		ioflag |= nh->nh_seqcount << IO_SEQSHIFT;
 		error = VOP_READ(vp, uiop, IO_NODELOCKED | ioflag, cred);
-		off = uiop->uio_offset;
-		nh->nh_nextr = off;
+		if (error == 0)
+			nh->nh_nextoff = uiop->uio_offset;
 		free((caddr_t)iv2, M_TEMP);
 		if (error || (getret = VOP_GETATTR(vp, vap, cred))) {
 			if (!error)
@@ -1030,6 +1034,7 @@
 	int v3 = (nfsd->nd_flag & ND_NFSV3);
 	struct mbuf *mb, *mreq;
 	struct vnode *vp = NULL;
+	struct nfsheur *nh;
 	nfsfh_t nfh;
 	fhandle_t *fhp;
 	struct uio io, *uiop = &io;
@@ -1170,7 +1175,11 @@
 	    uiop->uio_segflg = UIO_SYSSPACE;
 	    uiop->uio_td = NULL;
 	    uiop->uio_offset = off;
+	    nh = nfsrv_sequential_heuristic(uiop, vp);
+	    ioflags |= nh->nh_seqcount << IO_SEQSHIFT;
 	    error = VOP_WRITE(vp, uiop, ioflags, cred);
+	    if (error == 0)
+		    nh->nh_nextoff = uiop->uio_offset;
 	    /* Unlocked write. */
 	    nfsrvstats.srvvop_writes++;
 	    free((caddr_t)iv, M_TEMP);
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/pc98/include/md_var.h
--- a/head/sys/pc98/include/md_var.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/pc98/include/md_var.h	Tue Dec 06 20:26:16 2011 +0200
@@ -22,7 +22,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD$
+ * $FreeBSD: head/sys/pc98/include/md_var.h 228027 2011-11-27 16:22:19Z marius $
  */
 
 #ifndef _PC98_INCLUDE_MD_VAR_H_
@@ -39,10 +39,10 @@
 extern	int	need_post_dma_flush;
 
 /*
- * The ad driver maps the IDE disk's actual geometry to the firmware's
- * notion of geometry.  However, PC98 machines need to do something
- * different sometimes, so override the hook so we can do so.
+ * The geometry of disks might need adjustment on PC98 machines.
  */
+struct	ccb_calc_geometry;
+int	scsi_da_bios_params(struct ccb_calc_geometry *);
 struct disk;
 void	pc98_ata_disk_firmware_geom_adjust(struct disk *);
 #define	ata_disk_firmware_geom_adjust(disk)				\
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/pc98/pc98/pc98_machdep.h
--- a/head/sys/pc98/pc98/pc98_machdep.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/pc98/pc98/pc98_machdep.h	Tue Dec 06 20:26:16 2011 +0200
@@ -24,7 +24,7 @@
  * (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$
+ * $FreeBSD: head/sys/pc98/pc98/pc98_machdep.h 228027 2011-11-27 16:22:19Z marius $
  */
 
 #ifndef __PC98_PC98_PC98_MACHDEP_H__
@@ -33,9 +33,6 @@
 void	pc98_init_dmac(void);
 unsigned int	pc98_getmemsize(unsigned *, unsigned *);
 
-struct	ccb_calc_geometry;
-int	scsi_da_bios_params(struct ccb_calc_geometry *);
-
 #define	PC98_VECTOR_SIZE			(0x400)
 #define	PC98_SYSTEM_PARAMETER_SIZE		(0x240)
 #define	PC98_SAVE_AREA				(0xa1000)
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/pci/if_rlreg.h
--- a/head/sys/pci/if_rlreg.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/pci/if_rlreg.h	Tue Dec 06 20:26:16 2011 +0200
@@ -29,7 +29,7 @@
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
  * THE POSSIBILITY OF SUCH DAMAGE.
  *
- * $FreeBSD: head/sys/pci/if_rlreg.h 227639 2011-11-17 22:07:50Z yongari $
+ * $FreeBSD: head/sys/pci/if_rlreg.h 227916 2011-11-23 23:29:18Z yongari $
  */
 
 /*
@@ -143,6 +143,7 @@
  */
 #define	RL_TXCFG_CLRABRT	0x00000001	/* retransmit aborted pkt */
 #define	RL_TXCFG_MAXDMA		0x00000700	/* max DMA burst size */
+#define	RL_TXCFG_QUEUE_EMPTY	0x00000800	/* 8168E-VL or higher */
 #define	RL_TXCFG_CRCAPPEND	0x00010000	/* CRC append (0 = yes) */
 #define	RL_TXCFG_LOOPBKTST	0x00060000	/* loopback test */
 #define	RL_TXCFG_IFG2		0x00080000	/* 8169 only */
@@ -897,22 +898,25 @@
 	int			rl_int_rx_act;
 	int			rl_int_rx_mod;
 	uint32_t		rl_flags;
-#define	RL_FLAG_MSI		0x0001
-#define	RL_FLAG_AUTOPAD		0x0002
-#define	RL_FLAG_PHYWAKE_PM	0x0004
-#define	RL_FLAG_PHYWAKE		0x0008
-#define	RL_FLAG_JUMBOV2		0x0010
-#define	RL_FLAG_PAR		0x0020
-#define	RL_FLAG_DESCV2		0x0040
-#define	RL_FLAG_MACSTAT		0x0080
-#define	RL_FLAG_FASTETHER	0x0100
-#define	RL_FLAG_CMDSTOP		0x0200
-#define	RL_FLAG_MACRESET	0x0400
-#define	RL_FLAG_MSIX		0x0800
-#define	RL_FLAG_WOLRXENB	0x1000
-#define	RL_FLAG_MACSLEEP	0x2000
-#define	RL_FLAG_PCIE		0x4000
-#define	RL_FLAG_LINK		0x8000
+#define	RL_FLAG_MSI		0x00000001
+#define	RL_FLAG_AUTOPAD		0x00000002
+#define	RL_FLAG_PHYWAKE_PM	0x00000004
+#define	RL_FLAG_PHYWAKE		0x00000008
+#define	RL_FLAG_JUMBOV2		0x00000010
+#define	RL_FLAG_PAR		0x00000020
+#define	RL_FLAG_DESCV2		0x00000040
+#define	RL_FLAG_MACSTAT		0x00000080
+#define	RL_FLAG_FASTETHER	0x00000100
+#define	RL_FLAG_CMDSTOP		0x00000200
+#define	RL_FLAG_MACRESET	0x00000400
+#define	RL_FLAG_MSIX		0x00000800
+#define	RL_FLAG_WOLRXENB	0x00001000
+#define	RL_FLAG_MACSLEEP	0x00002000
+#define	RL_FLAG_WAIT_TXPOLL	0x00004000
+#define	RL_FLAG_CMDSTOP_WAIT_TXQ	0x00008000
+#define	RL_FLAG_WOL_MANLINK	0x00010000
+#define	RL_FLAG_PCIE		0x40000000
+#define	RL_FLAG_LINK		0x80000000
 };
 
 #define	RL_LOCK(_sc)		mtx_lock(&(_sc)->rl_mtx)
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/powerpc/booke/platform_bare.c
--- a/head/sys/powerpc/booke/platform_bare.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/powerpc/booke/platform_bare.c	Tue Dec 06 20:26:16 2011 +0200
@@ -25,7 +25,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/powerpc/booke/platform_bare.c 224618 2011-08-02 23:49:23Z marcel $");
+__FBSDID("$FreeBSD: head/sys/powerpc/booke/platform_bare.c 228201 2011-12-02 15:24:39Z jchandra $");
 
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -189,7 +189,7 @@
 	} else
 		ticks = 0;
 
-	if ((cpus = OF_finddevice("/cpus")) == 0)
+	if ((cpus = OF_finddevice("/cpus")) == -1)
 		goto out;
 
 	if ((child = OF_child(cpus)) == 0)
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/powerpc/powermac/platform_powermac.c
--- a/head/sys/powerpc/powermac/platform_powermac.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/powerpc/powermac/platform_powermac.c	Tue Dec 06 20:26:16 2011 +0200
@@ -26,7 +26,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/sys/powerpc/powermac/platform_powermac.c 228201 2011-12-02 15:24:39Z jchandra $");
 
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -163,7 +163,7 @@
 		 * but it can be found directly
 		 */
 		dev = OF_finddevice("/cpus");
-		if (dev == 0)
+		if (dev == -1)
 			return (ENOENT);
 	}
 
@@ -209,7 +209,7 @@
 	int res;
 
 	chosen = OF_finddevice("/chosen");
-	if (chosen == 0)
+	if (chosen == -1)
 		return (ENXIO);
 
 	res = OF_getprop(chosen, "cpu", &inst, sizeof(inst));
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/powerpc/powermac/pmu.c
--- a/head/sys/powerpc/powermac/pmu.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/powerpc/powermac/pmu.c	Tue Dec 06 20:26:16 2011 +0200
@@ -27,7 +27,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/powerpc/powermac/pmu.c 227843 2011-11-22 21:28:20Z marius $");
+__FBSDID("$FreeBSD: head/sys/powerpc/powermac/pmu.c 228277 2011-12-05 14:13:21Z jhibbits $");
 
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -701,6 +701,20 @@
 		adb_receive_raw_packet(sc->adb_bus,resp[1],resp[2],
 			len - 3,&resp[3]);
 	}
+	if (resp[1] & PMU_INT_ENVIRONMENT) {
+		/* if the lid was just closed, notify devd. */
+		if ((resp[2] & PMU_ENV_LID_CLOSED) && (!sc->lid_closed)) {
+			sc->lid_closed = 1;
+			if (devctl_process_running())
+				devctl_notify("PMU", "lid", "close", NULL);
+		}
+		else if (!(resp[2] & PMU_ENV_LID_CLOSED) && (sc->lid_closed)) {
+			/* if the lid was just opened, notify devd. */
+			if (devctl_process_running())
+				devctl_notify("PMU", "lid", "open", NULL);
+			sc->lid_closed = 0;
+		}
+	}
 }
 
 static u_int
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/powerpc/powermac/pmuvar.h
--- a/head/sys/powerpc/powermac/pmuvar.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/powerpc/powermac/pmuvar.h	Tue Dec 06 20:26:16 2011 +0200
@@ -24,7 +24,7 @@
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  * POSSIBILITY OF SUCH DAMAGE.
  *
- * $FreeBSD$
+ * $FreeBSD: head/sys/powerpc/powermac/pmuvar.h 228270 2011-12-05 00:12:10Z jhibbits $
  *
  */
 
@@ -160,6 +160,7 @@
 	volatile int	sc_autopoll;
 	int		sc_batteries;
 	struct cdev	*sc_leddev;
+	int	lid_closed;
 };
 
 struct pmu_battstate {
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/sparc64/conf/GENERIC
--- a/head/sys/sparc64/conf/GENERIC	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/sparc64/conf/GENERIC	Tue Dec 06 20:26:16 2011 +0200
@@ -16,7 +16,7 @@
 # If you are in doubt as to the purpose or necessity of a line, check first
 # in NOTES.
 #
-# $FreeBSD: head/sys/sparc64/conf/GENERIC 227006 2011-11-01 21:26:57Z marius $
+# $FreeBSD: head/sys/sparc64/conf/GENERIC 227980 2011-11-25 17:40:01Z marius $
 
 cpu		SUN4U
 ident		GENERIC
@@ -26,7 +26,7 @@
 # Platforms supported
 #	At this time all platforms are supported, as-is.
 
-options 	SCHED_4BSD		# 4BSD scheduler
+options 	SCHED_ULE		# ULE scheduler
 #options 	PREEMPTION		# Enable kernel thread preemption
 options 	INET			# InterNETworking
 options 	INET6			# IPv6 communications protocols
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/sparc64/include/atomic.h
--- a/head/sys/sparc64/include/atomic.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/sparc64/include/atomic.h	Tue Dec 06 20:26:16 2011 +0200
@@ -25,7 +25,7 @@
  * SUCH DAMAGE.
  *
  *	from: FreeBSD: src/sys/i386/include/atomic.h,v 1.20 2001/02/11
- * $FreeBSD: head/sys/sparc64/include/atomic.h 225890 2011-10-01 00:22:24Z marius $
+ * $FreeBSD: head/sys/sparc64/include/atomic.h 228222 2011-12-03 13:51:57Z marius $
  */
 
 #ifndef	_MACHINE_ATOMIC_H_
@@ -78,7 +78,7 @@
  * order which we use for running the kernel and all of the userland atomic
  * loads and stores behave as if the were followed by a membar with a mask
  * of #LoadLoad | #LoadStore | #StoreStore.  In order to be also sufficient
- * for use of relaxed memory ordering, the atomic_cas() in the acq variants 
+ * for use of relaxed memory ordering, the atomic_cas() in the acq variants
  * additionally would have to be followed by a membar #LoadLoad | #LoadStore.
  * Due to the suggested assembly syntax of the membar operands containing a
  * # character, they cannot be used in macros.  The cmask and mmask bits thus
@@ -97,6 +97,7 @@
 #define	atomic_cas_acq(p, e, s, sz) ({					\
 	itype(sz) v;							\
 	v = atomic_cas((p), (e), (s), sz);				\
+	__asm __volatile("" : : : "memory");				\
 	v;								\
 })
 
@@ -121,6 +122,7 @@
 #define	atomic_op_acq(p, op, v, sz) ({					\
 	itype(sz) t;							\
 	t = atomic_op((p), op, (v), sz);				\
+	__asm __volatile("" : : : "memory");				\
 	t;								\
 })
 
@@ -137,6 +139,7 @@
 #define	atomic_load_acq(p, sz) ({					\
 	itype(sz) v;							\
 	v = atomic_load((p), sz);					\
+	__asm __volatile("" : : : "memory");				\
 	v;								\
 })
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/sparc64/include/md_var.h
--- a/head/sys/sparc64/include/md_var.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/sparc64/include/md_var.h	Tue Dec 06 20:26:16 2011 +0200
@@ -27,7 +27,7 @@
  * SUCH DAMAGE.
  *
  *	from: FreeBSD: src/sys/i386/include/md_var.h,v 1.40 2001/07/12
- * $FreeBSD$
+ * $FreeBSD: head/sys/sparc64/include/md_var.h 228022 2011-11-27 15:43:40Z marius $
  */
 
 #ifndef	_MACHINE_MD_VAR_H_
@@ -65,10 +65,11 @@
 extern	cpu_block_zero_t *cpu_block_zero;
 
 /*
- * Given that the Sun disk label only uses 16-bit fields for cylinders,
- * heads and sectors we might need to adjust the geometry of large IDE
- * disks.
+ * Given that the VTOC8 disk label only uses 16-bit fields for cylinders,
+ * heads and sectors we might need to adjust the geometry of large disks.
  */
+struct ccb_calc_geometry;
+int scsi_da_bios_params(struct ccb_calc_geometry *ccg);
 struct disk;
 void sparc64_ata_disk_firmware_geom_adjust(struct disk *disk);
 #define	ata_disk_firmware_geom_adjust(disk)				\
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/sparc64/pci/schizo.c
--- a/head/sys/sparc64/pci/schizo.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/sparc64/pci/schizo.c	Tue Dec 06 20:26:16 2011 +0200
@@ -32,7 +32,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/sparc64/pci/schizo.c 227843 2011-11-22 21:28:20Z marius $");
+__FBSDID("$FreeBSD: head/sys/sparc64/pci/schizo.c 227960 2011-11-24 23:48:22Z marius $");
 
 /*
  * Driver for `Schizo' Fireplane/Safari to PCI 2.1, `Tomatillo' JBus to
@@ -1175,7 +1175,7 @@
 			;
 		SCHIZO_PCI_WRITE_8(sc, sc->sc_cdma_clr, INTCLR_RECEIVED);
 		microuptime(&cur);
-		end.tv_sec = 1;
+		end.tv_sec = 15;
 		end.tv_usec = 0;
 		timevaladd(&end, &cur);
 		for (; (res = atomic_cmpset_rel_32(&sc->sc_cdma_state,
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/sparc64/sparc64/ata_machdep.c
--- a/head/sys/sparc64/sparc64/ata_machdep.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/sparc64/sparc64/ata_machdep.c	Tue Dec 06 20:26:16 2011 +0200
@@ -25,7 +25,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/sys/sparc64/sparc64/ata_machdep.c 228024 2011-11-27 15:49:46Z marius $");
 
 #include <sys/param.h>
 #include <geom/geom_disk.h>
@@ -36,14 +36,13 @@
 {
 
 	/*
-	 * The Sun disk label only uses 16-bit fields for cylinders,
-	 * heads and sectors so the geometry of large IDE disks has
-	 * to be adjusted.  If the disk is > 32GB at 16 heads and 63
-	 * sectors, the sectors have to be adjusted to 255.  If the
-	 * the disk is even > 128GB, additionally adjust the heads
-	 * to 255.
-	 * XXX the OpenSolaris dad(7D) driver limits the mediasize
-	 * to 128GB.
+	 * The VTOC8 disk label only uses 16-bit fields for cylinders, heads
+	 * and sectors so the geometry of large disks has to be adjusted.
+	 * If the disk is > 32GB at 16 heads and 63 sectors, adjust to 255
+	 * sectors (this matches what the OpenSolaris dad(7D) driver does).
+	 * If the the disk is even > 128GB, additionally adjust the heads to
+	 * 255.  This allows disks up to the 2TB limit of the extended VTOC8.
+	 * XXX the OpenSolaris dad(7D) driver limits the mediasize to 128GB.
 	 */
 	if (disk->d_mediasize > (off_t)65535 * 16 * 63 * disk->d_sectorsize)
 		disk->d_fwsectors = 255;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/sparc64/sparc64/cam_machdep.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/sys/sparc64/sparc64/cam_machdep.c	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,74 @@
+/*-
+ * Copyright (c) 2011 Marius Strobl <marius at FreeBSD.org>
+ * 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 <sys/cdefs.h>
+__FBSDID("$FreeBSD: head/sys/sparc64/sparc64/cam_machdep.c 228022 2011-11-27 15:43:40Z marius $");
+
+#include <sys/param.h>
+#include <sys/systm.h>
+
+#include <cam/cam.h>
+#include <cam/cam_ccb.h>
+
+#include <machine/md_var.h>
+
+int
+scsi_da_bios_params(struct ccb_calc_geometry *ccg)
+{
+	uint32_t secs_per_cylinder, size_mb;
+
+	/*
+	 * The VTOC8 disk label only uses 16-bit fields for cylinders, heads
+	 * and sectors so the geometry of large disks has to be adjusted.
+	 * We generally use the sizing used by cam_calc_geometry(9), except
+	 * when it would overflow the cylinders, in which case we use 255
+	 * heads and sectors.  This allows disks up to the 2TB limit of the
+	 * extended VTOC8.
+	 * XXX this doesn't match the sizing used by OpenSolaris, as that
+	 * would exceed the 8-bit ccg->heads and ccg->secs_per_track.
+	 */
+	if (ccg->block_size == 0)
+		return (0);
+	size_mb = (1024L * 1024L) / ccg->block_size;
+	if (size_mb == 0)
+		return (0);
+	size_mb = ccg->volume_size / size_mb;
+	if (ccg->volume_size > (uint64_t)65535 * 255 * 63) {
+		ccg->heads = 255;
+		ccg->secs_per_track = 255;
+	} else if (size_mb > 1024) {
+		ccg->heads = 255;
+		ccg->secs_per_track = 63;
+	} else {
+		ccg->heads = 64;
+		ccg->secs_per_track = 32;
+	}
+	secs_per_cylinder = ccg->heads * ccg->secs_per_track;
+	if (secs_per_cylinder == 0)
+		return (0);
+	ccg->cylinders = ccg->volume_size / secs_per_cylinder;
+	return (1);
+}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/sparc64/sparc64/ofw_machdep.c
--- a/head/sys/sparc64/sparc64/ofw_machdep.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/sparc64/sparc64/ofw_machdep.c	Tue Dec 06 20:26:16 2011 +0200
@@ -25,7 +25,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/sys/sparc64/sparc64/ofw_machdep.c 228201 2011-12-02 15:24:39Z jchandra $");
 
 /*
  * Some Open Firmware helper functions that are likely machine dependent.
@@ -52,7 +52,7 @@
 	phandle_t node;
 	struct idprom idp;
 
-	if ((node = OF_finddevice("/options")) > 0 &&
+	if ((node = OF_finddevice("/options")) != -1 &&
 	    OF_getprop(node, "local-mac-address?", buf, sizeof(buf)) > 0) {
 		buf[sizeof(buf) - 1] = '\0';
 		if (strcmp(buf, "true") == 0 &&
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/sparc64/sparc64/vm_machdep.c
--- a/head/sys/sparc64/sparc64/vm_machdep.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/sparc64/sparc64/vm_machdep.c	Tue Dec 06 20:26:16 2011 +0200
@@ -39,7 +39,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/sparc64/sparc64/vm_machdep.c 223801 2011-07-05 18:55:56Z marius $");
+__FBSDID("$FreeBSD: head/sys/sparc64/sparc64/vm_machdep.c 228201 2011-12-02 15:24:39Z jchandra $");
 
 #include "opt_pmap.h"
 
@@ -368,7 +368,7 @@
 		(cell_t)bspec
 	};
 
-	if ((chosen = OF_finddevice("/chosen")) != 0) {
+	if ((chosen = OF_finddevice("/chosen")) != -1) {
 		if (OF_getprop(chosen, "bootpath", bspec, sizeof(bspec)) == -1)
 			bspec[0] = '\0';
 		bspec[sizeof(bspec) - 1] = '\0';
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/sys/resource.h
--- a/head/sys/sys/resource.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/sys/resource.h	Tue Dec 06 20:26:16 2011 +0200
@@ -27,7 +27,7 @@
  * SUCH DAMAGE.
  *
  *	@(#)resource.h	8.4 (Berkeley) 1/9/95
- * $FreeBSD$
+ * $FreeBSD: head/sys/sys/resource.h 227954 2011-11-24 20:37:09Z trociny $
  */
 
 #ifndef _SYS_RESOURCE_H_
@@ -108,7 +108,7 @@
  */
 
 #ifdef _RLIMIT_IDENT
-static char *rlimit_ident[RLIM_NLIMITS] = {
+static const char *rlimit_ident[RLIM_NLIMITS] = {
 	"cpu",
 	"fsize",
 	"data",
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/sys/sysctl.h
--- a/head/sys/sys/sysctl.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/sys/sysctl.h	Tue Dec 06 20:26:16 2011 +0200
@@ -30,7 +30,7 @@
  * SUCH DAMAGE.
  *
  *	@(#)sysctl.h	8.1 (Berkeley) 6/2/93
- * $FreeBSD: head/sys/sys/sysctl.h 227833 2011-11-22 20:40:18Z trociny $
+ * $FreeBSD: head/sys/sys/sysctl.h 228046 2011-11-27 21:01:51Z trociny $
  */
 
 #ifndef _SYS_SYSCTL_H_
@@ -561,6 +561,8 @@
 #define	KERN_PROC_GROUPS	34	/* process groups */
 #define	KERN_PROC_ENV		35	/* get environment */
 #define	KERN_PROC_AUXV		36	/* get ELF auxiliary vector */
+#define	KERN_PROC_RLIMIT	37	/* process resource limits */
+#define	KERN_PROC_PS_STRINGS	38	/* get ps_strings location */
 
 /*
  * KERN_IPC identifiers
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/sys/timeffc.h
--- a/head/sys/sys/timeffc.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/sys/timeffc.h	Tue Dec 06 20:26:16 2011 +0200
@@ -26,7 +26,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: head/sys/sys/timeffc.h 227776 2011-11-21 01:26:10Z lstewart $
+ * $FreeBSD: head/sys/sys/timeffc.h 228173 2011-12-01 07:19:13Z lstewart $
  */
 
 #ifndef _SYS_TIMEFF_H_
@@ -55,12 +55,19 @@
 #if __BSD_VISIBLE
 #ifdef _KERNEL
 
+/* Define the kern.sysclock sysctl tree. */
+SYSCTL_DECL(_kern_sysclock);
+
+/* Define the kern.sysclock.ffclock sysctl tree. */
+SYSCTL_DECL(_kern_sysclock_ffclock);
+
 /*
  * Index into the sysclocks array for obtaining the ASCII name of a particular
  * sysclock.
  */
 #define	SYSCLOCK_FBCK	0
 #define	SYSCLOCK_FFWD	1
+extern int sysclock_active;
 
 /*
  * Parameters of counter characterisation required by feed-forward algorithms.
@@ -164,6 +171,154 @@
 void ffclock_nanodifftime(ffcounter ffdelta, struct timespec *tsp);
 void ffclock_microdifftime(ffcounter ffdelta, struct timeval *tvp);
 
+/*
+ * When FFCLOCK is enabled in the kernel, [get]{bin,nano,micro}[up]time() become
+ * wrappers around equivalent feedback or feed-forward functions. Provide access
+ * outside of kern_tc.c to the feedback clock equivalent functions for
+ * specialised use i.e. these are not for general consumption.
+ */
+void fbclock_bintime(struct bintime *bt);
+void fbclock_nanotime(struct timespec *tsp);
+void fbclock_microtime(struct timeval *tvp);
+
+void fbclock_getbintime(struct bintime *bt);
+void fbclock_getnanotime(struct timespec *tsp);
+void fbclock_getmicrotime(struct timeval *tvp);
+
+void fbclock_binuptime(struct bintime *bt);
+void fbclock_nanouptime(struct timespec *tsp);
+void fbclock_microuptime(struct timeval *tvp);
+
+void fbclock_getbinuptime(struct bintime *bt);
+void fbclock_getnanouptime(struct timespec *tsp);
+void fbclock_getmicrouptime(struct timeval *tvp);
+
+/*
+ * Public system clock wrapper API which allows consumers to select which clock
+ * to obtain time from, independent of the current default system clock. These
+ * wrappers should be used instead of directly calling the underlying fbclock_
+ * or ffclock_ functions.
+ */
+static inline void
+bintime_fromclock(struct bintime *bt, int whichclock)
+{
+
+	if (whichclock == SYSCLOCK_FFWD)
+		ffclock_bintime(bt);
+	else
+		fbclock_bintime(bt);
+}
+
+static inline void
+nanotime_fromclock(struct timespec *tsp, int whichclock)
+{
+
+	if (whichclock == SYSCLOCK_FFWD)
+		ffclock_nanotime(tsp);
+	else
+		fbclock_nanotime(tsp);
+}
+
+static inline void
+microtime_fromclock(struct timeval *tvp, int whichclock)
+{
+
+	if (whichclock == SYSCLOCK_FFWD)
+		ffclock_microtime(tvp);
+	else
+		fbclock_microtime(tvp);
+}
+
+static inline void
+getbintime_fromclock(struct bintime *bt, int whichclock)
+{
+
+	if (whichclock == SYSCLOCK_FFWD)
+		ffclock_getbintime(bt);
+	else
+		fbclock_getbintime(bt);
+}
+
+static inline void
+getnanotime_fromclock(struct timespec *tsp, int whichclock)
+{
+
+	if (whichclock == SYSCLOCK_FFWD)
+		ffclock_getnanotime(tsp);
+	else
+		fbclock_getnanotime(tsp);
+}
+
+static inline void
+getmicrotime_fromclock(struct timeval *tvp, int whichclock)
+{
+
+	if (whichclock == SYSCLOCK_FFWD)
+		ffclock_getmicrotime(tvp);
+	else
+		fbclock_getmicrotime(tvp);
+}
+
+static inline void
+binuptime_fromclock(struct bintime *bt, int whichclock)
+{
+
+	if (whichclock == SYSCLOCK_FFWD)
+		ffclock_binuptime(bt);
+	else
+		fbclock_binuptime(bt);
+}
+
+static inline void
+nanouptime_fromclock(struct timespec *tsp, int whichclock)
+{
+
+	if (whichclock == SYSCLOCK_FFWD)
+		ffclock_nanouptime(tsp);
+	else
+		fbclock_nanouptime(tsp);
+}
+
+static inline void
+microuptime_fromclock(struct timeval *tvp, int whichclock)
+{
+
+	if (whichclock == SYSCLOCK_FFWD)
+		ffclock_microuptime(tvp);
+	else
+		fbclock_microuptime(tvp);
+}
+
+static inline void
+getbinuptime_fromclock(struct bintime *bt, int whichclock)
+{
+
+	if (whichclock == SYSCLOCK_FFWD)
+		ffclock_getbinuptime(bt);
+	else
+		fbclock_getbinuptime(bt);
+}
+
+static inline void
+getnanouptime_fromclock(struct timespec *tsp, int whichclock)
+{
+
+	if (whichclock == SYSCLOCK_FFWD)
+		ffclock_getnanouptime(tsp);
+	else
+		fbclock_getnanouptime(tsp);
+}
+
+static inline void
+getmicrouptime_fromclock(struct timeval *tvp, int whichclock)
+{
+
+	if (whichclock == SYSCLOCK_FFWD)
+		ffclock_getmicrouptime(tvp);
+	else
+		fbclock_getmicrouptime(tvp);
+}
+
 #else /* !_KERNEL */
 
 /* Feed-Forward Clock system calls. */
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/sys/umtx.h
--- a/head/sys/sys/umtx.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/sys/umtx.h	Tue Dec 06 20:26:16 2011 +0200
@@ -23,7 +23,7 @@
  * (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$
+ * $FreeBSD: head/sys/sys/umtx.h 228220 2011-12-03 12:33:17Z pho $
  *
  */
 
@@ -223,6 +223,7 @@
 	        k1->info.both.b == k2->info.both.b);
 }
 
+int umtx_copyin_timeout(const void *, struct timespec *);
 int umtx_key_get(void *, int, int, struct umtx_key *);
 void umtx_key_release(struct umtx_key *);
 struct umtx_q *umtxq_alloc(void);
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/vm/vm_page.c
--- a/head/sys/vm/vm_page.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/vm/vm_page.c	Tue Dec 06 20:26:16 2011 +0200
@@ -77,7 +77,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/vm/vm_page.c 227606 2011-11-17 06:54:49Z alc $");
+__FBSDID("$FreeBSD: head/sys/vm/vm_page.c 228287 2011-12-05 18:29:25Z alc $");
 
 #include "opt_vm.h"
 
@@ -1554,9 +1554,12 @@
 	    cnt.v_free_count + cnt.v_cache_count >= npages)) {
 #if VM_NRESERVLEVEL > 0
 retry:
+		if (object == NULL || (object->flags & OBJ_COLORED) == 0 ||
+		    (m_ret = vm_reserv_alloc_contig(object, pindex, npages,
+		    low, high, alignment, boundary)) == NULL)
 #endif
-		m_ret = vm_phys_alloc_contig(npages, low, high, alignment,
-		    boundary);
+			m_ret = vm_phys_alloc_contig(npages, low, high,
+			    alignment, boundary);
 	} else {
 		mtx_unlock(&vm_page_queue_free_mtx);
 		atomic_add_int(&vm_pageout_deficit, npages);
@@ -1581,8 +1584,8 @@
 		}
 	else {
 #if VM_NRESERVLEVEL > 0
-		if (vm_reserv_reclaim_contig(npages << PAGE_SHIFT, low, high,
-		    alignment, boundary))
+		if (vm_reserv_reclaim_contig(npages, low, high, alignment,
+		    boundary))
 			goto retry;
 #endif
 	}
@@ -2538,7 +2541,7 @@
 }
 
 /*
- *	vm_page_set_valid:
+ *	vm_page_set_valid_range:
  *
  *	Sets portions of a page valid.  The arguments are expected
  *	to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
@@ -2548,7 +2551,7 @@
  *	(base + size) must be less then or equal to PAGE_SIZE.
  */
 void
-vm_page_set_valid(vm_page_t m, int base, int size)
+vm_page_set_valid_range(vm_page_t m, int base, int size)
 {
 	int endoff, frag;
 
@@ -2581,7 +2584,7 @@
 	 * is already dirty. 
 	 */
 	KASSERT((~m->valid & vm_page_bits(base, size) & m->dirty) == 0,
-	    ("vm_page_set_valid: page %p is dirty", m)); 
+	    ("vm_page_set_valid_range: page %p is dirty", m));
 
 	/*
 	 * Set valid bits inclusive of any overlap.
@@ -2843,6 +2846,36 @@
 		vm_page_dirty(m);
 }
 
+void
+vm_page_lock_KBI(vm_page_t m, const char *file, int line)
+{
+
+	mtx_lock_flags_(vm_page_lockptr(m), 0, file, line);
+}
+
+void
+vm_page_unlock_KBI(vm_page_t m, const char *file, int line)
+{
+
+	mtx_unlock_flags_(vm_page_lockptr(m), 0, file, line);
+}
+
+int
+vm_page_trylock_KBI(vm_page_t m, const char *file, int line)
+{
+
+	return (mtx_trylock_flags_(vm_page_lockptr(m), 0, file, line));
+}
+
+#if defined(INVARIANTS) || defined(INVARIANT_SUPPORT)
+void
+vm_page_lock_assert_KBI(vm_page_t m, int a, const char *file, int line)
+{
+
+	mtx_assert_(vm_page_lockptr(m), a, file, line);
+}
+#endif
+
 int so_zerocp_fullpage = 0;
 
 /*
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/vm/vm_page.h
--- a/head/sys/vm/vm_page.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/vm/vm_page.h	Tue Dec 06 20:26:16 2011 +0200
@@ -57,7 +57,7 @@
  * any improvements or extensions that they make and grant Carnegie the
  * rights to redistribute these changes.
  *
- * $FreeBSD: head/sys/vm/vm_page.h 227568 2011-11-16 16:46:09Z alc $
+ * $FreeBSD: head/sys/vm/vm_page.h 228156 2011-11-30 17:39:00Z kib $
  */
 
 /*
@@ -218,11 +218,23 @@
 
 #define	PA_LOCK_ASSERT(pa, a)	mtx_assert(PA_LOCKPTR(pa), (a))
 
+#ifdef KLD_MODULE
+#define	vm_page_lock(m)		vm_page_lock_KBI((m), LOCK_FILE, LOCK_LINE)
+#define	vm_page_unlock(m)	vm_page_unlock_KBI((m), LOCK_FILE, LOCK_LINE)
+#define	vm_page_trylock(m)	vm_page_trylock_KBI((m), LOCK_FILE, LOCK_LINE)
+#if defined(INVARIANTS)
+#define	vm_page_lock_assert(m, a)		\
+    vm_page_lock_assert_KBI((m), (a), __FILE__, __LINE__)
+#else
+#define	vm_page_lock_assert(m, a)
+#endif
+#else	/* !KLD_MODULE */
 #define	vm_page_lockptr(m)	(PA_LOCKPTR(VM_PAGE_TO_PHYS((m))))
 #define	vm_page_lock(m)		mtx_lock(vm_page_lockptr((m)))
 #define	vm_page_unlock(m)	mtx_unlock(vm_page_lockptr((m)))
 #define	vm_page_trylock(m)	mtx_trylock(vm_page_lockptr((m)))
 #define	vm_page_lock_assert(m, a)	mtx_assert(vm_page_lockptr((m)), (a))
+#endif
 
 #define	vm_page_queue_free_mtx	vm_page_queue_free_lock.data
 /*
@@ -384,7 +396,7 @@
 void vm_page_remove (vm_page_t);
 void vm_page_rename (vm_page_t, vm_object_t, vm_pindex_t);
 void vm_page_requeue(vm_page_t m);
-void vm_page_set_valid(vm_page_t m, int base, int size);
+void vm_page_set_valid_range(vm_page_t m, int base, int size);
 void vm_page_sleep(vm_page_t m, const char *msg);
 vm_page_t vm_page_splay(vm_pindex_t, vm_page_t);
 vm_offset_t vm_page_startup(vm_offset_t vaddr);
@@ -405,6 +417,13 @@
 int vm_page_cowsetup(vm_page_t);
 void vm_page_cowclear (vm_page_t);
 
+void vm_page_lock_KBI(vm_page_t m, const char *file, int line);
+void vm_page_unlock_KBI(vm_page_t m, const char *file, int line);
+int vm_page_trylock_KBI(vm_page_t m, const char *file, int line);
+#if defined(INVARIANTS) || defined(INVARIANT_SUPPORT)
+void vm_page_lock_assert_KBI(vm_page_t m, int a, const char *file, int line);
+#endif
+
 #ifdef INVARIANTS
 void vm_page_object_lock_assert(vm_page_t m);
 #define	VM_PAGE_OBJECT_LOCK_ASSERT(m)	vm_page_object_lock_assert(m)
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/vm/vm_reserv.c
--- a/head/sys/vm/vm_reserv.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/vm/vm_reserv.c	Tue Dec 06 20:26:16 2011 +0200
@@ -31,10 +31,13 @@
 
 /*
  *	Superpage reservation management module
+ *
+ * Any external functions defined by this module are only to be used by the
+ * virtual memory system.
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/vm/vm_reserv.c 226928 2011-10-30 05:06:14Z alc $");
+__FBSDID("$FreeBSD: head/sys/vm/vm_reserv.c 228287 2011-12-05 18:29:25Z alc $");
 
 #include "opt_vm.h"
 
@@ -285,6 +288,201 @@
 }
 
 /*
+ * Allocates a contiguous set of physical pages of the given size "npages"
+ * from an existing or newly-created reservation.  All of the physical pages
+ * must be at or above the given physical address "low" and below the given
+ * physical address "high".  The given value "alignment" determines the
+ * alignment of the first physical page in the set.  If the given value
+ * "boundary" is non-zero, then the set of physical pages cannot cross any
+ * physical address boundary that is a multiple of that value.  Both
+ * "alignment" and "boundary" must be a power of two.
+ *
+ * The object and free page queue must be locked.
+ */
+vm_page_t
+vm_reserv_alloc_contig(vm_object_t object, vm_pindex_t pindex, u_long npages,
+    vm_paddr_t low, vm_paddr_t high, u_long alignment, vm_paddr_t boundary)
+{
+	vm_paddr_t pa, size;
+	vm_page_t m, m_ret, mpred, msucc;
+	vm_pindex_t first, leftcap, rightcap;
+	vm_reserv_t rv;
+	u_long allocpages, maxpages, minpages;
+	int i, index, n;
+
+	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
+	VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
+	KASSERT(npages != 0, ("vm_reserv_alloc_contig: npages is 0"));
+
+	/*
+	 * Is a reservation fundamentally impossible?
+	 */
+	if (pindex < VM_RESERV_INDEX(object, pindex) ||
+	    pindex + npages > object->size)
+		return (NULL);
+
+	/*
+	 * All reservations of a particular size have the same alignment.
+	 * Assuming that the first page is allocated from a reservation, the
+	 * least significant bits of its physical address can be determined
+	 * from its offset from the beginning of the reservation and the size
+	 * of the reservation.
+	 *
+	 * Could the specified index within a reservation of the smallest
+	 * possible size satisfy the alignment and boundary requirements?
+	 */
+	pa = VM_RESERV_INDEX(object, pindex) << PAGE_SHIFT;
+	if ((pa & (alignment - 1)) != 0)
+		return (NULL);
+	size = npages << PAGE_SHIFT;
+	if (((pa ^ (pa + size - 1)) & ~(boundary - 1)) != 0)
+		return (NULL);
+
+	/*
+	 * Look for an existing reservation.
+	 */
+	msucc = NULL;
+	mpred = object->root;
+	while (mpred != NULL) {
+		KASSERT(mpred->pindex != pindex,
+		    ("vm_reserv_alloc_contig: pindex already allocated"));
+		rv = vm_reserv_from_page(mpred);
+		if (rv->object == object && vm_reserv_has_pindex(rv, pindex))
+			goto found;
+		else if (mpred->pindex < pindex) {
+			if (msucc != NULL ||
+			    (msucc = TAILQ_NEXT(mpred, listq)) == NULL)
+				break;
+			KASSERT(msucc->pindex != pindex,
+		    ("vm_reserv_alloc_contig: pindex already allocated"));
+			rv = vm_reserv_from_page(msucc);
+			if (rv->object == object &&
+			    vm_reserv_has_pindex(rv, pindex))
+				goto found;
+			else if (pindex < msucc->pindex)
+				break;
+		} else if (msucc == NULL) {
+			msucc = mpred;
+			mpred = TAILQ_PREV(msucc, pglist, listq);
+			continue;
+		}
+		msucc = NULL;
+		mpred = object->root = vm_page_splay(pindex, object->root);
+	}
+
+	/*
+	 * Could at least one reservation fit between the first index to the
+	 * left that can be used and the first index to the right that cannot
+	 * be used?
+	 */
+	first = pindex - VM_RESERV_INDEX(object, pindex);
+	if (mpred != NULL) {
+		if ((rv = vm_reserv_from_page(mpred))->object != object)
+			leftcap = mpred->pindex + 1;
+		else
+			leftcap = rv->pindex + VM_LEVEL_0_NPAGES;
+		if (leftcap > first)
+			return (NULL);
+	}
+	minpages = VM_RESERV_INDEX(object, pindex) + npages;
+	maxpages = roundup2(minpages, VM_LEVEL_0_NPAGES);
+	allocpages = maxpages;
+	if (msucc != NULL) {
+		if ((rv = vm_reserv_from_page(msucc))->object != object)
+			rightcap = msucc->pindex;
+		else
+			rightcap = rv->pindex;
+		if (first + maxpages > rightcap) {
+			if (maxpages == VM_LEVEL_0_NPAGES)
+				return (NULL);
+			allocpages = minpages;
+		}
+	}
+
+	/*
+	 * Would the last new reservation extend past the end of the object?
+	 */
+	if (first + maxpages > object->size) {
+		/*
+		 * Don't allocate the last new reservation if the object is a
+		 * vnode or backed by another object that is a vnode. 
+		 */
+		if (object->type == OBJT_VNODE ||
+		    (object->backing_object != NULL &&
+		    object->backing_object->type == OBJT_VNODE)) {
+			if (maxpages == VM_LEVEL_0_NPAGES)
+				return (NULL);
+			allocpages = minpages;
+		}
+		/* Speculate that the object may grow. */
+	}
+
+	/*
+	 * Allocate and populate the new reservations.  The alignment and
+	 * boundary specified for this allocation may be different from the
+	 * alignment and boundary specified for the requested pages.  For
+	 * instance, the specified index may not be the first page within the
+	 * first new reservation.
+	 */
+	m = vm_phys_alloc_contig(allocpages, low, high, ulmax(alignment,
+	    VM_LEVEL_0_SIZE), boundary > VM_LEVEL_0_SIZE ? boundary : 0);
+	if (m == NULL)
+		return (NULL);
+	m_ret = NULL;
+	index = VM_RESERV_INDEX(object, pindex);
+	do {
+		rv = vm_reserv_from_page(m);
+		KASSERT(rv->pages == m,
+		    ("vm_reserv_alloc_contig: reserv %p's pages is corrupted",
+		    rv));
+		KASSERT(rv->object == NULL,
+		    ("vm_reserv_alloc_contig: reserv %p isn't free", rv));
+		LIST_INSERT_HEAD(&object->rvq, rv, objq);
+		rv->object = object;
+		rv->pindex = first;
+		KASSERT(rv->popcnt == 0,
+		    ("vm_reserv_alloc_contig: reserv %p's popcnt is corrupted",
+		    rv));
+		KASSERT(!rv->inpartpopq,
+		    ("vm_reserv_alloc_contig: reserv %p's inpartpopq is TRUE",
+		    rv));
+		n = ulmin(VM_LEVEL_0_NPAGES - index, npages);
+		for (i = 0; i < n; i++)
+			vm_reserv_populate(rv);
+		npages -= n;
+		if (m_ret == NULL) {
+			m_ret = &rv->pages[index];
+			index = 0;
+		}
+		m += VM_LEVEL_0_NPAGES;
+		first += VM_LEVEL_0_NPAGES;
+		allocpages -= VM_LEVEL_0_NPAGES;
+	} while (allocpages > VM_LEVEL_0_NPAGES);
+	return (m_ret);
+
+	/*
+	 * Found a matching reservation.
+	 */
+found:
+	index = VM_RESERV_INDEX(object, pindex);
+	/* Does the allocation fit within the reservation? */
+	if (index + npages > VM_LEVEL_0_NPAGES)
+		return (NULL);
+	m = &rv->pages[index];
+	pa = VM_PAGE_TO_PHYS(m);
+	if (pa < low || pa + size > high || (pa & (alignment - 1)) != 0 ||
+	    ((pa ^ (pa + size - 1)) & ~(boundary - 1)) != 0)
+		return (NULL);
+	/* Handle vm_page_rename(m, new_object, ...). */
+	for (i = 0; i < npages; i++)
+		if ((rv->pages[index + i].flags & (PG_CACHED | PG_FREE)) == 0)
+			return (NULL);
+	for (i = 0; i < npages; i++)
+		vm_reserv_populate(rv);
+	return (m);
+}
+
+/*
  * Allocates a page from an existing or newly-created reservation.
  *
  * The object and free page queue must be locked.
@@ -297,11 +495,11 @@
 	vm_reserv_t rv;
 
 	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
+	VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
 
 	/*
-	 * Is a reservation fundamentally not possible?
+	 * Is a reservation fundamentally impossible?
 	 */
-	VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
 	if (pindex < VM_RESERV_INDEX(object, pindex) ||
 	    pindex >= object->size)
 		return (NULL);
@@ -315,14 +513,9 @@
 		KASSERT(mpred->pindex != pindex,
 		    ("vm_reserv_alloc_page: pindex already allocated"));
 		rv = vm_reserv_from_page(mpred);
-		if (rv->object == object && vm_reserv_has_pindex(rv, pindex)) {
-			m = &rv->pages[VM_RESERV_INDEX(object, pindex)];
-			/* Handle vm_page_rename(m, new_object, ...). */
-			if ((m->flags & (PG_CACHED | PG_FREE)) == 0)
-				return (NULL);
-			vm_reserv_populate(rv);
-			return (m);
-		} else if (mpred->pindex < pindex) {
+		if (rv->object == object && vm_reserv_has_pindex(rv, pindex))
+			goto found;
+		else if (mpred->pindex < pindex) {
 			if (msucc != NULL ||
 			    (msucc = TAILQ_NEXT(mpred, listq)) == NULL)
 				break;
@@ -330,14 +523,9 @@
 			    ("vm_reserv_alloc_page: pindex already allocated"));
 			rv = vm_reserv_from_page(msucc);
 			if (rv->object == object &&
-			    vm_reserv_has_pindex(rv, pindex)) {
-				m = &rv->pages[VM_RESERV_INDEX(object, pindex)];
-				/* Handle vm_page_rename(m, new_object, ...). */
-				if ((m->flags & (PG_CACHED | PG_FREE)) == 0)
-					return (NULL);
-				vm_reserv_populate(rv);
-				return (m);
-			} else if (pindex < msucc->pindex)
+			    vm_reserv_has_pindex(rv, pindex))
+				goto found;
+			else if (pindex < msucc->pindex)
 				break;
 		} else if (msucc == NULL) {
 			msucc = mpred;
@@ -349,38 +537,31 @@
 	}
 
 	/*
-	 * Determine the first index to the left that can be used.
+	 * Could a reservation fit between the first index to the left that
+	 * can be used and the first index to the right that cannot be used?
 	 */
-	if (mpred == NULL)
-		leftcap = 0;
-	else if ((rv = vm_reserv_from_page(mpred))->object != object)
-		leftcap = mpred->pindex + 1;
-	else
-		leftcap = rv->pindex + VM_LEVEL_0_NPAGES;
+	first = pindex - VM_RESERV_INDEX(object, pindex);
+	if (mpred != NULL) {
+		if ((rv = vm_reserv_from_page(mpred))->object != object)
+			leftcap = mpred->pindex + 1;
+		else
+			leftcap = rv->pindex + VM_LEVEL_0_NPAGES;
+		if (leftcap > first)
+			return (NULL);
+	}
+	if (msucc != NULL) {
+		if ((rv = vm_reserv_from_page(msucc))->object != object)
+			rightcap = msucc->pindex;
+		else
+			rightcap = rv->pindex;
+		if (first + VM_LEVEL_0_NPAGES > rightcap)
+			return (NULL);
+	}
 
 	/*
-	 * Determine the first index to the right that cannot be used.
+	 * Would a new reservation extend past the end of the object? 
 	 */
-	if (msucc == NULL)
-		rightcap = pindex + VM_LEVEL_0_NPAGES;
-	else if ((rv = vm_reserv_from_page(msucc))->object != object)
-		rightcap = msucc->pindex;
-	else
-		rightcap = rv->pindex;
-
-	/*
-	 * Determine if a reservation fits between the first index to
-	 * the left that can be used and the first index to the right
-	 * that cannot be used. 
-	 */
-	first = pindex - VM_RESERV_INDEX(object, pindex);
-	if (first < leftcap || first + VM_LEVEL_0_NPAGES > rightcap)
-		return (NULL);
-
-	/*
-	 * Would a new reservation extend past the end of the given object? 
-	 */
-	if (object->size < first + VM_LEVEL_0_NPAGES) {
+	if (first + VM_LEVEL_0_NPAGES > object->size) {
 		/*
 		 * Don't allocate a new reservation if the object is a vnode or
 		 * backed by another object that is a vnode. 
@@ -393,28 +574,35 @@
 	}
 
 	/*
-	 * Allocate a new reservation.
+	 * Allocate and populate the new reservation.
 	 */
 	m = vm_phys_alloc_pages(VM_FREEPOOL_DEFAULT, VM_LEVEL_0_ORDER);
-	if (m != NULL) {
-		rv = vm_reserv_from_page(m);
-		KASSERT(rv->pages == m,
-		    ("vm_reserv_alloc_page: reserv %p's pages is corrupted",
-		    rv));
-		KASSERT(rv->object == NULL,
-		    ("vm_reserv_alloc_page: reserv %p isn't free", rv));
-		LIST_INSERT_HEAD(&object->rvq, rv, objq);
-		rv->object = object;
-		rv->pindex = first;
-		KASSERT(rv->popcnt == 0,
-		    ("vm_reserv_alloc_page: reserv %p's popcnt is corrupted",
-		    rv));
-		KASSERT(!rv->inpartpopq,
-		    ("vm_reserv_alloc_page: reserv %p's inpartpopq is TRUE",
-		    rv));
-		vm_reserv_populate(rv);
-		m = &rv->pages[VM_RESERV_INDEX(object, pindex)];
-	}
+	if (m == NULL)
+		return (NULL);
+	rv = vm_reserv_from_page(m);
+	KASSERT(rv->pages == m,
+	    ("vm_reserv_alloc_page: reserv %p's pages is corrupted", rv));
+	KASSERT(rv->object == NULL,
+	    ("vm_reserv_alloc_page: reserv %p isn't free", rv));
+	LIST_INSERT_HEAD(&object->rvq, rv, objq);
+	rv->object = object;
+	rv->pindex = first;
+	KASSERT(rv->popcnt == 0,
+	    ("vm_reserv_alloc_page: reserv %p's popcnt is corrupted", rv));
+	KASSERT(!rv->inpartpopq,
+	    ("vm_reserv_alloc_page: reserv %p's inpartpopq is TRUE", rv));
+	vm_reserv_populate(rv);
+	return (&rv->pages[VM_RESERV_INDEX(object, pindex)]);
+
+	/*
+	 * Found a matching reservation.
+	 */
+found:
+	m = &rv->pages[VM_RESERV_INDEX(object, pindex)];
+	/* Handle vm_page_rename(m, new_object, ...). */
+	if ((m->flags & (PG_CACHED | PG_FREE)) == 0)
+		return (NULL);
+	vm_reserv_populate(rv);
 	return (m);
 }
 
@@ -627,16 +815,17 @@
  * The free page queue lock must be held.
  */
 boolean_t
-vm_reserv_reclaim_contig(vm_paddr_t size, vm_paddr_t low, vm_paddr_t high,
+vm_reserv_reclaim_contig(u_long npages, vm_paddr_t low, vm_paddr_t high,
     u_long alignment, vm_paddr_t boundary)
 {
-	vm_paddr_t pa, pa_length;
+	vm_paddr_t pa, pa_length, size;
 	vm_reserv_t rv;
 	int i;
 
 	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
-	if (size > VM_LEVEL_0_SIZE - PAGE_SIZE)
+	if (npages > VM_LEVEL_0_NPAGES - 1)
 		return (FALSE);
+	size = npages << PAGE_SHIFT;
 	TAILQ_FOREACH(rv, &vm_rvq_partpop, partpopq) {
 		pa = VM_PAGE_TO_PHYS(&rv->pages[VM_LEVEL_0_NPAGES - 1]);
 		if (pa + PAGE_SIZE - size < low) {
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/vm/vm_reserv.h
--- a/head/sys/vm/vm_reserv.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/vm/vm_reserv.h	Tue Dec 06 20:26:16 2011 +0200
@@ -28,7 +28,7 @@
  * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  * POSSIBILITY OF SUCH DAMAGE.
  *
- * $FreeBSD: head/sys/vm/vm_reserv.h 226928 2011-10-30 05:06:14Z alc $
+ * $FreeBSD: head/sys/vm/vm_reserv.h 228287 2011-12-05 18:29:25Z alc $
  */
 
 /*
@@ -42,13 +42,19 @@
 
 #if VM_NRESERVLEVEL > 0
 
+/*
+ * The following functions are only to be used by the virtual memory system.
+ */
+vm_page_t	vm_reserv_alloc_contig(vm_object_t object, vm_pindex_t pindex,
+		    u_long npages, vm_paddr_t low, vm_paddr_t high,
+		    u_long alignment, vm_paddr_t boundary);
 vm_page_t	vm_reserv_alloc_page(vm_object_t object, vm_pindex_t pindex);
 void		vm_reserv_break_all(vm_object_t object);
 boolean_t	vm_reserv_free_page(vm_page_t m);
 void		vm_reserv_init(void);
 int		vm_reserv_level_iffullpop(vm_page_t m);
 boolean_t	vm_reserv_reactivate_page(vm_page_t m);
-boolean_t	vm_reserv_reclaim_contig(vm_paddr_t size, vm_paddr_t low,
+boolean_t	vm_reserv_reclaim_contig(u_long npages, vm_paddr_t low,
 		    vm_paddr_t high, u_long alignment, vm_paddr_t boundary);
 boolean_t	vm_reserv_reclaim_inactive(void);
 void		vm_reserv_rename(vm_page_t m, vm_object_t new_object,
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/vm/vnode_pager.c
--- a/head/sys/vm/vnode_pager.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/vm/vnode_pager.c	Tue Dec 06 20:26:16 2011 +0200
@@ -51,7 +51,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/vm/vnode_pager.c 227102 2011-11-05 08:20:32Z kib $");
+__FBSDID("$FreeBSD: head/sys/vm/vnode_pager.c 228156 2011-11-30 17:39:00Z kib $");
 
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -413,7 +413,7 @@
 			 * have been zeroed.  Some of these valid bits may
 			 * have already been set.
 			 */
-			vm_page_set_valid(m, base, size);
+			vm_page_set_valid_range(m, base, size);
 
 			/*
 			 * Round "base" to the next block boundary so that the
@@ -964,7 +964,7 @@
 			 * we just try to clear the piece that we couldn't
 			 * read.
 			 */
-			vm_page_set_valid(mt, 0,
+			vm_page_set_valid_range(mt, 0,
 			    object->un_pager.vnp.vnp_size - tfoff);
 			KASSERT((mt->dirty & vm_page_bits(0,
 			    object->un_pager.vnp.vnp_size - tfoff)) == 0,
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/x86/acpica/acpi_apm.c
--- a/head/sys/x86/acpica/acpi_apm.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/x86/acpica/acpi_apm.c	Tue Dec 06 20:26:16 2011 +0200
@@ -25,7 +25,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/sys/x86/acpica/acpi_apm.c 227293 2011-11-07 06:44:47Z ed $");
+__FBSDID("$FreeBSD: head/sys/x86/acpica/acpi_apm.c 228283 2011-12-05 16:08:18Z ed $");
 
 #include <sys/param.h>
 #include <sys/bus.h>
@@ -51,12 +51,10 @@
 #define	APM_UNKNOWN	0xff
 
 static int apm_active;
-static struct clonedevs *apm_clones;
 
 static MALLOC_DEFINE(M_APMDEV, "apmdev", "APM device emulation");
 
 static d_open_t		apmopen;
-static d_close_t	apmclose;
 static d_write_t	apmwrite;
 static d_ioctl_t	apmioctl;
 static d_poll_t		apmpoll;
@@ -71,9 +69,7 @@
 
 static struct cdevsw apm_cdevsw = {
 	.d_version =	D_VERSION,
-	.d_flags =	D_TRACKCLOSE | D_NEEDMINOR,
 	.d_open =	apmopen,
-	.d_close =	apmclose,
 	.d_write =	apmwrite,
 	.d_ioctl =	apmioctl,
 	.d_poll =	apmpoll,
@@ -202,39 +198,6 @@
 	return (0);
 }
 
-/* Create single-use devices for /dev/apm and /dev/apmctl. */
-static void
-apm_clone(void *arg, struct ucred *cred, char *name, int namelen,
-    struct cdev **dev)
-{
-	int ctl_dev, unit;
-
-	if (*dev != NULL)
-		return;
-	if (strcmp(name, "apmctl") == 0)
-		ctl_dev = TRUE;
-	else if (strcmp(name, "apm") == 0)
-		ctl_dev = FALSE;
-	else
-		return;
-
-	/* Always create a new device and unit number. */
-	unit = -1;
-	if (clone_create(&apm_clones, &apm_cdevsw, &unit, dev, 0)) {
-		if (ctl_dev) {
-			*dev = make_dev(&apm_cdevsw, unit,
-			    UID_ROOT, GID_OPERATOR, 0660, "apmctl%d", unit);
-		} else {
-			*dev = make_dev(&apm_cdevsw, unit,
-			    UID_ROOT, GID_OPERATOR, 0664, "apm%d", unit);
-		}
-		if (*dev != NULL) {
-			dev_ref(*dev);
-			(*dev)->si_flags |= SI_CHEAPCLONE;
-		}
-	}
-}
-
 /* Create a struct for tracking per-device suspend notification. */
 static struct apm_clone_data *
 apm_create_clone(struct cdev *dev, struct acpi_softc *acpi_sc)
@@ -263,30 +226,13 @@
 	return (clone);
 }
 
-static int
-apmopen(struct cdev *dev, int flag, int fmt, struct thread *td)
-{
-	struct	acpi_softc *acpi_sc;
-	struct 	apm_clone_data *clone;
-
-	acpi_sc = devclass_get_softc(devclass_find("acpi"), 0);
-	clone = apm_create_clone(dev, acpi_sc);
-	dev->si_drv1 = clone;
-
-	/* If the device is opened for write, record that. */
-	if ((flag & FWRITE) != 0)
-		clone->flags |= ACPI_EVF_WRITE;
-
-	return (0);
-}
-
-static int
-apmclose(struct cdev *dev, int flag, int fmt, struct thread *td)
+static void
+apmdtor(void *data)
 {
 	struct	apm_clone_data *clone;
 	struct	acpi_softc *acpi_sc;
 
-	clone = dev->si_drv1;
+	clone = data;
 	acpi_sc = clone->acpi_sc;
 
 	/* We are about to lose a reference so check if suspend should occur */
@@ -301,7 +247,22 @@
 	knlist_destroy(&clone->sel_read.si_note);
 	ACPI_UNLOCK(acpi);
 	free(clone, M_APMDEV);
-	destroy_dev_sched(dev);
+}
+
+static int
+apmopen(struct cdev *dev, int flag, int fmt, struct thread *td)
+{
+	struct	acpi_softc *acpi_sc;
+	struct 	apm_clone_data *clone;
+
+	acpi_sc = devclass_get_softc(devclass_find("acpi"), 0);
+	clone = apm_create_clone(dev, acpi_sc);
+	devfs_set_cdevpriv(clone, apmdtor);
+
+	/* If the device is opened for write, record that. */
+	if ((flag & FWRITE) != 0)
+		clone->flags |= ACPI_EVF_WRITE;
+
 	return (0);
 }
 
@@ -316,7 +277,7 @@
 	apm_info_old_t aiop;
 
 	error = 0;
-	clone = dev->si_drv1;
+	devfs_get_cdevpriv((void **)&clone);
 	acpi_sc = clone->acpi_sc;
 
 	switch (cmd) {
@@ -430,8 +391,8 @@
 	int revents;
 
 	revents = 0;
+	devfs_get_cdevpriv((void **)&clone);
 	ACPI_LOCK(acpi);
-	clone = dev->si_drv1;
 	if (clone->acpi_sc->acpi_next_sstate)
 		revents |= events & (POLLIN | POLLRDNORM);
 	else
@@ -445,8 +406,8 @@
 {
 	struct	apm_clone_data *clone;
 
+	devfs_get_cdevpriv((void **)&clone);
 	ACPI_LOCK(acpi);
-	clone = dev->si_drv1;
 	kn->kn_hook = clone;
 	kn->kn_fop = &apm_readfiltops;
 	knlist_add(&clone->sel_read.si_note, kn, 0);
@@ -485,6 +446,7 @@
 	/* Create a clone for /dev/acpi also. */
 	STAILQ_INIT(&sc->apm_cdevs);
 	sc->acpi_clone = apm_create_clone(sc->acpi_dev_t, sc);
-	clone_setup(&apm_clones);
-	EVENTHANDLER_REGISTER(dev_clone, apm_clone, 0, 1000);
+
+	make_dev(&apm_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0660, "apmctl");
+	make_dev(&apm_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0664, "apm");
 }
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/sys/xen/evtchn/evtchn_dev.c
--- a/head/sys/xen/evtchn/evtchn_dev.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/sys/xen/evtchn/evtchn_dev.c	Tue Dec 06 20:26:16 2011 +0200
@@ -7,7 +7,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/sys/xen/evtchn/evtchn_dev.c 228162 2011-11-30 18:52:30Z jhb $");
 
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -318,15 +318,14 @@
 }
 
 static struct cdevsw evtchn_devsw = {
-	d_version:   D_VERSION,
-	d_open:      evtchn_open,
-	d_close:     evtchn_close,
-	d_read:      evtchn_read,
-	d_write:     evtchn_write,
-	d_ioctl:     evtchn_ioctl,
-	d_poll:      evtchn_poll,
-	d_name:      "evtchn",
-	d_flags:     0,
+	.d_version =	D_VERSION,
+	.d_open =	evtchn_open,
+	.d_close =	evtchn_close,
+	.d_read =	evtchn_read,
+	.d_write =	evtchn_write,
+	.d_ioctl =	evtchn_ioctl,
+	.d_poll =	evtchn_poll,
+	.d_name =	"evtchn",
 };
 
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/build/options/WITHOUT_GPIO
--- a/head/tools/build/options/WITHOUT_GPIO	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/build/options/WITHOUT_GPIO	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-.\" $FreeBSD$
+.\" $FreeBSD: head/tools/build/options/WITHOUT_GPIO 228081 2011-11-28 17:54:34Z dim $
 Set to not build
 .Xr gpioctl 8
 as part of the base system.
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/build/options/WITHOUT_PROFILE
--- a/head/tools/build/options/WITHOUT_PROFILE	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/build/options/WITHOUT_PROFILE	Tue Dec 06 20:26:16 2011 +0200
@@ -1,2 +1,2 @@
-.\" $FreeBSD$
+.\" $FreeBSD: head/tools/build/options/WITHOUT_PROFILE 228196 2011-12-02 09:09:54Z fjoe $
 Set to avoid compiling profiled libraries.
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/build/options/WITH_CTF
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/tools/build/options/WITH_CTF	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,4 @@
+.\" $FreeBSD: head/tools/build/options/WITH_CTF 228159 2011-11-30 18:22:44Z fjoe $
+Set to compile with CTF (Compact C Type Format) data.
+CTF data encapsulates a reduced form of debugging information
+similar to DWARF and the venerable stabs and is required for DTrace.
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/build/options/WITH_LIBCPLUSPLUS
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/tools/build/options/WITH_LIBCPLUSPLUS	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,2 @@
+.\" $FreeBSD: head/tools/build/options/WITH_LIBCPLUSPLUS 228082 2011-11-28 17:56:46Z dim $
+Set to build libcxxrt and libc++.
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/build/options/WITH_OFED
--- a/head/tools/build/options/WITH_OFED	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/build/options/WITH_OFED	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-.\" $FreeBSD$
+.\" $FreeBSD: head/tools/build/options/WITH_OFED 228081 2011-11-28 17:54:34Z dim $
 Set to build the
 .Dq "OpenFabrics Enterprise Distribution"
 Infiniband software stack.
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/regression/bin/sh/builtins/case11.0
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/tools/regression/bin/sh/builtins/case11.0	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,6 @@
+# $FreeBSD: head/tools/regression/bin/sh/builtins/case11.0 228007 2011-11-26 22:28:25Z jilles $
+
+false
+case x in
+*)
+esac
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/regression/bin/sh/builtins/case12.0
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/tools/regression/bin/sh/builtins/case12.0	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,6 @@
+# $FreeBSD: head/tools/regression/bin/sh/builtins/case12.0 228007 2011-11-26 22:28:25Z jilles $
+
+false
+case x in
+y)
+esac
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/regression/bin/test/regress.sh
--- a/head/tools/regression/bin/test/regress.sh	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/regression/bin/test/regress.sh	Tue Dec 06 20:26:16 2011 +0200
@@ -28,7 +28,7 @@
 #
 # TEST.sh - check if test(1) or builtin test works
 #
-# $FreeBSD$
+# $FreeBSD: head/tools/regression/bin/test/regress.sh 228109 2011-11-28 23:10:53Z jilles $
 
 # force a specified test program, e.g. `env test=/bin/test sh regress.sh'
 : ${test=test}		
@@ -52,7 +52,7 @@
 }
 
 count=0
-echo "1..97"
+echo "1..130"
 
 t 0 'b = b' 
 t 0 'b == b' 
@@ -138,8 +138,6 @@
 t 0 '! != -n'
 t 0 '! -c /etc/passwd'
 
-t 0 '! \( = \)'
-t 1 '! \( != \)'
 t 1 '! = = ='
 t 0 '! = = \)'
 t 0 '! "" -o ""'
@@ -147,7 +145,6 @@
 t 1 '! "" -o "x"'
 t 1 '! "x" -o "x"'
 t 0 '\( -f /etc/passwd \)'
-t 1 '\( ! = \)'
 t 0 '\( ! "" \)'
 t 1 '\( ! -e \)'
 
@@ -160,3 +157,40 @@
 t 0 '0 -ne 0 -o ! -f /'
 t 0 '1 -ne 0 -o ! -f /etc/passwd'
 t 1 '0 -ne 0 -o ! -f /etc/passwd'
+
+t 0 '-n ='
+t 1 '-z ='
+t 1 '! ='
+t 0 '-n -eq'
+t 1 '-z -eq'
+t 1 '! -eq'
+t 0 '-n -a'
+t 1 '-z -a'
+t 1 '! -a'
+t 0 '-n -o'
+t 1 '-z -o'
+t 1 '! -o'
+t 1 '! -n ='
+t 0 '! -z ='
+t 0 '! ! ='
+t 1 '! -n -eq'
+t 0 '! -z -eq'
+t 0 '! ! -eq'
+t 1 '! -n -a'
+t 0 '! -z -a'
+t 0 '! ! -a'
+t 1 '! -n -o'
+t 0 '! -z -o'
+t 0 '! ! -o'
+t 0 '\( -n = \)'
+t 1 '\( -z = \)'
+t 1 '\( ! = \)'
+t 0 '\( -n -eq \)'
+t 1 '\( -z -eq \)'
+t 1 '\( ! -eq \)'
+t 0 '\( -n -a \)'
+t 1 '\( -z -a \)'
+t 1 '\( ! -a \)'
+t 0 '\( -n -o \)'
+t 1 '\( -z -o \)'
+t 1 '\( ! -o \)'
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/regression/pipe/pipe-fstatbug.c
--- a/head/tools/regression/pipe/pipe-fstatbug.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/regression/pipe/pipe-fstatbug.c	Tue Dec 06 20:26:16 2011 +0200
@@ -28,7 +28,7 @@
 #include <sys/stat.h>
 
 /*
- * $FreeBSD$
+ * $FreeBSD: head/tools/regression/pipe/pipe-fstatbug.c 228274 2011-12-05 04:20:13Z eadler $
  * The goal of this program is to see if fstat reports the correct
  * data count for a pipe.  Prior to revision 1.172 of sys_pipe.c,
  * 0 would be returned once the pipe entered direct write mode.
@@ -41,7 +41,7 @@
 {
 char buffer[32768], buffer2[32768];
 int desc[2];
-int error, successes;
+int error, successes = 0;
 struct stat status;
 pid_t new_pid;
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/regression/pipe/pipe-ino.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/tools/regression/pipe/pipe-ino.c	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,66 @@
+/*-
+ * Copyright (c) 2011 Giovanni Trematerra <giovanni.trematerra at gmail.com>
+ * 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: head/tools/regression/pipe/pipe-ino.c 228177 2011-12-01 11:20:25Z kib $
+ * Test conformance to stat(2) SUSv4 description:
+ *  "For all other file types defined in this volume of POSIX.1-2008, the
+ *  structure members st_mode, st_ino, st_dev, st_uid, st_gid, st_atim,
+ *  st_ctim, and st_mtim shall have meaningful values ...".
+ * Check that st_dev and st_ino are meaningful.
+ */
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <err.h>
+#include <stdio.h>
+#include <unistd.h>
+
+int
+main(int argc, char **argv)
+{
+	int pipefd[2];
+	struct stat st1, st2;
+
+	if (pipe(pipefd) == -1)
+		err(1, "FAIL: pipe");
+
+	if (fstat(pipefd[0], &st1) == -1)
+		err(1, "FAIL: fstat st1");
+	if (fstat(pipefd[1], &st2) == -1)
+		err(1, "FAIL: fstat st2");
+	if (st1.st_dev != st2.st_dev || st1.st_dev == 0 || st2.st_dev == 0) {
+		errx(1, "FAIL: wrong dev number %d %d",
+		    st1.st_dev, st2.st_dev);
+	}
+	if (st1.st_ino == st2.st_ino)
+		errx(1, "FAIL: inode numbers are equal: %d", st1.st_ino);
+	close(pipefd[0]);
+	close(pipefd[1]);
+	printf("PASS\n");
+
+	return (0);
+}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/regression/pipe/pipe-reverse.c
--- a/head/tools/regression/pipe/pipe-reverse.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/regression/pipe/pipe-reverse.c	Tue Dec 06 20:26:16 2011 +0200
@@ -28,7 +28,7 @@
 #include <sys/stat.h>
 
 /*
- * $FreeBSD$
+ * $FreeBSD: head/tools/regression/pipe/pipe-reverse.c 228274 2011-12-05 04:20:13Z eadler $
  * This program simply tests writing through the reverse direction of
  * a pipe.  Nothing too fancy, it's only needed because most pipe-using
  * programs never touch the reverse direction (it doesn't exist on
@@ -44,6 +44,7 @@
 pid_t new_pid;
 
 buggy = 0;
+total = 0;
 
 error = pipe(desc);
 
@@ -52,7 +53,7 @@
 
 buffer[0] = 'A';
 
-for (i = 0; i < 65535; i++) {
+for (i = 1; i < 65535; i++) {
 	buffer[i] = buffer[i - 1] + 1;
 	if (buffer[i] > 'Z')
 		buffer[i] = 'A';
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/regression/pipe/pipe-wraparound.c
--- a/head/tools/regression/pipe/pipe-wraparound.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/regression/pipe/pipe-wraparound.c	Tue Dec 06 20:26:16 2011 +0200
@@ -28,7 +28,7 @@
 #include <sys/stat.h>
 
 /*
- * $FreeBSD$
+ * $FreeBSD: head/tools/regression/pipe/pipe-wraparound.c 228274 2011-12-05 04:20:13Z eadler $
  * This program tests to make sure that wraparound writes and reads
  * are working, assuming that 16K socket buffers are used.  In order
  * to really stress the pipe code with this test, kernel modifications
@@ -44,6 +44,7 @@
 pid_t new_pid;
 
 buggy = 0;
+total = 0;
 
 error = pipe(desc);
 
@@ -52,7 +53,7 @@
 
 buffer[0] = 'A';
 
-for (i = 0; i < 32768; i++) {
+for (i = 1; i < 32768; i++) {
 	buffer[i] = buffer[i - 1] + 1;
 	if (buffer[i] > 'Z')
 		buffer[i] = 'A';
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/regression/sbin/Makefile
--- a/head/tools/regression/sbin/Makefile	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/regression/sbin/Makefile	Tue Dec 06 20:26:16 2011 +0200
@@ -1,5 +1,5 @@
-# $FreeBSD$
+# $FreeBSD: head/tools/regression/sbin/Makefile 228259 2011-12-04 14:44:31Z dumbbell $
 
-SUBDIR=	growfs
+SUBDIR=	dhclient growfs
 
 .include <bsd.subdir.mk>
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/regression/sbin/dhclient/Makefile
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/tools/regression/sbin/dhclient/Makefile	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,16 @@
+# $FreeBSD: head/tools/regression/sbin/dhclient/Makefile 228259 2011-12-04 14:44:31Z dumbbell $
+
+.PATH:	${.CURDIR}/../../../../sbin/dhclient
+
+SRCS=	alloc.c convert.c hash.c options.c tables.c			\
+	fake.c								\
+	option-domain-search.c
+
+CFLAGS+= -I${.CURDIR}/../../../../sbin/dhclient
+LDADD=	-lutil
+
+PROG=	option-domain-search
+
+WARNS?=	2
+
+.include <bsd.prog.mk>
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/regression/sbin/dhclient/fake.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/tools/regression/sbin/dhclient/fake.c	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,60 @@
+/* $FreeBSD: head/tools/regression/sbin/dhclient/fake.c 228259 2011-12-04 14:44:31Z dumbbell $ */
+
+#include <setjmp.h>
+#include <stdarg.h>
+#include <stdio.h>
+
+#include "dhcpd.h"
+
+extern jmp_buf env;
+
+void
+error(char *fmt, ...)
+{
+	va_list ap;
+
+	va_start(ap, fmt);
+	vfprintf(stderr, fmt, ap);
+	va_end(ap);
+	fprintf(stderr, "\n");
+
+	longjmp(env, 1);
+}
+
+int
+warning(char *fmt, ...)
+{
+	int ret;
+	va_list ap;
+
+	va_start(ap, fmt);
+	ret = vfprintf(stderr, fmt, ap);
+	va_end(ap);
+	fprintf(stderr, "\n");
+
+	return ret;
+}
+
+int
+note(char *fmt, ...)
+{
+	int ret;
+	va_list ap;
+
+	va_start(ap, fmt);
+	ret = vfprintf(stderr, fmt, ap);
+	va_end(ap);
+	fprintf(stderr, "\n");
+
+	return ret;
+}
+
+void
+bootp(struct packet *packet)
+{
+}
+
+void
+dhcp(struct packet *packet)
+{
+}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/regression/sbin/dhclient/option-domain-search.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/tools/regression/sbin/dhclient/option-domain-search.c	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,328 @@
+/* $FreeBSD: head/tools/regression/sbin/dhclient/option-domain-search.c 228259 2011-12-04 14:44:31Z dumbbell $ */
+
+#include <setjmp.h>
+#include <stdlib.h>
+
+#include "dhcpd.h"
+
+jmp_buf env;
+
+void	expand_domain_search(struct packet *packet);
+
+void
+no_option_present()
+{
+	int ret;
+	struct option_data option;
+	struct packet p;
+
+	option.data = NULL;
+	option.len  = 0;
+	p.options[DHO_DOMAIN_SEARCH] = option;
+
+	ret = setjmp(env);
+	if (ret == 0)
+		expand_domain_search(&p);
+
+	if (p.options[DHO_DOMAIN_SEARCH].len != 0 ||
+	    p.options[DHO_DOMAIN_SEARCH].data != NULL)
+		abort();
+}
+
+void
+one_domain_valid()
+{
+	int ret;
+	struct packet p;
+	struct option_data *option;
+
+	char *data     = "\007example\003org\0";
+	char *expected = "example.org.";
+
+	option = &p.options[DHO_DOMAIN_SEARCH];
+	option->len  = 13;
+	option->data = malloc(option->len);
+	memcpy(option->data, data, option->len);
+
+	ret = setjmp(env);
+	if (ret == 0)
+		expand_domain_search(&p);
+
+	if (option->len != strlen(expected) ||
+	    strcmp(option->data, expected) != 0)
+		abort();
+
+	free(option->data);
+}
+
+void
+one_domain_truncated1()
+{
+	int ret;
+	struct option_data *option;
+	struct packet p;
+
+	char *data = "\007example\003org";
+
+	option = &p.options[DHO_DOMAIN_SEARCH];
+	option->len  = 12;
+	option->data = malloc(option->len);
+	memcpy(option->data, data, option->len);
+
+	ret = setjmp(env);
+	if (ret == 0)
+		expand_domain_search(&p);
+
+	if (ret != 1)
+		abort();
+
+	free(option->data);
+}
+
+void
+one_domain_truncated2()
+{
+	int ret;
+	struct option_data *option;
+	struct packet p;
+
+	char *data = "\007ex";
+
+	option = &p.options[DHO_DOMAIN_SEARCH];
+	option->len  = 3;
+	option->data = malloc(option->len);
+	memcpy(option->data, data, option->len);
+
+	ret = setjmp(env);
+	if (ret == 0)
+		expand_domain_search(&p);
+
+	if (ret != 1)
+		abort();
+
+	free(option->data);
+}
+
+void
+two_domains_valid()
+{
+	int ret;
+	struct packet p;
+	struct option_data *option;
+
+	char *data     = "\007example\003org\0\007example\003com\0";
+	char *expected = "example.org. example.com.";
+
+	option = &p.options[DHO_DOMAIN_SEARCH];
+	option->len  = 26;
+	option->data = malloc(option->len);
+	memcpy(option->data, data, option->len);
+
+	ret = setjmp(env);
+	if (ret == 0)
+		expand_domain_search(&p);
+
+	if (option->len != strlen(expected) ||
+	    strcmp(option->data, expected) != 0)
+		abort();
+
+	free(option->data);
+}
+
+void
+two_domains_truncated1()
+{
+	int ret;
+	struct option_data *option;
+	struct packet p;
+
+	char *data = "\007example\003org\0\007example\003com";
+
+	option = &p.options[DHO_DOMAIN_SEARCH];
+	option->len  = 25;
+	option->data = malloc(option->len);
+	memcpy(option->data, data, option->len);
+
+	ret = setjmp(env);
+	if (ret == 0)
+		expand_domain_search(&p);
+
+	if (ret != 1)
+		abort();
+
+	free(option->data);
+}
+
+void
+two_domains_truncated2()
+{
+	int ret;
+	struct option_data *option;
+	struct packet p;
+
+	char *data = "\007example\003org\0\007ex";
+
+	option = &p.options[DHO_DOMAIN_SEARCH];
+	option->len  = 16;
+	option->data = malloc(option->len);
+	memcpy(option->data, data, option->len);
+
+	ret = setjmp(env);
+	if (ret == 0)
+		expand_domain_search(&p);
+
+	if (ret != 1)
+		abort();
+
+	free(option->data);
+}
+
+void
+two_domains_compressed()
+{
+	int ret;
+	struct packet p;
+	struct option_data *option;
+
+	char *data     = "\007example\003org\0\006foobar\xc0\x08";
+	char *expected = "example.org. foobar.org.";
+
+	option = &p.options[DHO_DOMAIN_SEARCH];
+	option->len  = 22;
+	option->data = malloc(option->len);
+	memcpy(option->data, data, option->len);
+
+	ret = setjmp(env);
+	if (ret == 0)
+		expand_domain_search(&p);
+
+	if (option->len != strlen(expected) ||
+	    strcmp(option->data, expected) != 0)
+		abort();
+
+	free(option->data);
+}
+
+void
+two_domains_infloop()
+{
+	int ret;
+	struct packet p;
+	struct option_data *option;
+
+	char *data = "\007example\003org\0\006foobar\xc0\x0d";
+
+	option = &p.options[DHO_DOMAIN_SEARCH];
+	option->len  = 22;
+	option->data = malloc(option->len);
+	memcpy(option->data, data, option->len);
+
+	ret = setjmp(env);
+	if (ret == 0)
+		expand_domain_search(&p);
+
+	if (ret != 1)
+		abort();
+
+	free(option->data);
+}
+
+void
+two_domains_forwardptr()
+{
+	int ret;
+	struct packet p;
+	struct option_data *option;
+
+	char *data = "\007example\003org\xc0\x0d\006foobar\0";
+
+	option = &p.options[DHO_DOMAIN_SEARCH];
+	option->len  = 22;
+	option->data = malloc(option->len);
+	memcpy(option->data, data, option->len);
+
+	ret = setjmp(env);
+	if (ret == 0)
+		expand_domain_search(&p);
+
+	if (ret != 1)
+		abort();
+
+	free(option->data);
+}
+
+void
+two_domains_truncatedptr()
+{
+	int ret;
+	struct packet p;
+	struct option_data *option;
+
+	char *data = "\007example\003org\0\006foobar\xc0";
+
+	option = &p.options[DHO_DOMAIN_SEARCH];
+	option->len  = 21;
+	option->data = malloc(option->len);
+	memcpy(option->data, data, option->len);
+
+	ret = setjmp(env);
+	if (ret == 0)
+		expand_domain_search(&p);
+
+	if (ret != 1)
+		abort();
+
+	free(option->data);
+}
+
+void
+multiple_domains_valid()
+{
+	int ret;
+	struct packet p;
+	struct option_data *option;
+
+	char *data =
+	    "\007example\003org\0\002cl\006foobar\003com\0\002fr\xc0\x10";
+
+	char *expected = "example.org. cl.foobar.com. fr.foobar.com.";
+
+	option = &p.options[DHO_DOMAIN_SEARCH];
+	option->len  = 33;
+	option->data = malloc(option->len);
+	memcpy(option->data, data, option->len);
+
+	ret = setjmp(env);
+	if (ret == 0)
+		expand_domain_search(&p);
+
+	if (option->len != strlen(expected) ||
+	    strcmp(option->data, expected) != 0)
+		abort();
+
+	free(option->data);
+}
+
+int
+main(int argc, char *argv[])
+{
+
+	no_option_present();
+
+	one_domain_valid();
+	one_domain_truncated1();
+	one_domain_truncated2();
+
+	two_domains_valid();
+	two_domains_truncated1();
+	two_domains_truncated2();
+
+	two_domains_compressed();
+	two_domains_infloop();
+	two_domains_forwardptr();
+	two_domains_truncatedptr();
+
+	multiple_domains_valid();
+
+	return (0);
+}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/regression/usr.bin/make/execution/ellipsis/Makefile
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/tools/regression/usr.bin/make/execution/ellipsis/Makefile	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,21 @@
+# $FreeBSD: head/tools/regression/usr.bin/make/execution/ellipsis/Makefile 228149 2011-11-30 05:49:17Z fjoe $
+
+ELLIPSIS=	...
+
+check-ellipsis:
+	@${MAKE} -f ${MAKEFILE} do-$@
+	@${MAKE} -f ${MAKEFILE} -j2 do-$@
+	@${MAKE} -f ${MAKEFILE} -j2 -B do-$@
+
+do-check-ellipsis: do-check-ellipsis-1 do-check-ellipsis-2
+.ORDER: do-check-ellipsis-1 do-check-ellipsis-2
+
+do-check-ellipsis-1:
+	@echo before $@
+	${ELLIPSIS}
+	@echo after $@
+
+do-check-ellipsis-2:
+	@echo before $@
+	${ELLIPSIS}
+	@echo after $@
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/regression/usr.bin/make/execution/ellipsis/expected.status.1
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/tools/regression/usr.bin/make/execution/ellipsis/expected.status.1	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,1 @@
+0
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/regression/usr.bin/make/execution/ellipsis/expected.stdout.1
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/tools/regression/usr.bin/make/execution/ellipsis/expected.stdout.1	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,12 @@
+before do-check-ellipsis-1
+before do-check-ellipsis-2
+after do-check-ellipsis-1
+after do-check-ellipsis-2
+before do-check-ellipsis-1
+before do-check-ellipsis-2
+after do-check-ellipsis-1
+after do-check-ellipsis-2
+before do-check-ellipsis-1
+before do-check-ellipsis-2
+after do-check-ellipsis-1
+after do-check-ellipsis-2
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/regression/usr.bin/make/execution/ellipsis/test.t
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/tools/regression/usr.bin/make/execution/ellipsis/test.t	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,15 @@
+#!/bin/sh
+
+# $FreeBSD: head/tools/regression/usr.bin/make/execution/ellipsis/test.t 228149 2011-11-30 05:49:17Z fjoe $
+
+cd `dirname $0`
+. ../../common.sh
+
+# Description
+DESC="Ellipsis command from variable"
+
+# Run
+TEST_N=1
+TEST_1=
+
+eval_cmd $*
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/regression/usr.bin/make/execution/empty/Makefile
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/tools/regression/usr.bin/make/execution/empty/Makefile	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,13 @@
+# $FreeBSD: head/tools/regression/usr.bin/make/execution/empty/Makefile 228149 2011-11-30 05:49:17Z fjoe $
+
+EMPTY=
+
+check-empty:
+	@${MAKE} -f ${MAKEFILE} do-$@
+	@${MAKE} -f ${MAKEFILE} -j2 do-$@
+	@${MAKE} -f ${MAKEFILE} -j2 -B do-$@
+
+do-check-empty:
+	${EMPTY}
+	@${EMPTY}
+	@-${EMPTY}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/regression/usr.bin/make/execution/empty/expected.status.1
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/tools/regression/usr.bin/make/execution/empty/expected.status.1	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,1 @@
+0
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/regression/usr.bin/make/execution/empty/test.t
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/tools/regression/usr.bin/make/execution/empty/test.t	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,15 @@
+#!/bin/sh
+
+# $FreeBSD: head/tools/regression/usr.bin/make/execution/empty/test.t 228149 2011-11-30 05:49:17Z fjoe $
+
+cd `dirname $0`
+. ../../common.sh
+
+# Description
+DESC="Empty command (from variable)"
+
+# Run
+TEST_N=1
+TEST_1=
+
+eval_cmd $*
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/regression/usr.bin/make/execution/plus/Makefile
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/tools/regression/usr.bin/make/execution/plus/Makefile	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,7 @@
+# $FreeBSD: head/tools/regression/usr.bin/make/execution/plus/Makefile 228149 2011-11-30 05:49:17Z fjoe $
+
+check-+:
+	@${MAKE} -f ${MAKEFILE} -j2 -n do-$@
+
+do-check-+:
+	@+echo $@
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/regression/usr.bin/make/execution/plus/expected.status.1
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/tools/regression/usr.bin/make/execution/plus/expected.status.1	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,1 @@
+0
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/regression/usr.bin/make/execution/plus/expected.stdout.1
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/tools/regression/usr.bin/make/execution/plus/expected.stdout.1	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,1 @@
+do-check-+
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/regression/usr.bin/make/execution/plus/test.t
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/tools/regression/usr.bin/make/execution/plus/test.t	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,15 @@
+#!/bin/sh
+
+# $FreeBSD: head/tools/regression/usr.bin/make/execution/plus/test.t 228149 2011-11-30 05:49:17Z fjoe $
+
+cd `dirname $0`
+. ../../common.sh
+
+# Description
+DESC="Test '+command' execution with -n -jX"
+
+# Run
+TEST_N=1
+TEST_1=
+
+eval_cmd $*
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tinder.sh
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/tools/tinder.sh	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,61 @@
+#!/bin/sh
+#
+# Copyright (c) 2011 Max Khon, The FreeBSD Project
+# 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: head/tools/tinder.sh 228066 2011-11-28 14:03:36Z fjoe $
+#
+
+#
+# Utility script to build specific parts of the source tree on all arches
+#
+# Example:
+#
+# cd /usr/src
+# make toolchains		# build toolchain for all arches
+# sh tools/tinder.sh gnu/lib/libdialog usr.sbin/sade NO_CLEAN=yes
+#				# build libdialog and sade for all architectures
+#				# without making clean
+# sh tools/tinder.sh gnu/lib/libdialog usr.sbin/sade TARGETS="amd64 i386"
+#				# build libdialog and sade only for amd64 and i386
+#
+
+if [ $# -eq 0 ]; then
+	echo 1>&2 "Usage: `basename $0` [MAKEVAR=value...] path..."
+	exit 1
+fi
+
+# MAKE_ARGS is intentionally not reset to allow caller to specify additional MAKE_ARGS
+SUBDIR=
+for i in "$@"; do
+	case "$i" in
+	*=*)
+		MAKE_ARGS="$MAKE_ARGS $i"
+		;;
+	*)
+		SUBDIR="$SUBDIR $i"
+		;;
+	esac
+done
+make tinderbox UNIVERSE_TARGET="_cleanobj _obj _depend everything" $MAKE_ARGS SUBDIR_OVERRIDE="$SUBDIR"
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/Makefile
--- a/head/tools/tools/ath/Makefile	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/Makefile	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-#	$FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/Makefile 224599 2011-08-02 08:31:23Z adrian $
+#	$FreeBSD: head/tools/tools/ath/Makefile 224266 2011-07-22 09:34:31Z adrian $
 
 SUBDIR=	arcode athdebug athdecode athkey athpoke athprom athrd athregs
 SUBDIR+=	athstats ath_ee_v14_print ath_prom_read ath_ee_v4k_print
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/Makefile.inc
--- a/head/tools/tools/ath/Makefile.inc	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/Makefile.inc	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-#	$FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/Makefile.inc 217681 2011-01-21 02:56:59Z adrian $
+#	$FreeBSD: head/tools/tools/ath/Makefile.inc 217681 2011-01-21 02:56:59Z adrian $
 
 BINDIR=	/usr/local/bin
 NO_MAN=
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/arcode/Makefile
--- a/head/tools/tools/ath/arcode/Makefile	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/arcode/Makefile	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-# $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/arcode/Makefile 220364 2011-04-05 15:11:09Z adrian $
+# $FreeBSD: head/tools/tools/ath/arcode/Makefile 220364 2011-04-05 15:11:09Z adrian $
 
 PROG=	arcode
 NOMAN=	yes
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/arcode/arcode.c
--- a/head/tools/tools/ath/arcode/arcode.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/arcode/arcode.c	Tue Dec 06 20:26:16 2011 +0200
@@ -13,7 +13,7 @@
  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  *
- * $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/arcode/arcode.c 220366 2011-04-05 16:12:38Z adrian $
+ * $FreeBSD: head/tools/tools/ath/arcode/arcode.c 220366 2011-04-05 16:12:38Z adrian $
  */
 
 #include <stdio.h>
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/ath_ee_9287_print/9287.c
--- a/head/tools/tools/ath/ath_ee_9287_print/9287.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/ath_ee_9287_print/9287.c	Tue Dec 06 20:26:16 2011 +0200
@@ -22,7 +22,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/ath_ee_9287_print/9287.c 222322 2011-05-26 19:49:32Z adrian $
+ * $FreeBSD: head/tools/tools/ath/ath_ee_9287_print/9287.c 222322 2011-05-26 19:49:32Z adrian $
  */
 
 #include <stdio.h>
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/ath_ee_9287_print/9287.h
--- a/head/tools/tools/ath/ath_ee_9287_print/9287.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/ath_ee_9287_print/9287.h	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-/* $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/ath_ee_9287_print/9287.h 222322 2011-05-26 19:49:32Z adrian $ */
+/* $FreeBSD: head/tools/tools/ath/ath_ee_9287_print/9287.h 222322 2011-05-26 19:49:32Z adrian $ */
 
 #ifndef	__9287_H__
 #define	__9287_H__
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/ath_ee_9287_print/Makefile
--- a/head/tools/tools/ath/ath_ee_9287_print/Makefile	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/ath_ee_9287_print/Makefile	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-# $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/ath_ee_9287_print/Makefile 222322 2011-05-26 19:49:32Z adrian $
+# $FreeBSD: head/tools/tools/ath/ath_ee_9287_print/Makefile 222322 2011-05-26 19:49:32Z adrian $
 
 .PATH:  ${.CURDIR}/../../../../sys/dev/ath/ath_hal
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/ath_ee_9287_print/eeprom.c
--- a/head/tools/tools/ath/ath_ee_9287_print/eeprom.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/ath_ee_9287_print/eeprom.c	Tue Dec 06 20:26:16 2011 +0200
@@ -23,7 +23,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/ath_ee_9287_print/eeprom.c 222322 2011-05-26 19:49:32Z adrian $
+ * $FreeBSD: head/tools/tools/ath/ath_ee_9287_print/eeprom.c 222322 2011-05-26 19:49:32Z adrian $
  */
 
 #include <stdio.h>
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/ath_ee_9287_print/eeprom.h
--- a/head/tools/tools/ath/ath_ee_9287_print/eeprom.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/ath_ee_9287_print/eeprom.h	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-/* $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/ath_ee_9287_print/eeprom.h 222322 2011-05-26 19:49:32Z adrian $ */
+/* $FreeBSD: head/tools/tools/ath/ath_ee_9287_print/eeprom.h 222322 2011-05-26 19:49:32Z adrian $ */
 
 #ifndef	__EEPROM_H__
 #define	__EEPROM_H__
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/ath_ee_9287_print/main.c
--- a/head/tools/tools/ath/ath_ee_9287_print/main.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/ath_ee_9287_print/main.c	Tue Dec 06 20:26:16 2011 +0200
@@ -23,7 +23,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/ath_ee_9287_print/main.c 222322 2011-05-26 19:49:32Z adrian $
+ * $FreeBSD: head/tools/tools/ath/ath_ee_9287_print/main.c 222322 2011-05-26 19:49:32Z adrian $
  */
 
 #include <stdio.h>
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/ath_ee_v14_print/Makefile
--- a/head/tools/tools/ath/ath_ee_v14_print/Makefile	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/ath_ee_v14_print/Makefile	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-# $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/ath_ee_v14_print/Makefile 217682 2011-01-21 03:14:08Z adrian $
+# $FreeBSD: head/tools/tools/ath/ath_ee_v14_print/Makefile 217682 2011-01-21 03:14:08Z adrian $
 
 .PATH:  ${.CURDIR}/../../../../sys/dev/ath/ath_hal
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/ath_ee_v14_print/ath_ee_v14_print.c
--- a/head/tools/tools/ath/ath_ee_v14_print/ath_ee_v14_print.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/ath_ee_v14_print/ath_ee_v14_print.c	Tue Dec 06 20:26:16 2011 +0200
@@ -23,7 +23,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/ath_ee_v14_print/ath_ee_v14_print.c 219901 2011-03-23 11:16:06Z adrian $
+ * $FreeBSD: head/tools/tools/ath/ath_ee_v14_print/ath_ee_v14_print.c 219901 2011-03-23 11:16:06Z adrian $
  */
 
 #include <stdio.h>
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/ath_ee_v4k_print/Makefile
--- a/head/tools/tools/ath/ath_ee_v4k_print/Makefile	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/ath_ee_v4k_print/Makefile	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-# $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/ath_ee_v4k_print/Makefile 217770 2011-01-24 06:46:03Z adrian $
+# $FreeBSD: head/tools/tools/ath/ath_ee_v4k_print/Makefile 217770 2011-01-24 06:46:03Z adrian $
 
 .PATH:  ${.CURDIR}/../../../../sys/dev/ath/ath_hal
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/ath_ee_v4k_print/eeprom.c
--- a/head/tools/tools/ath/ath_ee_v4k_print/eeprom.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/ath_ee_v4k_print/eeprom.c	Tue Dec 06 20:26:16 2011 +0200
@@ -23,7 +23,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/ath_ee_v4k_print/eeprom.c 217770 2011-01-24 06:46:03Z adrian $
+ * $FreeBSD: head/tools/tools/ath/ath_ee_v4k_print/eeprom.c 217770 2011-01-24 06:46:03Z adrian $
  */
 
 #include <stdio.h>
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/ath_ee_v4k_print/eeprom.h
--- a/head/tools/tools/ath/ath_ee_v4k_print/eeprom.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/ath_ee_v4k_print/eeprom.h	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-/* $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/ath_ee_v4k_print/eeprom.h 217770 2011-01-24 06:46:03Z adrian $ */
+/* $FreeBSD: head/tools/tools/ath/ath_ee_v4k_print/eeprom.h 217770 2011-01-24 06:46:03Z adrian $ */
 
 #ifndef	__EEPROM_H__
 #define	__EEPROM_H__
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/ath_ee_v4k_print/main.c
--- a/head/tools/tools/ath/ath_ee_v4k_print/main.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/ath_ee_v4k_print/main.c	Tue Dec 06 20:26:16 2011 +0200
@@ -23,7 +23,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/ath_ee_v4k_print/main.c 217770 2011-01-24 06:46:03Z adrian $
+ * $FreeBSD: head/tools/tools/ath/ath_ee_v4k_print/main.c 217770 2011-01-24 06:46:03Z adrian $
  */
 
 #include <stdio.h>
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/ath_ee_v4k_print/v4k.c
--- a/head/tools/tools/ath/ath_ee_v4k_print/v4k.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/ath_ee_v4k_print/v4k.c	Tue Dec 06 20:26:16 2011 +0200
@@ -23,7 +23,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/ath_ee_v4k_print/v4k.c 221691 2011-05-09 10:39:15Z adrian $
+ * $FreeBSD: head/tools/tools/ath/ath_ee_v4k_print/v4k.c 221691 2011-05-09 10:39:15Z adrian $
  */
 
 #include <stdio.h>
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/ath_ee_v4k_print/v4k.h
--- a/head/tools/tools/ath/ath_ee_v4k_print/v4k.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/ath_ee_v4k_print/v4k.h	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-/* $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/ath_ee_v4k_print/v4k.h 217770 2011-01-24 06:46:03Z adrian $ */
+/* $FreeBSD: head/tools/tools/ath/ath_ee_v4k_print/v4k.h 217770 2011-01-24 06:46:03Z adrian $ */
 
 #ifndef	__V4K_H__
 #define	__V4K_H__
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/ath_prom_read/Makefile
--- a/head/tools/tools/ath/ath_prom_read/Makefile	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/ath_prom_read/Makefile	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-# $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/ath_prom_read/Makefile 217739 2011-01-22 23:44:56Z adrian $
+# $FreeBSD: head/tools/tools/ath/ath_prom_read/Makefile 217739 2011-01-22 23:44:56Z adrian $
 
 PROG=	ath_prom_read
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/ath_prom_read/ath_prom_read.c
--- a/head/tools/tools/ath/ath_prom_read/ath_prom_read.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/ath_prom_read/ath_prom_read.c	Tue Dec 06 20:26:16 2011 +0200
@@ -26,7 +26,7 @@
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
  * THE POSSIBILITY OF SUCH DAMAGES.
  *
- * $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/ath_prom_read/ath_prom_read.c 217739 2011-01-22 23:44:56Z adrian $
+ * $FreeBSD: head/tools/tools/ath/ath_prom_read/ath_prom_read.c 217739 2011-01-22 23:44:56Z adrian $
  */
 #include "diag.h"
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/athctrl.sh
--- a/head/tools/tools/ath/athctrl.sh	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/athctrl.sh	Tue Dec 06 20:26:16 2011 +0200
@@ -4,7 +4,7 @@
 # point-to-point use at a specific distance.  Based on a
 # program by Gunter Burchardt.
 #
-# $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/athctrl.sh 149629 2005-08-30 16:03:15Z sam $
+# $FreeBSD: head/tools/tools/ath/athctrl.sh 149629 2005-08-30 16:03:15Z sam $
 #
 DEV=ath0
 d=0
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/athdebug/Makefile
--- a/head/tools/tools/ath/athdebug/Makefile	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/athdebug/Makefile	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-# $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/athdebug/Makefile 185743 2008-12-07 19:17:33Z sam $
+# $FreeBSD: head/tools/tools/ath/athdebug/Makefile 185743 2008-12-07 19:17:33Z sam $
 
 PROG=	athdebug
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/athdebug/athdebug.c
--- a/head/tools/tools/ath/athdebug/athdebug.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/athdebug/athdebug.c	Tue Dec 06 20:26:16 2011 +0200
@@ -26,7 +26,7 @@
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
  * THE POSSIBILITY OF SUCH DAMAGES.
  *
- * $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/athdebug/athdebug.c 217680 2011-01-21 02:53:32Z adrian $
+ * $FreeBSD: head/tools/tools/ath/athdebug/athdebug.c 217680 2011-01-21 02:53:32Z adrian $
  */
 
 /*
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/athdecode/Makefile
--- a/head/tools/tools/ath/athdecode/Makefile	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/athdecode/Makefile	Tue Dec 06 20:26:16 2011 +0200
@@ -1,5 +1,5 @@
 #
-# $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/athdecode/Makefile 220534 2011-04-11 06:53:45Z adrian $
+# $FreeBSD: head/tools/tools/ath/athdecode/Makefile 220534 2011-04-11 06:53:45Z adrian $
 
 PROG=	athdecode
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/athdecode/main.c
--- a/head/tools/tools/ath/athdecode/main.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/athdecode/main.c	Tue Dec 06 20:26:16 2011 +0200
@@ -26,7 +26,7 @@
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
  * THE POSSIBILITY OF SUCH DAMAGES.
  *
- * $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/athdecode/main.c 217680 2011-01-21 02:53:32Z adrian $
+ * $FreeBSD: head/tools/tools/ath/athdecode/main.c 217680 2011-01-21 02:53:32Z adrian $
  */
 #include "diag.h"
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/athkey/Makefile
--- a/head/tools/tools/ath/athkey/Makefile	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/athkey/Makefile	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-# $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/athkey/Makefile 220534 2011-04-11 06:53:45Z adrian $
+# $FreeBSD: head/tools/tools/ath/athkey/Makefile 220534 2011-04-11 06:53:45Z adrian $
 
 PROG=	athkey
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/athkey/athkey.c
--- a/head/tools/tools/ath/athkey/athkey.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/athkey/athkey.c	Tue Dec 06 20:26:16 2011 +0200
@@ -26,7 +26,7 @@
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
  * THE POSSIBILITY OF SUCH DAMAGES.
  *
- * $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/athkey/athkey.c 185743 2008-12-07 19:17:33Z sam $
+ * $FreeBSD: head/tools/tools/ath/athkey/athkey.c 185743 2008-12-07 19:17:33Z sam $
  */
 
 #include "diag.h"
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/athpoke/Makefile
--- a/head/tools/tools/ath/athpoke/Makefile	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/athpoke/Makefile	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-# $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/athpoke/Makefile 220534 2011-04-11 06:53:45Z adrian $
+# $FreeBSD: head/tools/tools/ath/athpoke/Makefile 220534 2011-04-11 06:53:45Z adrian $
 
 PROG=	athpoke
 LINKS=	${BINDIR}/${PROG} ${BINDIR}/athpeek
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/athpoke/athpoke.c
--- a/head/tools/tools/ath/athpoke/athpoke.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/athpoke/athpoke.c	Tue Dec 06 20:26:16 2011 +0200
@@ -26,7 +26,7 @@
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
  * THE POSSIBILITY OF SUCH DAMAGES.
  *
- * $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/athpoke/athpoke.c 196599 2009-08-27 17:32:58Z sam $
+ * $FreeBSD: head/tools/tools/ath/athpoke/athpoke.c 196599 2009-08-27 17:32:58Z sam $
  */
 #include "diag.h"
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/athpow/Makefile
--- a/head/tools/tools/ath/athpow/Makefile	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/athpow/Makefile	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-# $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/athpow/Makefile 185743 2008-12-07 19:17:33Z sam $
+# $FreeBSD: head/tools/tools/ath/athpow/Makefile 185743 2008-12-07 19:17:33Z sam $
 
 PROG=	athpow
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/athpow/athpow.c
--- a/head/tools/tools/ath/athpow/athpow.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/athpow/athpow.c	Tue Dec 06 20:26:16 2011 +0200
@@ -26,7 +26,7 @@
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
  * THE POSSIBILITY OF SUCH DAMAGES.
  *
- * $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/athpow/athpow.c 218057 2011-01-29 04:34:30Z adrian $
+ * $FreeBSD: head/tools/tools/ath/athpow/athpow.c 218057 2011-01-29 04:34:30Z adrian $
  */
 #include "diag.h"
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/athprom/Makefile
--- a/head/tools/tools/ath/athprom/Makefile	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/athprom/Makefile	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-# $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/athprom/Makefile 220534 2011-04-11 06:53:45Z adrian $
+# $FreeBSD: head/tools/tools/ath/athprom/Makefile 220534 2011-04-11 06:53:45Z adrian $
 
 PROG=	athprom
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/athprom/athprom.c
--- a/head/tools/tools/ath/athprom/athprom.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/athprom/athprom.c	Tue Dec 06 20:26:16 2011 +0200
@@ -26,7 +26,7 @@
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
  * THE POSSIBILITY OF SUCH DAMAGES.
  *
- * $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/athprom/athprom.c 217680 2011-01-21 02:53:32Z adrian $
+ * $FreeBSD: head/tools/tools/ath/athprom/athprom.c 217680 2011-01-21 02:53:32Z adrian $
  */
 #include "diag.h"
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/athprom/eeprom-14
--- a/head/tools/tools/ath/athprom/eeprom-14	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/athprom/eeprom-14	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-# $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/athprom/eeprom-14 185743 2008-12-07 19:17:33Z sam $
+# $FreeBSD: head/tools/tools/ath/athprom/eeprom-14 185743 2008-12-07 19:17:33Z sam $
 #
 # v14 format EEPROM template (AR5416 and later 11n parts)
 #
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/athprom/eeprom-3
--- a/head/tools/tools/ath/athprom/eeprom-3	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/athprom/eeprom-3	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-# $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/athprom/eeprom-3 185743 2008-12-07 19:17:33Z sam $
+# $FreeBSD: head/tools/tools/ath/athprom/eeprom-3 185743 2008-12-07 19:17:33Z sam $
 #
 # v3 format EEPROM template
 #
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/athprom/eeprom-4
--- a/head/tools/tools/ath/athprom/eeprom-4	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/athprom/eeprom-4	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-# $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/athprom/eeprom-4 185743 2008-12-07 19:17:33Z sam $
+# $FreeBSD: head/tools/tools/ath/athprom/eeprom-4 185743 2008-12-07 19:17:33Z sam $
 #
 # v4 format EEPROM template
 #
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/athprom/eeprom-5
--- a/head/tools/tools/ath/athprom/eeprom-5	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/athprom/eeprom-5	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-# $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/athprom/eeprom-5 185743 2008-12-07 19:17:33Z sam $
+# $FreeBSD: head/tools/tools/ath/athprom/eeprom-5 185743 2008-12-07 19:17:33Z sam $
 #
 # v5 format EEPROM template
 #
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/athradar/Makefile
--- a/head/tools/tools/ath/athradar/Makefile	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/athradar/Makefile	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-# $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/athradar/Makefile 224266 2011-07-22 09:34:31Z adrian $
+# $FreeBSD: head/tools/tools/ath/athradar/Makefile 224266 2011-07-22 09:34:31Z adrian $
 
 PROG=	athradar
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/athradar/athradar.c
--- a/head/tools/tools/ath/athradar/athradar.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/athradar/athradar.c	Tue Dec 06 20:26:16 2011 +0200
@@ -22,7 +22,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/athradar/athradar.c 224266 2011-07-22 09:34:31Z adrian $
+ * $FreeBSD: head/tools/tools/ath/athradar/athradar.c 224266 2011-07-22 09:34:31Z adrian $
  */
 
 #include "diag.h"
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/athrd/Makefile
--- a/head/tools/tools/ath/athrd/Makefile	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/athrd/Makefile	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-# $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/athrd/Makefile 187322 2009-01-15 23:38:21Z sam $
+# $FreeBSD: head/tools/tools/ath/athrd/Makefile 187322 2009-01-15 23:38:21Z sam $
 
 .PATH:	${.CURDIR}/../../../../sys/dev/ath/ath_hal
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/athrd/athrd.1
--- a/head/tools/tools/ath/athrd/athrd.1	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/athrd/athrd.1	Tue Dec 06 20:26:16 2011 +0200
@@ -26,7 +26,7 @@
 .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 .\" THE POSSIBILITY OF SUCH DAMAGES.
 .\"
-.\" $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/athrd/athrd.1 187904 2009-01-29 23:24:21Z sam $
+.\" $FreeBSD: head/tools/tools/ath/athrd/athrd.1 187904 2009-01-29 23:24:21Z sam $
 .\"/
 .Dd January 27, 2009
 .Dt ATHRD 1
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/athrd/athrd.c
--- a/head/tools/tools/ath/athrd/athrd.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/athrd/athrd.c	Tue Dec 06 20:26:16 2011 +0200
@@ -26,7 +26,7 @@
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
  * THE POSSIBILITY OF SUCH DAMAGES.
  *
- * $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/athrd/athrd.c 219398 2011-03-08 12:08:23Z adrian $
+ * $FreeBSD: head/tools/tools/ath/athrd/athrd.c 219398 2011-03-08 12:08:23Z adrian $
  */
 #include "opt_ah.h"
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/athrd/run.sh
--- a/head/tools/tools/ath/athrd/run.sh	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/athrd/run.sh	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-# $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/athrd/run.sh 187322 2009-01-15 23:38:21Z sam $
+# $FreeBSD: head/tools/tools/ath/athrd/run.sh 187322 2009-01-15 23:38:21Z sam $
 
 COUNTRIES=${@:-"
 	DB NA AL DZ AR AM AU AT AZ BH BY BE BZ BO BR BN BG
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/athregs/Makefile
--- a/head/tools/tools/ath/athregs/Makefile	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/athregs/Makefile	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-# $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/athregs/Makefile 220534 2011-04-11 06:53:45Z adrian $
+# $FreeBSD: head/tools/tools/ath/athregs/Makefile 220534 2011-04-11 06:53:45Z adrian $
 
 PROG=	athregs
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/athregs/dumpregs.c
--- a/head/tools/tools/ath/athregs/dumpregs.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/athregs/dumpregs.c	Tue Dec 06 20:26:16 2011 +0200
@@ -26,7 +26,7 @@
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
  * THE POSSIBILITY OF SUCH DAMAGES.
  *
- * $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/athregs/dumpregs.c 217680 2011-01-21 02:53:32Z adrian $
+ * $FreeBSD: head/tools/tools/ath/athregs/dumpregs.c 217680 2011-01-21 02:53:32Z adrian $
  */
 #include "diag.h"
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/athstats/Makefile
--- a/head/tools/tools/ath/athstats/Makefile	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/athstats/Makefile	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-# $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/athstats/Makefile 217738 2011-01-22 23:37:42Z adrian $
+# $FreeBSD: head/tools/tools/ath/athstats/Makefile 217738 2011-01-22 23:37:42Z adrian $
 
 .PATH:	${.CURDIR}/../../../../sys/dev/ath/ath_hal
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/athstats/athstats.h
--- a/head/tools/tools/ath/athstats/athstats.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/athstats/athstats.h	Tue Dec 06 20:26:16 2011 +0200
@@ -26,7 +26,7 @@
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
  * THE POSSIBILITY OF SUCH DAMAGES.
  *
- * $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/athstats/athstats.h 188560 2009-02-13 05:45:23Z sam $
+ * $FreeBSD: head/tools/tools/ath/athstats/athstats.h 188560 2009-02-13 05:45:23Z sam $
  */
 
 #ifndef _ATHSTATS_H_
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/athstats/main.c
--- a/head/tools/tools/ath/athstats/main.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/athstats/main.c	Tue Dec 06 20:26:16 2011 +0200
@@ -26,7 +26,7 @@
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
  * THE POSSIBILITY OF SUCH DAMAGES.
  *
- * $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/athstats/main.c 217680 2011-01-21 02:53:32Z adrian $
+ * $FreeBSD: head/tools/tools/ath/athstats/main.c 217680 2011-01-21 02:53:32Z adrian $
  */
 
 /*
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/athstats/statfoo.c
--- a/head/tools/tools/ath/athstats/statfoo.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/athstats/statfoo.c	Tue Dec 06 20:26:16 2011 +0200
@@ -26,7 +26,7 @@
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
  * THE POSSIBILITY OF SUCH DAMAGES.
  *
- * $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/athstats/statfoo.c 188558 2009-02-13 05:42:25Z sam $
+ * $FreeBSD: head/tools/tools/ath/athstats/statfoo.c 188558 2009-02-13 05:42:25Z sam $
  */
 
 #include <stdio.h>
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/athstats/statfoo.h
--- a/head/tools/tools/ath/athstats/statfoo.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/athstats/statfoo.h	Tue Dec 06 20:26:16 2011 +0200
@@ -26,7 +26,7 @@
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
  * THE POSSIBILITY OF SUCH DAMAGES.
  *
- * $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/athstats/statfoo.h 174245 2007-12-04 05:52:58Z sam $
+ * $FreeBSD: head/tools/tools/ath/athstats/statfoo.h 174245 2007-12-04 05:52:58Z sam $
  */
 
 #ifndef _STATFOO_H_
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/common/ah_osdep.h
--- a/head/tools/tools/ath/common/ah_osdep.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/common/ah_osdep.h	Tue Dec 06 20:26:16 2011 +0200
@@ -26,7 +26,7 @@
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
  * THE POSSIBILITY OF SUCH DAMAGES.
  *
- * $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/common/ah_osdep.h 185743 2008-12-07 19:17:33Z sam $
+ * $FreeBSD: head/tools/tools/ath/common/ah_osdep.h 185743 2008-12-07 19:17:33Z sam $
  */
 #ifndef _ATH_AH_OSDEP_H_
 #define _ATH_AH_OSDEP_H_
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/common/diag.h
--- a/head/tools/tools/ath/common/diag.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/common/diag.h	Tue Dec 06 20:26:16 2011 +0200
@@ -28,7 +28,7 @@
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
  * THE POSSIBILITY OF SUCH DAMAGES.
  *
- * $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/common/diag.h 185743 2008-12-07 19:17:33Z sam $
+ * $FreeBSD: head/tools/tools/ath/common/diag.h 185743 2008-12-07 19:17:33Z sam $
  */
 #include <sys/types.h>
 #include <sys/file.h>
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/common/dumpregs.h
--- a/head/tools/tools/ath/common/dumpregs.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/common/dumpregs.h	Tue Dec 06 20:26:16 2011 +0200
@@ -28,7 +28,7 @@
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
  * THE POSSIBILITY OF SUCH DAMAGES.
  *
- * $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/common/dumpregs.h 196696 2009-08-31 13:23:55Z jhb $
+ * $FreeBSD: head/tools/tools/ath/common/dumpregs.h 196696 2009-08-31 13:23:55Z jhb $
  */
 
 #define	__constructor	__attribute__((constructor))
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/common/dumpregs_5210.c
--- a/head/tools/tools/ath/common/dumpregs_5210.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/common/dumpregs_5210.c	Tue Dec 06 20:26:16 2011 +0200
@@ -26,7 +26,7 @@
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
  * THE POSSIBILITY OF SUCH DAMAGES.
  *
- * $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/common/dumpregs_5210.c 196696 2009-08-31 13:23:55Z jhb $
+ * $FreeBSD: head/tools/tools/ath/common/dumpregs_5210.c 196696 2009-08-31 13:23:55Z jhb $
  */
 #include "diag.h"
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/common/dumpregs_5211.c
--- a/head/tools/tools/ath/common/dumpregs_5211.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/common/dumpregs_5211.c	Tue Dec 06 20:26:16 2011 +0200
@@ -26,7 +26,7 @@
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
  * THE POSSIBILITY OF SUCH DAMAGES.
  *
- * $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/common/dumpregs_5211.c 196696 2009-08-31 13:23:55Z jhb $
+ * $FreeBSD: head/tools/tools/ath/common/dumpregs_5211.c 196696 2009-08-31 13:23:55Z jhb $
  */
 #include "diag.h"
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/common/dumpregs_5212.c
--- a/head/tools/tools/ath/common/dumpregs_5212.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/common/dumpregs_5212.c	Tue Dec 06 20:26:16 2011 +0200
@@ -26,7 +26,7 @@
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
  * THE POSSIBILITY OF SUCH DAMAGES.
  *
- * $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/common/dumpregs_5212.c 196696 2009-08-31 13:23:55Z jhb $
+ * $FreeBSD: head/tools/tools/ath/common/dumpregs_5212.c 196696 2009-08-31 13:23:55Z jhb $
  */
 #include "diag.h"
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/ath/common/dumpregs_5416.c
--- a/head/tools/tools/ath/common/dumpregs_5416.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/ath/common/dumpregs_5416.c	Tue Dec 06 20:26:16 2011 +0200
@@ -26,7 +26,7 @@
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
  * THE POSSIBILITY OF SUCH DAMAGES.
  *
- * $FreeBSD: user/adrian/if_ath_tx/tools/tools/ath/common/dumpregs_5416.c 206848 2010-04-19 17:16:23Z rpaulo $
+ * $FreeBSD: head/tools/tools/ath/common/dumpregs_5416.c 206848 2010-04-19 17:16:23Z rpaulo $
  */
 #include "diag.h"
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/tools/tools/netmap/pkt-gen.c
--- a/head/tools/tools/netmap/pkt-gen.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/tools/tools/netmap/pkt-gen.c	Tue Dec 06 20:26:16 2011 +0200
@@ -4,10 +4,10 @@
  * 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
+ *   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
@@ -24,8 +24,8 @@
  */
 
 /*
- * $FreeBSD: head/tools/tools/netmap/pkt-gen.c 227614 2011-11-17 12:17:39Z luigi $
- * $Id: pkt-gen.c 9638 2011-11-07 18:07:43Z luigi $
+ * $FreeBSD: head/tools/tools/netmap/pkt-gen.c 228276 2011-12-05 12:06:53Z luigi $
+ * $Id: pkt-gen.c 9827 2011-12-05 11:29:34Z luigi $
  *
  * Example program to show how to build a multithreaded packet
  * source/sink using the netmap device.
@@ -45,6 +45,7 @@
 #include <signal.h>	/* signal */
 #include <stdlib.h>
 #include <stdio.h>
+#include <inttypes.h>	/* PRI* macros */
 #include <string.h>	/* strcmp */
 #include <fcntl.h>	/* open */
 #include <unistd.h>	/* close */
@@ -616,7 +617,7 @@
 		punit += 1;
 	}
 
-	printf("Sent %llu packets, %d bytes each, in %.2f seconds.\n",
+	printf("Sent %" PRIu64 " packets, %d bytes each, in %.2f seconds.\n",
 	       sent, size, delta);
 	printf("Speed: %.2f%cpps. Bandwidth: %.2f%cbps.\n",
 	       pps, units[punit], amount, units[aunit]);
@@ -636,7 +637,7 @@
 		punit += 1;
 	}
 
-	printf("Received %llu packets, in %.2f seconds.\n", received, delta);
+	printf("Received %" PRIu64 " packets, in %.2f seconds.\n", received, delta);
 	printf("Speed: %.2f%cpps.\n", pps, units[punit]);
 }
 
@@ -971,7 +972,7 @@
 		if (pps < 10000)
 			continue;
 		pps = (my_count - prev)*1000000 / pps;
-		D("%llu pps", pps);
+		D("%" PRIu64 " pps", pps);
 		prev = my_count;
 		toc = now;
 		if (done == g.nthreads)
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.bin/grep/Makefile
--- a/head/usr.bin/grep/Makefile	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/usr.bin/grep/Makefile	Tue Dec 06 20:26:16 2011 +0200
@@ -1,5 +1,5 @@
 #	$NetBSD: Makefile,v 1.4 2011/02/16 01:31:33 joerg Exp $
-#	$FreeBSD: head/usr.bin/grep/Makefile 226664 2011-10-23 16:04:07Z gabor $
+#	$FreeBSD: head/usr.bin/grep/Makefile 228099 2011-11-28 20:16:55Z gabor $
 #	$OpenBSD: Makefile,v 1.6 2003/06/25 15:00:04 millert Exp $
 
 .include <bsd.own.mk>
@@ -25,13 +25,7 @@
 	${BINDIR}/grep ${BINDIR}/fgrep \
 	${BINDIR}/grep ${BINDIR}/zgrep \
 	${BINDIR}/grep ${BINDIR}/zegrep \
-	${BINDIR}/grep ${BINDIR}/zfgrep \
-	${BINDIR}/grep ${BINDIR}/xzgrep \
-	${BINDIR}/grep ${BINDIR}/xzegrep \
-	${BINDIR}/grep ${BINDIR}/xzfgrep \
-	${BINDIR}/grep ${BINDIR}/lzgrep \
-	${BINDIR}/grep ${BINDIR}/lzegrep \
-	${BINDIR}/grep ${BINDIR}/lzfgrep
+	${BINDIR}/grep ${BINDIR}/zfgrep
 
 MLINKS= grep.1 egrep.1 \
 	grep.1 fgrep.1 \
@@ -46,6 +40,13 @@
 	grep.1 lzfgrep.1
 .endif
 
+LINKS+=	${BINDIR}/${PROG} ${BINDIR}/xzgrep \
+	${BINDIR}/${PROG} ${BINDIR}/xzegrep \
+	${BINDIR}/${PROG} ${BINDIR}/xzfgrep \
+	${BINDIR}/${PROG} ${BINDIR}/lzgrep \
+	${BINDIR}/${PROG} ${BINDIR}/lzegrep \
+	${BINDIR}/${PROG} ${BINDIR}/lzfgrep
+
 LDADD=	-lz -llzma
 DPADD=	${LIBZ} ${LIBLZMA}
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.bin/grep/util.c
--- a/head/usr.bin/grep/util.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/usr.bin/grep/util.c	Tue Dec 06 20:26:16 2011 +0200
@@ -1,5 +1,5 @@
 /*	$NetBSD: util.c,v 1.9 2011/02/27 17:33:37 joerg Exp $	*/
-/*	$FreeBSD: head/usr.bin/grep/util.c 226273 2011-10-12 01:09:57Z gabor $	*/
+/*	$FreeBSD: head/usr.bin/grep/util.c 228097 2011-11-28 20:04:26Z gabor $	*/
 /*	$OpenBSD: util.c,v 1.39 2010/07/02 22:18:03 tedu Exp $	*/
 
 /*-
@@ -30,7 +30,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/usr.bin/grep/util.c 226273 2011-10-12 01:09:57Z gabor $");
+__FBSDID("$FreeBSD: head/usr.bin/grep/util.c 228097 2011-11-28 20:04:26Z gabor $");
 
 #include <sys/stat.h>
 #include <sys/types.h>
@@ -130,7 +130,9 @@
 		case FTS_DNR:
 			/* FALLTHROUGH */
 		case FTS_ERR:
-			errx(2, "%s: %s", p->fts_path, strerror(p->fts_errno));
+			notfound = true;
+			if(!sflag)
+				warnx("%s: %s", p->fts_path, strerror(p->fts_errno));
 			break;
 		case FTS_D:
 			/* FALLTHROUGH */
@@ -246,9 +248,9 @@
 		printf("%u\n", c);
 	}
 	if (lflag && !qflag && c != 0)
-		printf("%s\n", fn);
+		printf("%s%c", fn, nullflag ? 0 : '\n');
 	if (Lflag && !qflag && c == 0)
-		printf("%s\n", fn);
+		printf("%s%c", fn, nullflag ? 0 : '\n');
 	if (c && !cflag && !lflag && !Lflag &&
 	    binbehave == BINFILE_BIN && f->binary && !qflag)
 		printf(getstr(8), fn);
@@ -440,13 +442,13 @@
 	int i, n = 0;
 
 	if (!hflag) {
-		if (nullflag == 0)
+		if (!nullflag) {
 			fputs(line->file, stdout);
-		else {
+			++n;
+		} else {
 			printf("%s", line->file);
 			putchar(0);
 		}
-		++n;
 	}
 	if (nflag) {
 		if (n > 0)
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.bin/m4/Makefile
--- a/head/usr.bin/m4/Makefile	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/usr.bin/m4/Makefile	Tue Dec 06 20:26:16 2011 +0200
@@ -1,12 +1,24 @@
 #	$OpenBSD: Makefile,v 1.10 2002/04/26 13:13:41 espie Exp $
-# $FreeBSD: head/usr.bin/m4/Makefile 226422 2011-10-16 08:09:17Z ed $
+# $FreeBSD: head/usr.bin/m4/Makefile 228063 2011-11-28 13:32:39Z bapt $
 
 # -DEXTENDED 
 # 	if you want the paste & spaste macros.
 
 PROG=	m4
-CFLAGS+=-DEXTENDED
+CFLAGS+=-DEXTENDED -I${.CURDIR}/lib
+LDADD=	-ly -ll
+# clang needs 1 while with gcc we can use 2
+#WARNS=	1
 
-SRCS=	eval.c expr.c look.c main.c misc.c gnum4.c trace.c
+SRCS=	eval.c expr.c look.c main.c misc.c gnum4.c trace.c parser.y tokenizer.l
+.PATH: ${.CURDIR}/lib
+SRCS+=	ohash_create_entry.c ohash_delete.c ohash_do.c ohash_entries.c \
+	ohash_enum.c ohash_init.c ohash_int.h ohash_interval.c \
+	ohash_lookup_interval.c ohash_lookup_memory.c ohash_qlookup.c \
+	ohash_qlookupi.c
+
+tokenizer.o: parser.h
+
+CLEANFILES+=	parser.c parser.h tokenizer.o
 
 .include <bsd.prog.mk>
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.bin/m4/eval.c
--- a/head/usr.bin/m4/eval.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/usr.bin/m4/eval.c	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-/*	$OpenBSD: eval.c,v 1.44 2002/04/26 16:15:16 espie Exp $	*/
+/*	$OpenBSD: eval.c,v 1.69 2011/03/24 11:23:08 espie Exp $	*/
 /*	$NetBSD: eval.c,v 1.7 1996/11/10 21:21:29 pk Exp $	*/
 
 /*
@@ -16,7 +16,7 @@
  * 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.
- * 4. Neither the name of the University nor the names of its contributors
+ * 3. Neither the name of the University nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
  *
@@ -33,18 +33,9 @@
  * SUCH DAMAGE.
  */
 
-#ifndef lint
-#if 0
-static char sccsid[] = "@(#)eval.c	8.2 (Berkeley) 4/27/95";
-#else
-#if 0
-static char rcsid[] = "$OpenBSD: eval.c,v 1.44 2002/04/26 16:15:16 espie Exp $";
-#endif
-#endif
-#endif /* not lint */
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD: head/usr.bin/m4/eval.c 228063 2011-11-28 13:32:39Z bapt $");
 
-#include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
 
 /*
  * eval.c
@@ -53,21 +44,21 @@
  */
 
 #include <sys/types.h>
+#include <err.h>
 #include <errno.h>
+#include <limits.h>
 #include <unistd.h>
+#include <stdint.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <stddef.h>
 #include <string.h>
 #include <fcntl.h>
-#include <err.h>
 #include "mdef.h"
 #include "stdd.h"
 #include "extern.h"
 #include "pathnames.h"
 
-#define BUILTIN_MARKER	"__builtin_"
-
 static void	dodefn(const char *);
 static void	dopushdef(const char *, const char *);
 static void	dodump(const char *[], int);
@@ -75,10 +66,9 @@
 static void	doifelse(const char *[], int);
 static int	doincl(const char *);
 static int	dopaste(const char *);
-static void	gnu_dochq(const char *[], int);
 static void	dochq(const char *[], int);
-static void	gnu_dochc(const char *[], int);
 static void	dochc(const char *[], int);
+static void	dom4wrap(const char *);
 static void	dodiv(int);
 static void	doundiv(const char *[], int);
 static void	dosub(const char *[], int);
@@ -86,7 +76,7 @@
 static const char *handledash(char *, char *, const char *);
 static void	expand_builtin(const char *[], int, int);
 static void	expand_macro(const char *[], int);
-static void	dump_one_def(ndptr);
+static void	dump_one_def(const char *, struct macro_definition *);
 
 unsigned long	expansion_id;
 
@@ -95,7 +85,7 @@
  *	  argc - number of elements in argv.
  *	  argv - element vector :
  *			argv[0] = definition of a user
- *				  macro or nil if built-in.
+ *				  macro or NULL if built-in.
  *			argv[1] = name of the macro or
  *				  built-in.
  *			argv[2] = parameters to user-defined
@@ -110,21 +100,20 @@
  * argc is 3 for macro-or-builtin() and 2 for macro-or-builtin
  */
 void
-eval(const char *argv[], int argc, int td)
+eval(const char *argv[], int argc, int td, int is_traced)
 {
-	ssize_t mark = -1;
+	size_t mark = SIZE_MAX;
 
 	expansion_id++;
 	if (td & RECDEF)
-		errx(1, "%s at line %lu: expanding recursive definition for %s",
-			CURRENT_NAME, CURRENT_LINE, argv[1]);
-	if (traced_macros && is_traced(argv[1]))
+		m4errx(1, "expanding recursive definition for %s.", argv[1]);
+	if (is_traced)
 		mark = trace(argv, argc, infile+ilevel);
 	if (td == MACRTYPE)
 		expand_macro(argv, argc);
 	else
 		expand_builtin(argv, argc, td);
-    	if (mark != -1)
+	if (mark != SIZE_MAX)
 		finish_trace(mark);
 }
 
@@ -150,9 +139,12 @@
   * have macro-or-builtin() type call. We adjust
   * argc to avoid further checking..
   */
-  	ac = argc;
+ /* we keep the initial value for those built-ins that differentiate
+  * between builtin() and builtin.
+  */
+	ac = argc;
 
-	if (argc == 3 && !*(argv[2]))
+	if (argc == 3 && !*(argv[2]) && !mimic_gnu)
 		argc--;
 
 	switch (td & TYPEMASK) {
@@ -184,9 +176,27 @@
 	 * doexpr - evaluate arithmetic
 	 * expression
 	 */
+	{
+		int base = 10;
+		int maxdigits = 0;
+		const char *errstr;
+
+		if (argc > 3) {
+			base = strtonum(argv[3], 2, 36, &errstr);
+			if (errstr) {
+				m4errx(1, "expr: base %s invalid.", argv[3]);
+			}
+		}
+		if (argc > 4) {
+			maxdigits = strtonum(argv[4], 0, INT_MAX, &errstr);
+			if (errstr) {
+				m4errx(1, "expr: maxdigits %s invalid.", argv[4]);
+			}
+		}
 		if (argc > 2)
-			pbnum(expr(argv[2]));
+			pbnumbase(expr(argv[2]), base, maxdigits);
 		break;
+	}
 
 	case IFELTYPE:
 		if (argc > 4)
@@ -200,7 +210,7 @@
 	 * another definition
 	 */
 		if (argc > 3) {
-			if (lookup(argv[2]) != nil)
+			if (lookup_macro_definition(argv[2]) != NULL)
 				pbstr(argv[3]);
 			else if (argc > 4)
 				pbstr(argv[4]);
@@ -238,7 +248,7 @@
 	 * dosys - execute system command
 	 */
 		if (argc > 2) {
-			fflush(NULL);
+			fflush(stdout);
 			sysval = system(argv[2]);
 		}
 		break;
@@ -255,7 +265,7 @@
 	case ESYSCMDTYPE:
 		if (argc > 2)
 			doesyscmd(argv[2]);
-	    	break;
+		break;
 	case INCLTYPE:
 		if (argc > 2)
 			if (!doincl(argv[2]))
@@ -271,7 +281,7 @@
 	case PASTTYPE:
 		if (argc > 2)
 			if (!dopaste(argv[2]))
-				err(1, "%s at line %lu: paste(%s)",
+				err(1, "%s at line %lu: paste(%s)", 
 				    CURRENT_NAME, CURRENT_LINE, argv[2]);
 		break;
 
@@ -279,19 +289,16 @@
 		if (argc > 2)
 			(void) dopaste(argv[2]);
 		break;
+	case FORMATTYPE:
+		doformat(argv, argc);
+		break;
 #endif
 	case CHNQTYPE:
-		if (mimic_gnu)
-			gnu_dochq(argv, ac);
-		else
-			dochq(argv, argc);
+		dochq(argv, ac);
 		break;
 
 	case CHNCTYPE:
-		if (mimic_gnu)
-			gnu_dochc(argv, ac);
-		else
-			dochc(argv, argc);
+		dochc(argv, argc);
 		break;
 
 	case SUBSTYPE:
@@ -314,7 +321,7 @@
 				pbstr(rquote);
 				pbstr(argv[n]);
 				pbstr(lquote);
-				putback(COMMA);
+				pushback(COMMA);
 			}
 			pbstr(rquote);
 			pbstr(argv[3]);
@@ -350,7 +357,7 @@
 	 */
 		if (argc > 2)
 			for (n = 2; n < argc; n++)
-				remhash(argv[n], ALL);
+				macro_undefine(argv[n]);
 		break;
 
 	case POPDTYPE:
@@ -361,7 +368,7 @@
 	 */
 		if (argc > 2)
 			for (n = 2; n < argc; n++)
-				remhash(argv[n], TOP);
+				macro_popdef(argv[n]);
 		break;
 
 	case MKTMTYPE:
@@ -395,7 +402,7 @@
 		if (argc > 3) {
 			char *temp;
 
-			temp = xalloc(strlen(argv[2])+1);
+			temp = xalloc(strlen(argv[2])+1, NULL);
 			if (argc > 4)
 				map(temp, argv[2], argv[3], argv[4]);
 			else
@@ -441,7 +448,8 @@
 	 * dom4wrap - set up for
 	 * wrap-up/wind-down activity
 	 */
-		m4wraps = (argc > 2) ? xstrdup(argv[2]) : null;
+		if (argc > 2)
+			dom4wrap(argv[2]);
 		break;
 
 	case EXITTYPE:
@@ -488,8 +496,7 @@
 		pbstr(lquote);
 		break;
 	default:
-		errx(1, "%s at line %lu: eval: major botch.",
-			CURRENT_NAME, CURRENT_LINE);
+		m4errx(1, "eval: major botch.");
 		break;
 	}
 }
@@ -512,7 +519,7 @@
 	p--;			       /* last character of defn */
 	while (p > t) {
 		if (*(p - 1) != ARGFLAG)
-			PUTBACK(*p);
+			PUSHBACK(*p);
 		else {
 			switch (*p) {
 
@@ -536,10 +543,10 @@
 				if (argc > 2) {
 					for (n = argc - 1; n > 2; n--) {
 						pbstr(argv[n]);
-						putback(COMMA);
+						pushback(COMMA);
 					}
 					pbstr(argv[2]);
-			    	}
+				}
 				break;
                         case '@':
 				if (argc > 2) {
@@ -547,7 +554,7 @@
 						pbstr(rquote);
 						pbstr(argv[n]);
 						pbstr(lquote);
-						putback(COMMA);
+						pushback(COMMA);
 					}
 					pbstr(rquote);
 					pbstr(argv[2]);
@@ -555,8 +562,8 @@
 				}
                                 break;
 			default:
-				PUTBACK(*p);
-				PUTBACK('$');
+				PUSHBACK(*p);
+				PUSHBACK('$');
 				break;
 			}
 			p--;
@@ -564,42 +571,20 @@
 		p--;
 	}
 	if (p == t)		       /* do last character */
-		PUTBACK(*p);
+		PUSHBACK(*p);
 }
 
+
 /*
  * dodefine - install definition in the table
  */
 void
 dodefine(const char *name, const char *defn)
 {
-	ndptr p;
-	int n;
-
-	if (!*name)
-		errx(1, "%s at line %lu: null definition.", CURRENT_NAME,
-		    CURRENT_LINE);
-	if ((p = lookup(name)) == nil)
-		p = addent(name);
-	else if (p->defn != null)
-		free((char *) p->defn);
-	if (strncmp(defn, BUILTIN_MARKER, sizeof(BUILTIN_MARKER)-1) == 0) {
-		n = builtin_type(defn+sizeof(BUILTIN_MARKER)-1);
-		if (n != -1) {
-			p->type = n & TYPEMASK;
-			if ((n & NOARGS) == 0)
-				p->type |= NEEDARGS;
-			p->defn = null;
-			return;
-		}
-	}
-	if (!*defn)
-		p->defn = null;
+	if (!*name && !mimic_gnu)
+		m4errx(1, "null definition.");
 	else
-		p->defn = xstrdup(defn);
-	p->type = MACRTYPE;
-	if (STREQ(name, defn))
-		p->type |= RECDEF;
+		macro_define(name, defn);
 }
 
 /*
@@ -609,16 +594,15 @@
 static void
 dodefn(const char *name)
 {
-	ndptr p;
-	const char *real;
+	struct macro_definition *p;
 
-	if ((p = lookup(name)) != nil) {
-		if (p->defn != null) {
+	if ((p = lookup_macro_definition(name)) != NULL) {
+		if ((p->type & TYPEMASK) == MACRTYPE) {
 			pbstr(rquote);
 			pbstr(p->defn);
 			pbstr(lquote);
-		} else if ((real = builtin_realname(p->type)) != NULL) {
-			pbstr(real);
+		} else {
+			pbstr(p->defn);
 			pbstr(BUILTIN_MARKER);
 		}
 	}
@@ -634,40 +618,28 @@
 static void
 dopushdef(const char *name, const char *defn)
 {
-	ndptr p;
-
-	if (!*name)
-		errx(1, "%s at line %lu: null definition", CURRENT_NAME,
-		    CURRENT_LINE);
-	p = addent(name);
-	if (!*defn)
-		p->defn = null;
+	if (!*name && !mimic_gnu)
+		m4errx(1, "null definition.");
 	else
-		p->defn = xstrdup(defn);
-	p->type = MACRTYPE;
-	if (STREQ(name, defn))
-		p->type |= RECDEF;
+		macro_pushdef(name, defn);
 }
 
 /*
  * dump_one_def - dump the specified definition.
  */
 static void
-dump_one_def(ndptr p)
+dump_one_def(const char *name, struct macro_definition *p)
 {
-	const char *real;
-
+	if (!traceout)
+		traceout = stderr;
 	if (mimic_gnu) {
 		if ((p->type & TYPEMASK) == MACRTYPE)
-			fprintf(traceout, "%s:\t%s\n", p->name, p->defn);
+			fprintf(traceout, "%s:\t%s\n", name, p->defn);
 		else {
-			real = builtin_realname(p->type);
-			if (real == NULL)
-				real = null;
-			fprintf(traceout, "%s:\t<%s>\n", p->name, real);
-	    	}
+			fprintf(traceout, "%s:\t<%s>\n", name, p->defn);
+		}
 	} else
-		fprintf(traceout, "`%s'\t`%s'\n", p->name, p->defn);
+		fprintf(traceout, "`%s'\t`%s'\n", name, p->defn);
 }
 
 /*
@@ -679,17 +651,14 @@
 dodump(const char *argv[], int argc)
 {
 	int n;
-	ndptr p;
+	struct macro_definition *p;
 
 	if (argc > 2) {
 		for (n = 2; n < argc; n++)
-			if ((p = lookup(argv[n])) != nil)
-				dump_one_def(p);
-	} else {
-		for (n = 0; n < HASHSIZE; n++)
-			for (p = hashtab[n]; p != nil; p = p->nxtptr)
-				dump_one_def(p);
-	}
+			if ((p = lookup_macro_definition(argv[n])) != NULL)
+				dump_one_def(argv[n], p);
+	} else
+		macro_for_all(dump_one_def);
 }
 
 /*
@@ -734,15 +703,10 @@
 doincl(const char *ifile)
 {
 	if (ilevel + 1 == MAXINP)
-		errx(1, "%s at line %lu: too many include files.",
-		    CURRENT_NAME, CURRENT_LINE);
+		m4errx(1, "too many include files.");
 	if (fopen_trypath(infile+ilevel+1, ifile) != NULL) {
 		ilevel++;
-		if ((inname[ilevel] = strdup(ifile)) == NULL)
-			err(1, NULL);
-		inlineno[ilevel] = 1;
 		bbase[ilevel] = bufbase = bp;
-		emitline();
 		return (1);
 	} else
 		return (0);
@@ -760,97 +724,74 @@
 	int c;
 
 	if ((pf = fopen(pfile, "r")) != NULL) {
-		fprintf(active, "#line 1 \"%s\"\n", pfile);
+		if (synch_lines)
+		    fprintf(active, "#line 1 \"%s\"\n", pfile);
 		while ((c = getc(pf)) != EOF)
 			putc(c, active);
 		(void) fclose(pf);
-		emitline();
+		emit_synchline();
 		return (1);
 	} else
 		return (0);
 }
 #endif
 
-static void
-gnu_dochq(const char *argv[], int ac)
-{
-	/* In gnu-m4 mode, the only way to restore quotes is to have no
-	 * arguments at all. */
-	if (ac == 2) {
-		lquote[0] = LQUOTE, lquote[1] = EOS;
-		rquote[0] = RQUOTE, rquote[1] = EOS;
-	} else {
-		strlcpy(lquote, argv[2], sizeof(lquote));
-		if(ac > 3)
-			strlcpy(rquote, argv[3], sizeof(rquote));
-		else
-			rquote[0] = EOS;
-	}
-}
-
 /*
  * dochq - change quote characters
  */
 static void
-dochq(const char *argv[], int argc)
+dochq(const char *argv[], int ac)
 {
-	if (argc > 2) {
-		if (*argv[2])
-			strlcpy(lquote, argv[2], sizeof(lquote));
-		else {
-			lquote[0] = LQUOTE;
-			lquote[1] = EOS;
+	if (ac == 2) {
+		lquote[0] = LQUOTE; lquote[1] = EOS;
+		rquote[0] = RQUOTE; rquote[1] = EOS;
+	} else {
+		strlcpy(lquote, argv[2], sizeof(lquote));
+		if (ac > 3) {
+			strlcpy(rquote, argv[3], sizeof(rquote));
+		} else {
+			rquote[0] = ECOMMT; rquote[1] = EOS;
 		}
-		if (argc > 3) {
-			if (*argv[3])
-				strlcpy(rquote, argv[3], sizeof(rquote));
-		} else
-			strcpy(rquote, lquote);
-	} else {
-		lquote[0] = LQUOTE, lquote[1] = EOS;
-		rquote[0] = RQUOTE, rquote[1] = EOS;
 	}
 }
 
-static void
-gnu_dochc(const char *argv[], int ac)
-{
-	/* In gnu-m4 mode, no arguments mean no comment
-	 * arguments at all. */
-	if (ac == 2) {
-		scommt[0] = EOS;
-		ecommt[0] = EOS;
-	} else {
-		if (*argv[2])
-			strlcpy(scommt, argv[2], sizeof(scommt));
-		else
-			scommt[0] = SCOMMT, scommt[1] = EOS;
-		if(ac > 3 && *argv[3])
-			strlcpy(ecommt, argv[3], sizeof(ecommt));
-		else
-			ecommt[0] = ECOMMT, ecommt[1] = EOS;
-	}
-}
 /*
  * dochc - change comment characters
  */
 static void
 dochc(const char *argv[], int argc)
 {
-	if (argc > 2) {
-		if (*argv[2])
-			strlcpy(scommt, argv[2], sizeof(scommt));
-		if (argc > 3) {
-			if (*argv[3])
-				strlcpy(ecommt, argv[3], sizeof(ecommt));
+/* XXX Note that there is no difference between no argument and a single
+ * empty argument.
+ */
+	if (argc == 2) {
+		scommt[0] = EOS;
+		ecommt[0] = EOS;
+	} else {
+		strlcpy(scommt, argv[2], sizeof(scommt));
+		if (argc == 3) {
+			ecommt[0] = ECOMMT; ecommt[1] = EOS;
+		} else {
+			strlcpy(ecommt, argv[3], sizeof(ecommt));
 		}
+	}
+}
+
+/*
+ * dom4wrap - expand text at EOF
+ */
+static void
+dom4wrap(const char *text)
+{
+	if (wrapindex >= maxwraps) {
+		if (maxwraps == 0)
+			maxwraps = 16;
 		else
-			ecommt[0] = ECOMMT, ecommt[1] = EOS;
+			maxwraps *= 2;
+		m4wraps = xrealloc(m4wraps, maxwraps * sizeof(*m4wraps),
+		   "too many m4wraps");
 	}
-	else {
-		scommt[0] = SCOMMT, scommt[1] = EOS;
-		ecommt[0] = ECOMMT, ecommt[1] = EOS;
-	}
+	m4wraps[wrapindex++] = xstrdup(text);
 }
 
 /*
@@ -867,14 +808,14 @@
 			resizedivs(n + 10);
 		else
 			n = 0;		/* bitbucket */
-    	}
+	}
 
 	if (n < 0)
 		n = 0;		       /* bitbucket */
 	if (outfile[n] == NULL) {
 		char fname[] = _PATH_DIVNAME;
 
-		if ((fd = mkstemp(fname)) < 0 ||
+		if ((fd = mkstemp(fname)) < 0 || 
 			(outfile[n] = fdopen(fd, "w+")) == NULL)
 				err(1, "%s: cannot divert", fname);
 		if (unlink(fname) == -1)
@@ -895,10 +836,15 @@
 
 	if (argc > 2) {
 		for (ind = 2; ind < argc; ind++) {
-			n = atoi(argv[ind]);
-			if (n > 0 && n < maxout && outfile[n] != NULL)
-				getdiv(n);
-
+			const char *errstr;
+			n = strtonum(argv[ind], 1, INT_MAX, &errstr);
+			if (errstr) {
+				if (errno == EINVAL && mimic_gnu)
+					getdivfile(argv[ind]);
+			} else {
+				if (n < maxout && outfile[n] != NULL)
+					getdiv(n);
+			}
 		}
 	}
 	else
@@ -931,7 +877,7 @@
 #endif
 	if (fc >= ap && fc < ap + strlen(ap))
 		for (k = fc + nc - 1; k >= fc; k--)
-			putback(*k);
+			pushback(*k);
 }
 
 /*
@@ -939,25 +885,11 @@
  * map every character of s1 that is specified in from
  * into s3 and replace in s. (source s1 remains untouched)
  *
- * This is a standard implementation of map(s,from,to) function of ICON
- * language. Within mapvec, we replace every character of "from" with
- * the corresponding character in "to". If "to" is shorter than "from",
- * than the corresponding entries are null, which means that those
- * characters dissapear altogether. Furthermore, imagine
- * map(dest, "sourcestring", "srtin", "rn..*") type call. In this case,
- * `s' maps to `r', `r' maps to `n' and `n' maps to `*'. Thus, `s'
- * ultimately maps to `*'. In order to achieve this effect in an efficient
- * manner (i.e. without multiple passes over the destination string), we
- * loop over mapvec, starting with the initial source character. if the
- * character value (dch) in this location is different than the source
- * character (sch), sch becomes dch, once again to index into mapvec, until
- * the character value stabilizes (i.e. sch = dch, in other words
- * mapvec[n] == n). Even if the entry in the mapvec is null for an ordinary
- * character, it will stabilize, since mapvec[0] == 0 at all times. At the
- * end, we restore mapvec* back to normal where mapvec[n] == n for
- * 0 <= n <= 127. This strategy, along with the restoration of mapvec, is
- * about 5 times faster than any algorithm that makes multiple passes over
- * destination string.
+ * This is derived from the a standard implementation of map(s,from,to) 
+ * function of ICON language. Within mapvec, we replace every character 
+ * of "from" with the corresponding character in "to". 
+ * If "to" is shorter than "from", than the corresponding entries are null, 
+ * which means that those characters dissapear altogether. 
  */
 static void
 map(char *dest, const char *src, const char *from, const char *to)
@@ -966,6 +898,8 @@
 	unsigned char sch, dch;
 	static char frombis[257];
 	static char tobis[257];
+	int i;
+	char seen[256];
 	static unsigned char mapvec[256] = {
 	    0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
 	    19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
@@ -1000,17 +934,21 @@
 	 * create a mapping between "from" and
 	 * "to"
 	 */
-		while (*from)
-			mapvec[(unsigned char)(*from++)] = (*to) ?
-				(unsigned char)(*to++) : 0;
+		for (i = 0; i < 256; i++)
+			seen[i] = 0;
+		while (*from) {
+			if (!seen[(unsigned char)(*from)]) {
+				mapvec[(unsigned char)(*from)] = (unsigned char)(*to);
+				seen[(unsigned char)(*from)] = 1;
+			}
+			from++;
+			if (*to)
+				to++;
+		}
 
 		while (*src) {
 			sch = (unsigned char)(*src++);
 			dch = mapvec[sch];
-			while (dch != sch) {
-				sch = dch;
-				dch = mapvec[sch];
-			}
 			if ((*dest = (char)dch))
 				dest++;
 		}
@@ -1040,12 +978,23 @@
 	while(*src) {
 		if (src[1] == '-' && src[2]) {
 			unsigned char i;
-			for (i = (unsigned char)src[0];
-			    i <= (unsigned char)src[2]; i++) {
-				*p++ = i;
-				if (p == end) {
-					*p = '\0';
-					return buffer;
+			if ((unsigned char)src[0] <= (unsigned char)src[2]) {
+				for (i = (unsigned char)src[0]; 
+				    i <= (unsigned char)src[2]; i++) {
+					*p++ = i;
+					if (p == end) {
+						*p = '\0';
+						return buffer;
+					}
+				}
+			} else {
+				for (i = (unsigned char)src[0]; 
+				    i >= (unsigned char)src[2]; i--) {
+					*p++ = i;
+					if (p == end) {
+						*p = '\0';
+						return buffer;
+					}
 				}
 			}
 			src += 3;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.bin/m4/expr.c
--- a/head/usr.bin/m4/expr.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/usr.bin/m4/expr.c	Tue Dec 06 20:26:16 2011 +0200
@@ -1,640 +1,47 @@
-/*	$OpenBSD: expr.c,v 1.14 2002/04/26 16:15:16 espie Exp $	*/
-/*	$NetBSD: expr.c,v 1.7 1995/09/28 05:37:31 tls Exp $	*/
+/* $OpenBSD: expr.c,v 1.18 2010/09/07 19:58:09 marco Exp $ */
+/*
+ * Copyright (c) 2004 Marc Espie <espie at cvs.openbsd.org>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, 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.
+ */
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD: head/usr.bin/m4/expr.c 228063 2011-11-28 13:32:39Z bapt $");
 
-/*
- * Copyright (c) 1989, 1993
- *	The Regents of the University of California.  All rights reserved.
- *
- * This code is derived from software contributed to Berkeley by
- * Ozan Yigit at York University.
- *
- * 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.
- * 4. Neither the name of the University nor the names of its contributors
- *    may be used to endorse or promote products derived from this software
- *    without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#ifndef lint
-#if 0
-static char sccsid[] = "@(#)expr.c	8.2 (Berkeley) 4/29/95";
-#else
-#if 0
-static char rcsid[] = "$OpenBSD: expr.c,v 1.14 2002/04/26 16:15:16 espie Exp $";
-#endif
-#endif
-#endif /* not lint */
-
-#include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/usr.bin/m4/expr.c 226422 2011-10-16 08:09:17Z ed $");
-
-#include <sys/types.h>
-#include <ctype.h>
-#include <err.h>
+#include <stdint.h>
+#include <stdio.h>
 #include <stddef.h>
-#include <stdio.h>
 #include "mdef.h"
 #include "extern.h"
 
-/*
- *      expression evaluator: performs a standard recursive
- *      descent parse to evaluate any expression permissible
- *      within the following grammar:
- *
- *      expr    :       query EOS
- *      query   :       lor
- *              |       lor "?" query ":" query
- *      lor     :       land { "||" land }
- *      land    :       bor { "&&" bor }
- *      bor     :       xor { "|" xor }
- *      xor     :       band { "^" eqrel }
- *      band    :       eqrel { "&" eqrel }
- *      eqrel   :       nerel { ("==" | "!=") nerel }
- *      nerel   :       shift { ("<" | ">" | "<=" | ">=") shift }
- *      shift   :       primary { ("<<" | ">>") primary }
- *      primary :       term { ("+" | "-") term }
- *      term    :       exponent { ("*" | "/" | "%") exponent }
- *      exponent:       unary { "**" unary }
- *      unary   :       factor
- *              |       ("+" | "-" | "~" | "!") unary
- *      factor  :       constant
- *              |       "(" query ")"
- *      constant:       num
- *              |       "'" CHAR "'"
- *      num     :       DIGIT
- *              |       DIGIT num
- *
- *
- *      This expression evaluator is lifted from a public-domain
- *      C Pre-Processor included with the DECUS C Compiler distribution.
- *      It is hacked somewhat to be suitable for m4.
- *
- *      Originally by:  Mike Lutz
- *                      Bob Harper
- */
+int32_t end_result;
+const char *copy_toeval;
+int yyerror(const char *msg);
 
-#define EQL     0
-#define NEQ     1
-#define LSS     2
-#define LEQ     3
-#define GTR     4
-#define GEQ     5
-#define OCTAL   8
-#define DECIMAL 10
-#define HEX	16
-
-static const char *nxtch;		       /* Parser scan pointer */
-static const char *where;
-
-static int query(int mayeval);
-static int lor(int mayeval);
-static int land(int mayeval);
-static int bor(int mayeval);
-static int xor(int mayeval);
-static int band(int mayeval);
-static int eqrel(int mayeval);
-static int nerel(int mayeval);
-static int shift(int mayeval);
-static int primary(int mayeval);
-static int term(int mayeval);
-static int exponent(int mayeval);
-static int unary(int mayeval);
-static int factor(int mayeval);
-static int constant(int mayeval);
-static int num(int mayeval);
-static int skipws(void);
-static void experr(const char *);
-
-/*
- * For longjmp
- */
-#include <setjmp.h>
-static jmp_buf expjump;
-
-/*
- * macros:
- *      ungetch - Put back the last character examined.
- *      getch   - return the next character from expr string.
- */
-#define ungetch()       nxtch--
-#define getch()         *nxtch++
+extern void yy_scan_string(const char *);
+extern int yyparse(void);
 
 int
-expr(const char *expbuf)
+yyerror(const char *msg)
 {
-	int rval;
-
-	nxtch = expbuf;
-	where = expbuf;
-	if (setjmp(expjump) != 0)
-		return FALSE;
-
-	rval = query(1);
-	if (skipws() == EOS)
-		return rval;
-
-	printf("m4: ill-formed expression.\n");
-	return FALSE;
+	fprintf(stderr, "m4: %s in expr %s\n", msg, copy_toeval);
+	return(0);
 }
 
-/*
- * query : lor | lor '?' query ':' query
- */
-static int
-query(int mayeval)
+int
+expr(const char *toeval)
 {
-	int result, true_val, false_val;
-
-	result = lor(mayeval);
-	if (skipws() != '?') {
-		ungetch();
-		return result;
-	}
-
-	true_val = query(result);
-	if (skipws() != ':')
-		experr("bad query: missing \":\"");
-
-	false_val = query(!result);
-	return result ? true_val : false_val;
+	copy_toeval = toeval;
+	yy_scan_string(toeval);
+	yyparse();
+	return end_result;
 }
-
-/*
- * lor : land { '||' land }
- */
-static int
-lor(int mayeval)
-{
-	int c, vl, vr;
-
-	vl = land(mayeval);
-	while ((c = skipws()) == '|') {
-		if (getch() != '|') {
-			ungetch();
-			break;
-		}
-		if (vl != 0)
-			mayeval = 0;
-		vr = land(mayeval);
-		vl = vl || vr;
-	}
-
-	ungetch();
-	return vl;
-}
-
-/*
- * land : not { '&&' not }
- */
-static int
-land(int mayeval)
-{
-	int c, vl, vr;
-
-	vl = bor(mayeval);
-	while ((c = skipws()) == '&') {
-		if (getch() != '&') {
-			ungetch();
-			break;
-		}
-		if (vl == 0)
-			mayeval = 0;
-		vr = bor(mayeval);
-		vl = vl && vr;
-	}
-
-	ungetch();
-	return vl;
-}
-
-/*
- * bor : xor { "|" xor }
- */
-static int
-bor(int mayeval)
-{
-	int vl, vr, c, cr;
-
-	vl = xor(mayeval);
-	while ((c = skipws()) == '|') {
-		cr = getch();
-		ungetch();
-		if (cr == '|')
-			break;
-		vr = xor(mayeval);
-		vl |= vr;
-	}
-	ungetch();
-	return (vl);
-}
-
-/*
- * xor : band { "^" band }
- */
-static int
-xor(int mayeval)
-{
-	int vl, vr, c;
-
-	vl = band(mayeval);
-	while ((c = skipws()) == '^') {
-		vr = band(mayeval);
-		vl ^= vr;
-	}
-	ungetch();
-	return (vl);
-}
-
-/*
- * band : eqrel { "&" eqrel }
- */
-static int
-band(int mayeval)
-{
-	int c, cr, vl, vr;
-
-	vl = eqrel(mayeval);
-	while ((c = skipws()) == '&') {
-		cr = getch();
-		ungetch();
-		if (cr == '&')
-			break;
-		vr = eqrel(mayeval);
-		vl &= vr;
-	}
-	ungetch();
-	return vl;
-}
-
-/*
- * eqrel : nerel { ("==" | "!=" ) nerel }
- */
-static int
-eqrel(int mayeval)
-{
-	int vl, vr, c, cr;
-
-	vl = nerel(mayeval);
-	while ((c = skipws()) == '!' || c == '=') {
-		if ((cr = getch()) != '=') {
-			ungetch();
-			break;
-		}
-		vr = nerel(mayeval);
-		switch (c) {
-		case '=':
-			vl = (vl == vr);
-			break;
-		case '!':
-			vl = (vl != vr);
-			break;
-		}
-	}
-	ungetch();
-	return vl;
-}
-
-/*
- * nerel : shift { ("<=" | ">=" | "<" | ">") shift }
- */
-static int
-nerel(int mayeval)
-{
-	int vl, vr, c, cr;
-
-	vl = shift(mayeval);
-	while ((c = skipws()) == '<' || c == '>') {
-		if ((cr = getch()) != '=') {
-			ungetch();
-			cr = '\0';
-		}
-		vr = shift(mayeval);
-		switch (c) {
-		case '<':
-			vl = (cr == '\0') ? (vl < vr) : (vl <= vr);
-			break;
-		case '>':
-			vl = (cr == '\0') ? (vl > vr) : (vl >= vr);
-			break;
-		}
-	}
-	ungetch();
-	return vl;
-}
-
-/*
- * shift : primary { ("<<" | ">>") primary }
- */
-static int
-shift(int mayeval)
-{
-	int vl, vr, c;
-
-	vl = primary(mayeval);
-	while (((c = skipws()) == '<' || c == '>') && getch() == c) {
-		vr = primary(mayeval);
-
-		if (c == '<')
-			vl <<= vr;
-		else
-			vl >>= vr;
-	}
-
-	if (c == '<' || c == '>')
-		ungetch();
-	ungetch();
-	return vl;
-}
-
-/*
- * primary : term { ("+" | "-") term }
- */
-static int
-primary(int mayeval)
-{
-	int c, vl, vr;
-
-	vl = term(mayeval);
-	while ((c = skipws()) == '+' || c == '-') {
-		vr = term(mayeval);
-
-		if (c == '+')
-			vl += vr;
-		else
-			vl -= vr;
-	}
-
-	ungetch();
-	return vl;
-}
-
-/*
- * term : exponent { ("*" | "/" | "%") exponent }
- */
-static int
-term(int mayeval)
-{
-	int c, vl, vr;
-
-	vl = exponent(mayeval);
-	while ((c = skipws()) == '*' || c == '/' || c == '%') {
-		vr = exponent(mayeval);
-
-		switch (c) {
-		case '*':
-			vl *= vr;
-			break;
-		case '/':
-			if (!mayeval)
-				/* short-circuit */;
-			else if (vr == 0)
-				errx(1, "division by zero in eval.");
-			else
-				vl /= vr;
-			break;
-		case '%':
-			if (!mayeval)
-				/* short-circuit */;
-			else if (vr == 0)
-				errx(1, "modulo zero in eval.");
-			else
-				vl %= vr;
-			break;
-		}
-	}
-	ungetch();
-	return vl;
-}
-
-/*
- * exponent : unary { "**" exponent }
- */
-static int
-exponent(int mayeval)
-{
-	int c, vl, vr, n;
-
-	vl = unary(mayeval);
-	while ((c = skipws()) == '*') {
-		if (getch() != '*') {
-			ungetch();
-			break;
-		}
-		vr = unary(mayeval);
-		n = 1;
-		while (vr-- > 0)
-			n *= vl;
-		return n;
-	}
-
-	ungetch();
-	return vl;
-}
-
-/*
- * unary : factor | ("+" | "-" | "~" | "!") unary
- */
-static int
-unary(int mayeval)
-{
-	int val, c;
-
-	if ((c = skipws()) == '+' || c == '-' || c == '~' || c == '!') {
-		val = unary(mayeval);
-
-		switch (c) {
-		case '+':
-			return val;
-		case '-':
-			return -val;
-		case '~':
-			return ~val;
-		case '!':
-			return !val;
-		}
-	}
-
-	ungetch();
-	return factor(mayeval);
-}
-
-/*
- * factor : constant | '(' query ')'
- */
-static int
-factor(int mayeval)
-{
-	int val;
-
-	if (skipws() == '(') {
-		val = query(mayeval);
-		if (skipws() != ')')
-			experr("bad factor: missing \")\"");
-		return val;
-	}
-
-	ungetch();
-	return constant(mayeval);
-}
-
-/*
- * constant: num | 'char'
- * Note: constant() handles multi-byte constants
- */
-static int
-constant(int mayeval)
-{
-	int i;
-	int value;
-	int c;
-	int v[sizeof(int)];
-
-	if (skipws() != '\'') {
-		ungetch();
-		return num(mayeval);
-	}
-	for (i = 0; i < (ssize_t)sizeof(int); i++) {
-		if ((c = getch()) == '\'') {
-			ungetch();
-			break;
-		}
-		if (c == '\\') {
-			switch (c = getch()) {
-			case '0':
-			case '1':
-			case '2':
-			case '3':
-			case '4':
-			case '5':
-			case '6':
-			case '7':
-				ungetch();
-				c = num(mayeval);
-				break;
-			case 'n':
-				c = 012;
-				break;
-			case 'r':
-				c = 015;
-				break;
-			case 't':
-				c = 011;
-				break;
-			case 'b':
-				c = 010;
-				break;
-			case 'f':
-				c = 014;
-				break;
-			}
-		}
-		v[i] = c;
-	}
-	if (i == 0 || getch() != '\'')
-		experr("illegal character constant");
-	for (value = 0; --i >= 0;) {
-		value <<= 8;
-		value += v[i];
-	}
-	return value;
-}
-
-/*
- * num : digit | num digit
- */
-static int
-num(int mayeval __unused)
-{
-	int rval, c, base;
-	int ndig;
-
-	rval = 0;
-	ndig = 0;
-	c = skipws();
-	if (c == '0') {
-		c = skipws();
-		if (c == 'x' || c == 'X') {
-			base = HEX;
-			c = skipws();
-		} else {
-			base = OCTAL;
-			ndig++;
-		}
-	} else
-		base = DECIMAL;
-	for(;;) {
-		switch(c) {
-			case '8': case '9':
-				if (base == OCTAL)
-					goto bad_digit;
-				/*FALLTHRU*/
-			case '0': case '1': case '2': case '3':
-			case '4': case '5': case '6': case '7':
-				rval *= base;
-				rval += c - '0';
-				break;
-			case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
-				c = tolower(c);
-			case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
-				if (base == HEX) {
-					rval *= base;
-					rval += c - 'a' + 10;
-					break;
-				}
-				/*FALLTHRU*/
-			default:
-				goto bad_digit;
-		}
-		c = getch();
-		ndig++;
-	}
-bad_digit:
-	ungetch();
-
-	if (ndig == 0)
-		experr("bad constant");
-
-	return rval;
-}
-
-/*
- * Skip over any white space and return terminating char.
- */
-static int
-skipws(void)
-{
-	int c;
-
-	while ((c = getch()) <= ' ' && c > EOS)
-		;
-	return c;
-}
-
-/*
- * resets environment to eval(), prints an error
- * and forces eval to return FALSE.
- */
-static void
-experr(const char *msg)
-{
-	printf("m4: %s in expr %s.\n", msg, where);
-	longjmp(expjump, -1);
-}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.bin/m4/extern.h
--- a/head/usr.bin/m4/extern.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/usr.bin/m4/extern.h	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-/*	$OpenBSD: extern.h,v 1.29 2002/02/16 21:27:48 millert Exp $	*/
+/*	$OpenBSD: extern.h,v 1.51 2011/09/27 07:24:02 espie Exp $	*/
 /*	$NetBSD: extern.h,v 1.3 1996/01/13 23:25:24 pk Exp $	*/
 
 /*-
@@ -16,7 +16,7 @@
  * 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.
- * 4. Neither the name of the University nor the names of its contributors
+ * 3. Neither the name of the University nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
  *
@@ -33,11 +33,11 @@
  * SUCH DAMAGE.
  *
  *	@(#)extern.h	8.1 (Berkeley) 6/6/93
- * $FreeBSD$
+ * $FreeBSD: head/usr.bin/m4/extern.h 228063 2011-11-28 13:32:39Z bapt $
  */
 
 /* eval.c */
-extern void	eval(const char *[], int, int);
+extern void	eval(const char *[], int, int, int);
 extern void	dodefine(const char *, const char *);
 extern unsigned long expansion_id;
 
@@ -45,7 +45,7 @@
 extern int	expr(const char *);
 
 /* gnum4.c */
-extern void 	addtoincludepath(const char *);
+extern void	addtoincludepath(const char *);
 extern struct input_file *fopen_trypath(struct input_file *, const char *);
 extern void doindir(const char *[], int);
 extern void dobuiltin(const char *[], int);
@@ -56,45 +56,67 @@
 extern void doprintfilename(struct input_file *);
 
 extern void doesyscmd(const char *);
-
+extern void getdivfile(const char *);
+extern void doformat(const char *[], int);
 
 /* look.c */
-extern ndptr	addent(const char *);
-extern unsigned	hash(const char *);
+
+#define FLAG_UNTRACED 0
+#define FLAG_TRACED 1
+#define FLAG_NO_TRACE 2
+
+extern void	init_macros(void);
 extern ndptr	lookup(const char *);
-extern void	remhash(const char *, int);
+extern void mark_traced(const char *, int);
+extern struct ohash macros;
+
+extern struct macro_definition *lookup_macro_definition(const char *);
+extern void	macro_define(const char *, const char *);
+extern void	macro_pushdef(const char *, const char *);
+extern void	macro_popdef(const char *);
+extern void	macro_undefine(const char *);
+extern void	setup_builtin(const char *, unsigned int);
+extern void	macro_for_all(void (*)(const char *, struct macro_definition *));
+#define macro_getdef(p)		((p)->d)
+#define macro_name(p)		((p)->name)
+#define macro_builtin_type(p)	((p)->builtin_type)
+#define is_traced(p) ((p)->trace_flags == FLAG_NO_TRACE ? (trace_flags & TRACE_ALL) : (p)->trace_flags)
+
+extern ndptr macro_getbuiltin(const char *);
 
 /* main.c */
 extern void outputstr(const char *);
-extern int builtin_type(const char *);
-extern const char *builtin_realname(int);
-extern void emitline(void);
+extern void do_emit_synchline(void);
+#define emit_synchline() do { if (synch_lines) do_emit_synchline(); } while(0)
 
 /* misc.c */
 extern void	chrsave(int);
-extern char 	*compute_prevep(void);
+extern char	*compute_prevep(void);
 extern void	getdiv(int);
 extern ptrdiff_t indx(const char *, const char *);
-extern void 	initspaces(void);
+extern void	initspaces(void);
 extern void	killdiv(void);
 extern void	onintr(int);
 extern void	pbnum(int);
+extern void	pbnumbase(int, int, int);
 extern void	pbunsigned(unsigned long);
 extern void	pbstr(const char *);
-extern void	putback(int);
-extern void	*xalloc(size_t);
+extern void	pushback(int);
+extern void	*xalloc(size_t, const char *fmt, ...);
+extern void	*xrealloc(void *, size_t, const char *fmt, ...);
 extern char	*xstrdup(const char *);
 extern void	usage(void);
 extern void	resizedivs(int);
 extern size_t	buffer_mark(void);
 extern void	dump_buffer(FILE *, size_t);
+extern void	m4errx(int, const char *, ...);
 
-extern int 	obtain_char(struct input_file *);
+extern int	obtain_char(struct input_file *);
 extern void	set_input(struct input_file *, FILE *, const char *);
 extern void	release_input(struct input_file *);
 
-/* speeded-up versions of chrsave/putback */
-#define PUTBACK(c)				\
+/* speeded-up versions of chrsave/pushback */
+#define PUSHBACK(c)				\
 	do {					\
 		if (bp >= endpbb)		\
 			enlarge_bufspace();	\
@@ -111,60 +133,44 @@
 /* and corresponding exposure for local symbols */
 extern void enlarge_bufspace(void);
 extern void enlarge_strspace(void);
-extern char *endpbb;
+extern unsigned char *endpbb;
 extern char *endest;
 
 /* trace.c */
-extern void mark_traced(const char *, int);
-extern int is_traced(const char *);
+extern unsigned int trace_flags;
+#define TRACE_ALL	512
 extern void trace_file(const char *);
-extern ssize_t trace(const char **, int, struct input_file *);
+extern size_t trace(const char **, int, struct input_file *);
 extern void finish_trace(size_t);
-extern int traced_macros;
 extern void set_trace_flags(const char *);
 extern FILE *traceout;
 
-extern ndptr hashtab[];		/* hash table for macros etc. */
 extern stae *mstack;		/* stack of m4 machine */
 extern char *sstack;		/* shadow stack, for string space extension */
 extern FILE *active;		/* active output file pointer */
 extern struct input_file infile[];/* input file stack (0=stdin) */
-extern char *inname[];		/* names of these input files */
-extern int inlineno[];		/* current number in each input file */
 extern FILE **outfile;		/* diversion array(0=bitbucket) */
 extern int maxout;		/* maximum number of diversions */
-extern int fp; 			/* m4 call frame pointer */
+extern int fp;			/* m4 call frame pointer */
 extern int ilevel;		/* input file stack pointer */
 extern int oindex;		/* diversion index. */
 extern int sp;			/* current m4 stack pointer */
-extern char *bp;		/* first available character */
-extern char *buf;		/* push-back buffer */
-extern char *bufbase;		/* buffer base for this ilevel */
-extern char *bbase[];		/* buffer base per ilevel */
+extern unsigned char *bp;	/* first available character */
+extern unsigned char *buf;	/* push-back buffer */
+extern unsigned char *bufbase;	/* buffer base for this ilevel */
+extern unsigned char *bbase[];	/* buffer base per ilevel */
 extern char ecommt[MAXCCHARS+1];/* end character for comment */
 extern char *ep;		/* first free char in strspace */
 extern char lquote[MAXCCHARS+1];/* left quote character (`) */
-extern const char *m4wraps;	/* m4wrap string default. */
-extern char null[];		/* as it says.. just a null. */
+extern char **m4wraps;		/* m4wrap string default. */
+extern int maxwraps;		/* size of m4wraps array */
+extern int wrapindex;		/* current index in m4wraps */
+
+extern const char *null;	/* as it says.. just a null. */
 extern char rquote[MAXCCHARS+1];/* right quote character (') */
 extern char scommt[MAXCCHARS+1];/* start character for comment */
-extern int synccpp;		/* Line synchronisation for C preprocessor */
+extern int  synch_lines;	/* line synchronisation directives */
 
 extern int mimic_gnu;		/* behaves like gnu-m4 */
+extern int prefix_builtins;	/* prefix builtin macros with m4_ */
 
-/* get a possibly pushed-back-character, increment lineno if need be */
-static __inline int gpbc(void)
-{
-	int chscratch;		/* Scratch space. */
-
-	if (bp > bufbase) {
-		if (*--bp)
-			return ((unsigned char)*bp);
-		else
-			return (EOF);
-	}
-	chscratch = obtain_char(infile+ilevel);
-	if (chscratch == '\n')
-		++inlineno[ilevel];
-	return (chscratch);
-}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.bin/m4/gnum4.c
--- a/head/usr.bin/m4/gnum4.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/usr.bin/m4/gnum4.c	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-/* $OpenBSD: gnum4.c,v 1.18 2002/04/26 16:15:16 espie Exp $ */
+/* $OpenBSD: gnum4.c,v 1.42 2011/11/06 12:25:43 espie Exp $ */
 
 /*
  * Copyright (c) 1999 Marc Espie
@@ -24,9 +24,8 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  */
-
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/usr.bin/m4/gnum4.c 227241 2011-11-06 18:49:48Z ed $");
+__FBSDID("$FreeBSD: head/usr.bin/m4/gnum4.c 228063 2011-11-28 13:32:39Z bapt $");
 
 /*
  * functions needed to support gnu-m4 extensions, including a fake freezing
@@ -36,13 +35,13 @@
 #include <sys/types.h>
 #include <sys/wait.h>
 #include <ctype.h>
+#include <err.h>
 #include <paths.h>
 #include <regex.h>
 #include <stddef.h>
 #include <stdlib.h>
 #include <stdio.h>
 #include <string.h>
-#include <err.h>
 #include <errno.h>
 #include <unistd.h>
 #include "mdef.h"
@@ -60,7 +59,7 @@
  * Then M4PATH env variable
  */
 
-static struct path_entry {
+struct path_entry {
 	char *name;
 	struct path_entry *next;
 } *first, *last;
@@ -133,7 +132,7 @@
 
 	for (pe = first; pe; pe = pe->next) {
 		snprintf(path, sizeof(path), "%s/%s", pe->name, filename);
-		if ((f = fopen(path, "r")) != NULL) {
+		if ((f = fopen(path, "r")) != 0) {
 			set_input(i, f, path);
 			return i;
 		}
@@ -162,25 +161,28 @@
 void
 doindir(const char *argv[], int argc)
 {
-	ndptr p;
+	ndptr n;
+	struct macro_definition *p = NULL;
 
-	p = lookup(argv[2]);
-	if (p == NULL)
-		errx(1, "undefined macro %s", argv[2]);
+	n = lookup(argv[2]);
+	if (n == NULL || (p = macro_getdef(n)) == NULL)
+		m4errx(1, "indir: undefined macro %s.", argv[2]);
 	argv[1] = p->defn;
-	eval(argv+1, argc-1, p->type);
+
+	eval(argv+1, argc-1, p->type, is_traced(n));
 }
 
 void
 dobuiltin(const char *argv[], int argc)
 {
-	int n;
+	ndptr p;
+
 	argv[1] = NULL;
-	n = builtin_type(argv[2]);
-	if (n != -1)
-		eval(argv+1, argc-1, n);
+	p = macro_getbuiltin(argv[2]);
+	if (p != NULL)
+		eval(argv+1, argc-1, macro_builtin_type(p), is_traced(p));
 	else
-		errx(1, "unknown builtin %s", argv[2]);
+		m4errx(1, "unknown builtin %s.", argv[2]);
 }
 
 
@@ -198,7 +200,7 @@
 static void do_subst(const char *, regex_t *, const char *, regmatch_t *);
 static void do_regexpindex(const char *, regex_t *, regmatch_t *);
 static void do_regexp(const char *, regex_t *, const char *, regmatch_t *);
-static void add_sub(size_t, const char *, regex_t *, regmatch_t *);
+static void add_sub(int, const char *, regex_t *, regmatch_t *);
 static void add_replace(const char *, regex_t *, const char *, regmatch_t *);
 #define addconstantstring(s) addchars((s), sizeof(s)-1)
 
@@ -212,9 +214,7 @@
 			bufsize = 1024;
 		else
 			bufsize *= 2;
-		buffer = realloc(buffer, bufsize);
-		if (buffer == NULL)
-			errx(1, "out of memory");
+		buffer = xrealloc(buffer, bufsize, NULL);
 	}
 	memcpy(buffer+current, c, n);
 	current += n;
@@ -228,9 +228,7 @@
 			bufsize = 1024;
 		else
 			bufsize *= 2;
-		buffer = realloc(buffer, bufsize);
-		if (buffer == NULL)
-			errx(1, "out of memory");
+		buffer = xrealloc(buffer, bufsize, NULL);
 	}
 	buffer[current++] = c;
 }
@@ -247,20 +245,21 @@
 static void
 exit_regerror(int er, regex_t *re)
 {
-	size_t 	errlen;
-	char 	*errbuf;
+	size_t	errlen;
+	char	*errbuf;
 
 	errlen = regerror(er, re, NULL, 0);
-	errbuf = xalloc(errlen);
+	errbuf = xalloc(errlen,
+	    "malloc in regerror: %lu", (unsigned long)errlen);
 	regerror(er, re, errbuf, errlen);
-	errx(1, "regular expression error: %s", errbuf);
+	m4errx(1, "regular expression error: %s.", errbuf);
 }
 
 static void
-add_sub(size_t n, const char *string, regex_t *re, regmatch_t *pm)
+add_sub(int n, const char *string, regex_t *re, regmatch_t *pm)
 {
-	if (n > re->re_nsub)
-		warnx("No subexpression %zu", n);
+	if (n > (int)re->re_nsub)
+		warnx("No subexpression %d", n);
 	/* Subexpressions that did not match are
 	 * not an error.  */
 	else if (pm[n].rm_so != -1 &&
@@ -302,7 +301,7 @@
 				continue;
 			}
 		}
-	    	addchar(*p);
+		addchar(*p);
 	}
 }
 
@@ -386,6 +385,14 @@
 static char *
 twiddle(const char *p)
 {
+	/* + at start of regexp is a normal character for Gnu m4 */
+	if (*p == '^') {
+		addchar(*p);
+		p++;
+	}
+	if (*p == '+') {
+		addchar('\\');
+	}
 	/* This could use strcspn for speed... */
 	while (*p != '\0') {
 		if (*p == '\\') {
@@ -431,25 +438,46 @@
 void
 dopatsubst(const char *argv[], int argc)
 {
-	int error;
-	regex_t re;
-	regmatch_t *pmatch;
-
 	if (argc <= 3) {
 		warnx("Too few arguments to patsubst");
 		return;
 	}
-	error = regcomp(&re, mimic_gnu ? twiddle(argv[3]) : argv[3],
-	    REG_NEWLINE | REG_EXTENDED);
-	if (error != 0)
-		exit_regerror(error, &re);
+	/* special case: empty regexp */
+	if (argv[3][0] == '\0') {
+		const char *s;
+		size_t len;
+		if (argc > 4 && argv[4])
+			len = strlen(argv[4]);
+		else
+			len = 0;
+		for (s = argv[2]; *s != '\0'; s++) {
+			addchars(argv[4], len);
+			addchar(*s);
+		}
+	} else {
+		int error;
+		regex_t re;
+		regmatch_t *pmatch;
+		int mode = REG_EXTENDED;
+		size_t l = strlen(argv[3]);
 
-	pmatch = xalloc(sizeof(regmatch_t) * (re.re_nsub+1));
-	do_subst(argv[2], &re,
-	    argc != 4 && argv[4] != NULL ? argv[4] : "", pmatch);
+		if (!mimic_gnu ||
+		    (argv[3][0] == '^') ||
+		    (l > 0 && argv[3][l-1] == '$'))
+			mode |= REG_NEWLINE;
+
+		error = regcomp(&re, mimic_gnu ? twiddle(argv[3]) : argv[3],
+		    mode);
+		if (error != 0)
+			exit_regerror(error, &re);
+
+		pmatch = xalloc(sizeof(regmatch_t) * (re.re_nsub+1), NULL);
+		do_subst(argv[2], &re,
+		    argc > 4 && argv[4] != NULL ? argv[4] : "", pmatch);
+		free(pmatch);
+		regfree(&re);
+	}
 	pbstr(getstring());
-	free(pmatch);
-	regfree(&re);
 }
 
 void
@@ -463,13 +491,20 @@
 		warnx("Too few arguments to regexp");
 		return;
 	}
+	/* special gnu case */
+	if (argv[3][0] == '\0' && mimic_gnu) {
+		if (argc == 4 || argv[4] == NULL)
+			return;
+		else
+			pbstr(argv[4]);
+	}
 	error = regcomp(&re, mimic_gnu ? twiddle(argv[3]) : argv[3],
-	    REG_EXTENDED);
+	    REG_EXTENDED|REG_NEWLINE);
 	if (error != 0)
 		exit_regerror(error, &re);
 
-	pmatch = xalloc(sizeof(regmatch_t) * (re.re_nsub+1));
-	if (argv[4] == NULL || argc == 4)
+	pmatch = xalloc(sizeof(regmatch_t) * (re.re_nsub+1), NULL);
+	if (argc == 4 || argv[4] == NULL)
 		do_regexpindex(argv[2], &re, pmatch);
 	else
 		do_regexp(argv[2], &re, argv[4], pmatch);
@@ -478,16 +513,111 @@
 }
 
 void
+doformat(const char *argv[], int argc)
+{
+	const char *format = argv[2];
+	int pos = 3;
+	int left_padded;
+	long width;
+	size_t l;
+	const char *thisarg = NULL;
+	char temp[2];
+	long extra;
+
+	while (*format != 0) {
+		if (*format != '%') {
+			addchar(*format++);
+			continue;
+		}
+
+		format++;
+		if (*format == '%') {
+			addchar(*format++);
+			continue;
+		}
+		if (*format == 0) {
+			addchar('%');
+			break;
+		}
+
+		if (*format == '*') {
+			format++;
+			if (pos >= argc)
+				m4errx(1,
+				    "Format with too many format specifiers.");
+			width = strtol(argv[pos++], NULL, 10);
+		} else {
+			width = strtol(format, __DECONST(char **,&format), 10);
+		}
+		if (width < 0) {
+			left_padded = 1;
+			width = -width;
+		} else {
+			left_padded = 0;
+		}
+		if (*format == '.') {
+			format++;
+			if (*format == '*') {
+				format++;
+				if (pos >= argc)
+					m4errx(1,
+					    "Format with too many format specifiers.");
+				extra = strtol(argv[pos++], NULL, 10);
+			} else {
+				extra = strtol(format, __DECONST(char **, &format), 10);
+			}
+		} else {
+			extra = LONG_MAX;
+		}
+		if (pos >= argc)
+			m4errx(1, "Format with too many format specifiers.");
+		switch(*format) {
+		case 's':
+			thisarg = argv[pos++];
+			break;
+		case 'c':
+			temp[0] = strtoul(argv[pos++], NULL, 10);
+			temp[1] = 0;
+			thisarg = temp;
+			break;
+		default:
+			m4errx(1, "Unsupported format specification: %s.",
+			    argv[2]);
+		}
+		format++;
+		l = strlen(thisarg);
+		if ((long)l > extra)
+			l = extra;
+		if (!left_padded) {
+			while ((long)l < width--)
+				addchar(' ');
+		}
+		addchars(thisarg, l);
+		if (left_padded) {
+			while ((long)l < width--)
+				addchar(' ');
+		}
+	}
+	pbstr(getstring());
+}
+
+void
 doesyscmd(const char *cmd)
 {
 	int p[2];
 	pid_t pid, cpid;
+	char *argv[4];
 	int cc;
 	int status;
 
 	/* Follow gnu m4 documentation: first flush buffers. */
 	fflush(NULL);
 
+	argv[0] = __DECONST(char *, "sh");
+	argv[1] = __DECONST(char *, "-c");
+	argv[2] = __DECONST(char *, cmd);
+	argv[3] = NULL;
+
 	/* Just set up standard output, share stderr and stdin with m4 */
 	if (pipe(p) == -1)
 		err(1, "bad pipe");
@@ -499,7 +629,7 @@
 		(void) close(p[0]);
 		(void) dup2(p[1], 1);
 		(void) close(p[1]);
-		execl(_PATH_BSHELL, "sh", "-c", cmd, (char *)NULL);
+		execv(_PATH_BSHELL, argv);
 		exit(1);
 	default:
 		/* Read result in two stages, since m4's buffer is
@@ -518,3 +648,18 @@
 		pbstr(getstring());
 	}
 }
+
+void
+getdivfile(const char *name)
+{
+	FILE *f;
+	int c;
+
+	f = fopen(name, "r");
+	if (!f)
+		return;
+
+	while ((c = getc(f))!= EOF)
+		putc(c, active);
+	(void) fclose(f);
+}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.bin/m4/lib/ohash.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/usr.bin/m4/lib/ohash.h	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,75 @@
+#ifndef OHASH_H
+#define OHASH_H
+/* $OpenBSD: ohash.h,v 1.8 2005/12/29 18:54:47 jaredy Exp $ */
+/* ex:ts=8 sw=4: 
+ */
+
+/* Copyright (c) 1999, 2004 Marc Espie <espie at openbsd.org>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, 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.
+ *
+ * $FreeBSD: head/usr.bin/m4/lib/ohash.h 228063 2011-11-28 13:32:39Z bapt $
+ */
+
+/* Open hashing support. 
+ * Open hashing was chosen because it is much lighter than other hash
+ * techniques, and more efficient in most cases.
+ */
+
+struct ohash_info {
+	ptrdiff_t key_offset;
+	void *data;	/* user data */
+	void *(*halloc)(size_t, void *);
+	void (*hfree)(void *, size_t, void *);
+	void *(*alloc)(size_t, void *);
+};
+
+struct _ohash_record;
+
+struct ohash {
+	struct _ohash_record 	*t;
+	struct ohash_info 	info;
+	unsigned int 		size;
+	unsigned int 		total;
+	unsigned int 		deleted;
+};
+
+/* For this to be tweakable, we use small primitives, and leave part of the
+ * logic to the client application.  e.g., hashing is left to the client
+ * application.  We also provide a simple table entry lookup that yields
+ * a hashing table index (opaque) to be used in find/insert/remove.
+ * The keys are stored at a known position in the client data.
+ */
+__BEGIN_DECLS
+void ohash_init(struct ohash *, unsigned, struct ohash_info *);
+void ohash_delete(struct ohash *);
+
+unsigned int ohash_lookup_interval(struct ohash *, const char *,
+	    const char *, u_int32_t);
+unsigned int ohash_lookup_memory(struct ohash *, const char *,
+	    size_t, u_int32_t);
+void *ohash_find(struct ohash *, unsigned int);
+void *ohash_remove(struct ohash *, unsigned int);
+void *ohash_insert(struct ohash *, unsigned int, void *);
+void *ohash_first(struct ohash *, unsigned int *);
+void *ohash_next(struct ohash *, unsigned int *);
+unsigned int ohash_entries(struct ohash *);
+
+void *ohash_create_entry(struct ohash_info *, const char *, const char **);
+u_int32_t ohash_interval(const char *, const char **);
+
+unsigned int ohash_qlookupi(struct ohash *, const char *, const char **);
+unsigned int ohash_qlookup(struct ohash *, const char *);
+__END_DECLS
+#endif
+
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.bin/m4/lib/ohash_create_entry.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/usr.bin/m4/lib/ohash_create_entry.c	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,40 @@
+/* $OpenBSD: ohash_create_entry.c,v 1.2 2004/06/22 20:00:16 espie Exp $ */
+/* ex:ts=8 sw=4: 
+ */
+
+/* Copyright (c) 1999, 2004 Marc Espie <espie at openbsd.org>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, 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.
+ */
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD: head/usr.bin/m4/lib/ohash_create_entry.c 228063 2011-11-28 13:32:39Z bapt $");
+
+#include "ohash_int.h"
+
+/* This handles the common case of variable length keys, where the 
+ * key is stored at the end of the record.
+ */
+void *
+ohash_create_entry(struct ohash_info *i, const char *start, const char **end)
+{
+	char *p;
+
+	if (!*end)
+		*end = start + strlen(start);
+	p = (i->alloc)(i->key_offset + (*end - start) + 1, i->data);
+	if (p) {
+	    memcpy(p+i->key_offset, start, *end-start);
+	    p[i->key_offset + (*end - start)] = '\0';
+	}
+	return (void *)p;
+}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.bin/m4/lib/ohash_delete.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/usr.bin/m4/lib/ohash_delete.c	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,33 @@
+/* $OpenBSD: ohash_delete.c,v 1.2 2004/06/22 20:00:16 espie Exp $ */
+/* ex:ts=8 sw=4: 
+ */
+
+/* Copyright (c) 1999, 2004 Marc Espie <espie at openbsd.org>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, 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.
+ */
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD: head/usr.bin/m4/lib/ohash_delete.c 228063 2011-11-28 13:32:39Z bapt $");
+
+#include "ohash_int.h"
+/* hash_delete only frees the hash structure. Use hash_first/hash_next
+ * to free entries as well.  */
+void 
+ohash_delete(struct ohash *h)
+{
+	(h->info.hfree)(h->t, sizeof(struct _ohash_record) * h->size,
+		h->info.data);
+#ifndef NDEBUG
+	h->t = NULL;
+#endif
+}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.bin/m4/lib/ohash_do.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/usr.bin/m4/lib/ohash_do.c	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,113 @@
+/* $OpenBSD: ohash_do.c,v 1.4 2004/06/22 20:00:16 espie Exp $ */
+/* ex:ts=8 sw=4: 
+ */
+
+/* Copyright (c) 1999, 2004 Marc Espie <espie at openbsd.org>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, 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.
+ */
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD: head/usr.bin/m4/lib/ohash_do.c 228063 2011-11-28 13:32:39Z bapt $");
+
+#include "ohash_int.h"
+
+static void ohash_resize(struct ohash *);
+
+static void 
+ohash_resize(struct ohash *h)
+{
+	struct _ohash_record *n;
+	unsigned int 	ns, j;
+	unsigned int	i, incr;
+
+	if (4 * h->deleted < h->total)
+		ns = h->size << 1;
+	else if (3 * h->deleted > 2 * h->total)
+		ns = h->size >> 1;
+	else
+		ns = h->size;
+	if (ns < MINSIZE)
+		ns = MINSIZE;
+#ifdef STATS_HASH
+	STAT_HASH_EXPAND++;
+	STAT_HASH_SIZE += ns - h->size;
+#endif
+	n = (h->info.halloc)(sizeof(struct _ohash_record) * ns, h->info.data);
+	if (!n)
+		return;
+
+	for (j = 0; j < h->size; j++) {
+		if (h->t[j].p != NULL && h->t[j].p != DELETED) {
+			i = h->t[j].hv % ns;
+			incr = ((h->t[j].hv % (ns - 2)) & ~1) + 1;
+			while (n[i].p != NULL) {
+				i += incr;
+				if (i >= ns)
+					i -= ns;
+		    	}
+			n[i].hv = h->t[j].hv;
+			n[i].p = h->t[j].p;
+		}
+	}
+	(h->info.hfree)(h->t, sizeof(struct _ohash_record) * h->size, 
+		h->info.data);
+	h->t = n;
+	h->size = ns;
+	h->total -= h->deleted;
+	h->deleted = 0;
+}
+
+void *
+ohash_remove(struct ohash *h, unsigned int i)
+{
+	void 		*result = __DECONST(void *, h->t[i].p);
+
+	if (result == NULL || result == DELETED)
+		return NULL;
+
+#ifdef STATS_HASH
+	STAT_HASH_ENTRIES--;
+#endif
+	h->t[i].p = DELETED;
+	h->deleted++;
+	if (h->deleted >= MINDELETED && 4 * h->deleted > h->total)
+		ohash_resize(h);
+	return result;
+}
+
+void *
+ohash_find(struct ohash *h, unsigned int i)
+{
+	if (h->t[i].p == DELETED)
+		return NULL;
+	else
+		return __DECONST(void *, h->t[i].p);
+}
+
+void *
+ohash_insert(struct ohash *h, unsigned int i, void *p)
+{
+#ifdef STATS_HASH
+	STAT_HASH_ENTRIES++;
+#endif
+	if (h->t[i].p == DELETED) {
+		h->deleted--;
+		h->t[i].p = p;
+	} else {
+		h->t[i].p = p;
+	/* Arbitrary resize boundary.  Tweak if not efficient enough.  */
+		if (++h->total * 4 > h->size * 3)
+			ohash_resize(h);
+	}
+    	return p;
+}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.bin/m4/lib/ohash_entries.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/usr.bin/m4/lib/ohash_entries.c	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,28 @@
+/* $OpenBSD: ohash_entries.c,v 1.2 2004/06/22 20:00:16 espie Exp $ */
+/* ex:ts=8 sw=4: 
+ */
+
+/* Copyright (c) 1999, 2004 Marc Espie <espie at openbsd.org>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, 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.
+ */
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD: head/usr.bin/m4/lib/ohash_entries.c 228063 2011-11-28 13:32:39Z bapt $");
+
+#include "ohash_int.h"
+
+unsigned int
+ohash_entries(struct ohash *h)
+{
+	return h->total - h->deleted;
+}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.bin/m4/lib/ohash_enum.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/usr.bin/m4/lib/ohash_enum.c	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,38 @@
+/* $OpenBSD: ohash_enum.c,v 1.3 2004/06/22 20:00:16 espie Exp $ */
+/* ex:ts=8 sw=4: 
+ */
+
+/* Copyright (c) 1999, 2004 Marc Espie <espie at openbsd.org>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, 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.
+ */
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD: head/usr.bin/m4/lib/ohash_enum.c 228063 2011-11-28 13:32:39Z bapt $");
+
+#include "ohash_int.h"
+
+void *
+ohash_first(struct ohash *h, unsigned int *pos)
+{
+	*pos = 0;
+	return ohash_next(h, pos);
+}
+	
+void *
+ohash_next(struct ohash *h, unsigned int *pos)
+{
+	for (; *pos < h->size; (*pos)++) 
+		if (h->t[*pos].p != DELETED && h->t[*pos].p != NULL) 
+			return __DECONST(void *, h->t[(*pos)++].p);
+	return NULL;
+}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.bin/m4/lib/ohash_init.3
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/usr.bin/m4/lib/ohash_init.3	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,231 @@
+.\"	$OpenBSD: ohash_init.3,v 1.14 2007/05/31 19:19:30 jmc Exp $
+.\" Copyright (c) 1999 Marc Espie <espie at openbsd.org>
+.\"
+.\" Permission to use, copy, modify, and distribute this software for any
+.\" purpose with or without fee is hereby granted, provided that the above
+.\" copyright notice and this permission notice appear in all copies.
+.\"
+.\" THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+.\" WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+.\" MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+.\" ANY SPECIAL, DIRECT, 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.
+.\"
+.\" $FreeBSD: head/usr.bin/m4/lib/ohash_init.3 228063 2011-11-28 13:32:39Z bapt $
+.\"
+.Dd $Mdocdate: May 31 2007 $
+.Dt OPEN_HASH 3
+.Os
+.Sh NAME
+.Nm ohash_init ,
+.Nm ohash_delete ,
+.Nm ohash_lookup_interval ,
+.Nm ohash_lookup_memory ,
+.Nm ohash_find ,
+.Nm ohash_remove ,
+.Nm ohash_insert ,
+.Nm ohash_first ,
+.Nm ohash_next ,
+.Nm ohash_entries
+.Nd light-weight open hashing
+.Sh SYNOPSIS
+.Fd #include <stdint.h>
+.Fd #include <stddef.h>
+.Fd #include <ohash.h>
+.Ft void
+.Fn ohash_init "struct ohash *h" "unsigned int size" "struct ohash_info *info"
+.Ft void
+.Fn ohash_delete "struct ohash *h"
+.Ft "unsigned int"
+.Fn ohash_lookup_interval "struct ohash *h" "const char *start" "const char *end" "uint32_t hv"
+.Ft "unsigned int"
+.Fn ohash_lookup_memory "struct ohash *h" "const char *k" "size_t s" "uint32_t hv"
+.Ft void *
+.Fn ohash_find "struct ohash *h" "unsigned int i"
+.Ft void *
+.Fn ohash_remove "struct ohash *h" "unsigned int i"
+.Ft void *
+.Fn ohash_insert "struct ohash *h" "unsigned int i" "void *p"
+.Ft void *
+.Fn ohash_first "struct ohash *h" "unsigned int *i"
+.Ft void *
+.Fn ohash_next "struct ohash *h" "unsigned int *i"
+.Ft "unsigned int"
+.Fn ohash_entries "struct ohash *h"
+.Sh DESCRIPTION
+These functions have been designed as a fast, extensible alternative to
+the usual hash table functions.
+They provide storage and retrieval of records indexed by keys,
+where a key is a contiguous sequence of bytes at a fixed position in
+each record.
+Keys can either be NUL-terminated strings or fixed-size memory areas.
+All functions take a pointer to an ohash structure as the
+.Fa h
+function argument.
+Storage for this structure should be provided by user code.
+.Pp
+.Fn ohash_init
+initializes the table to store roughly 2 to the power
+.Fa size
+elements.
+.Fa info
+holds the position of the key in each record, and two pointers to
+.Xr calloc 3
+and
+.Xr free 3 Ns -like
+functions, to use for managing the table internal storage.
+.Pp
+.Fn ohash_delete
+frees storage internal to
+.Fa h .
+Elements themselves should be freed by the user first, using for instance
+.Fn ohash_first
+and
+.Fn ohash_next .
+.Pp
+.Fn ohash_lookup_interval
+and
+.Fn ohash_lookup_memory
+are the basic look-up element functions.
+The hashing function result is provided by the user as
+.Fa hv .
+These return a
+.Qq slot
+in the ohash table
+.Fa h ,
+to be used with
+.Fn ohash_find ,
+.Fn ohash_insert ,
+or
+.Fn ohash_remove .
+This slot is only valid up to the next call to
+.Fn ohash_insert
+or
+.Fn ohash_remove .
+.Pp
+.Fn ohash_lookup_interval
+handles string-like keys.
+.Fn ohash_lookup_interval
+assumes the key is the interval between
+.Fa start
+and
+.Fa end ,
+exclusive,
+though the actual elements stored in the table should only contain
+NUL-terminated keys.
+.Pp
+.Fn ohash_lookup_memory
+assumes the key is the memory area starting at
+.Fa k
+of size
+.Fa s .
+All bytes are significant in key comparison.
+.Pp
+.Fn ohash_find
+retrieves an element from a slot
+.Fa i
+returned by the
+.Fn ohash_lookup*
+functions.
+It returns
+.Dv NULL
+if the slot is empty.
+.Pp
+.Fn ohash_insert
+inserts a new element
+.Fa p
+at slot
+.Fa i .
+Slot
+.Fa i
+must be empty and element
+.Fa p
+must have a key corresponding to the
+.Fn ohash_lookup*
+call.
+.Pp
+.Fn ohash_remove
+removes the element at slot
+.Fa i .
+It returns the removed element, for user code to dispose of, or
+.Dv NULL
+if the slot was empty.
+.Pp
+.Fn ohash_first
+and
+.Fn ohash_next
+can be used to access all elements in an ohash table, like this:
+.Bd -literal -offset indent
+for (n = ohash_first(h, &i); n != NULL; n = ohash_next(h, &i))
+	do_something_with(n);
+.Ed
+.Pp
+.Fa i
+points to an auxiliary unsigned integer used to record the current position
+in the ohash table.
+Those functions are safe to use even while entries are added to/removed
+from the table, but in such a case they don't guarantee that new entries
+will be returned.
+As a special case, they can safely be used to free elements in the table.
+.Pp
+.Fn ohash_entries
+returns the number of elements in the hash table.
+.Sh STORAGE HANDLING
+Only
+.Fn ohash_init ,
+.Fn ohash_insert ,
+.Fn ohash_remove
+and
+.Fn ohash_delete
+may call the user-supplied memory functions.
+It is the responsibility of the user memory allocation code to verify
+that those calls did not fail.
+.Pp
+If memory allocation fails,
+.Fn ohash_init
+returns a useless hash table.
+.Fn ohash_insert
+and
+.Fn ohash_remove
+still perform the requested operation, but the returned table should be
+considered read-only.
+It can still be accessed by
+.Fn ohash_lookup* ,
+.Fn ohash_find ,
+.Fn ohash_first
+and
+.Fn ohash_next
+to dump relevant information to disk before aborting.
+.Sh THREAD SAFETY
+The open hashing functions are not thread-safe by design.
+In particular, in a threaded environment, there is no guarantee that a
+.Qq slot
+will not move between a
+.Fn ohash_lookup*
+and a
+.Fn ohash_find ,
+.Fn ohash_insert
+or
+.Fn ohash_remove
+call.
+.Pp
+Multi-threaded applications should explicitly protect ohash table access.
+.Sh SEE ALSO
+.Xr ohash_interval 3
+.Rs
+.%A Donald E. Knuth
+.%B The Art of Computer Programming
+.%V Vol. 3
+.%P pp 506-550
+.%D 1973
+.Re
+.Sh STANDARDS
+Those functions are completely non-standard and should be avoided in
+portable programs.
+.Sh HISTORY
+Those functions were designed and written for
+.Ox
+.Xr make 1
+by Marc Espie in 1999.
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.bin/m4/lib/ohash_init.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/usr.bin/m4/lib/ohash_init.c	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,43 @@
+/* $OpenBSD: ohash_init.c,v 1.2 2004/06/22 20:00:16 espie Exp $ */
+/* ex:ts=8 sw=4: 
+ */
+
+/* Copyright (c) 1999, 2004 Marc Espie <espie at openbsd.org>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, 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.
+ */
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD: head/usr.bin/m4/lib/ohash_init.c 228063 2011-11-28 13:32:39Z bapt $");
+
+#include "ohash_int.h"
+
+void 
+ohash_init(struct ohash *h, unsigned int size, struct ohash_info *info)
+{
+	h->size = 1UL << size;
+	if (h->size < MINSIZE)
+		h->size = MINSIZE;
+#ifdef STATS_HASH
+	STAT_HASH_CREATION++;
+	STAT_HASH_SIZE += h->size;
+#endif
+	/* Copy info so that caller may free it.  */
+	h->info.key_offset = info->key_offset;
+	h->info.halloc = info->halloc;
+	h->info.hfree = info->hfree;
+	h->info.alloc = info->alloc;
+	h->info.data = info->data;
+	h->t = (h->info.halloc)(sizeof(struct _ohash_record) * h->size,
+	    h->info.data);
+	h->total = h->deleted = 0;
+}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.bin/m4/lib/ohash_int.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/usr.bin/m4/lib/ohash_int.h	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,25 @@
+/*	$OpenBSD: ohash_int.h,v 1.3 2006/01/16 15:52:25 espie Exp $	*/
+/* $FreeBSD: head/usr.bin/m4/lib/ohash_int.h 228063 2011-11-28 13:32:39Z bapt $ */
+
+#if HAVE_NBTOOL_CONFIG_H
+#include "nbtool_config.h"
+#endif
+
+#include <sys/types.h>
+#include <stddef.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+#include "ohash.h"
+
+struct _ohash_record {
+	u_int32_t	hv;
+	const char 	*p;
+};
+
+#define DELETED		((const char *)h)
+#define NONE		(h->size)
+
+/* Don't bother changing the hash table if the change is small enough.  */
+#define MINSIZE		(1UL << 4)
+#define MINDELETED	4
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.bin/m4/lib/ohash_interval.3
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/usr.bin/m4/lib/ohash_interval.3	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,92 @@
+.\"	$OpenBSD: ohash_interval.3,v 1.11 2007/05/31 19:19:30 jmc Exp $
+.\" Copyright (c) 2001 Marc Espie <espie at openbsd.org>
+.\"
+.\" Permission to use, copy, modify, and distribute this software for any
+.\" purpose with or without fee is hereby granted, provided that the above
+.\" copyright notice and this permission notice appear in all copies.
+.\"
+.\" THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+.\" WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+.\" MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+.\" ANY SPECIAL, DIRECT, 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.
+.\"
+.\" $FreeBSD: head/usr.bin/m4/lib/ohash_interval.3 228063 2011-11-28 13:32:39Z bapt $
+.\"
+.Dd $Mdocdate: May 31 2007 $
+.Dt OPEN_HASH_HELPER 3
+.Os
+.Sh NAME
+.Nm ohash_interval ,
+.Nm ohash_create_entry ,
+.Nm ohash_qlookup ,
+.Nm ohash_qlookupi
+.Nd helper functions for open hashing
+.Sh SYNOPSIS
+.Fd #include <stdint.h>
+.Fd #include <stddef.h>
+.Fd #include <ohash.h>
+.Ft u_int32_t
+.Fn ohash_interval "const char *start" "const char **pend"
+.Ft "void *"
+.Fn ohash_create_entry "struct ohash_info *info" "const char *start" "const char **pend"
+.Ft "unsigned int"
+.Fn ohash_qlookupi "struct ohash *h" "const char *start" "const char **pend"
+.Ft "unsigned int"
+.Fn ohash_qlookup "struct ohash *h" "const char *start"
+.Sh DESCRIPTION
+These functions are commonly used to simplify open hashing usage, and use
+similar conventions.
+They operate indifferently on NUL-terminated strings
+.Po
+by setting
+.Fa *pend
+=
+.Dv NULL
+.Pc
+or memory ranges
+.Po
+delimited by
+.Fa start
+and
+.Fa *pend
+.Pc .
+For NUL-terminated strings, as a side effect, those functions
+set
+.Fa *pend
+to the terminating NUL byte.
+.Pp
+.Fn ohash_interval
+is a simple hashing function that yields good results on common data sets.
+.Pp
+.Fn ohash_create_entry
+can be used to create a new record with a given key.
+In that case,
+the alloc field of
+.Fa info
+should point to a
+.Xr malloc 3 Ns -like
+function to allocate the storage.
+.Pp
+.Fn ohash_qlookupi
+is a wrapper function that simply calls
+.Fn ohash_interval
+and
+.Fn ohash_lookup_interval .
+.Pp
+.Fn ohash_qlookup
+is a variation on
+.Fn ohash_qlookupi
+designed for NUL-terminated strings.
+.Sh SEE ALSO
+.Xr ohash_init 3
+.Sh STANDARDS
+Those functions are completely non-standard and should be avoided in
+portable programs.
+.Sh HISTORY
+Those functions were designed and written for
+.Ox
+.Xr make 1
+by Marc Espie in 1999.
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.bin/m4/lib/ohash_interval.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/usr.bin/m4/lib/ohash_interval.c	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,38 @@
+/* $OpenBSD: ohash_interval.c,v 1.3 2006/01/16 15:52:25 espie Exp $ */
+/* ex:ts=8 sw=4: 
+ */
+
+/* Copyright (c) 1999, 2004 Marc Espie <espie at openbsd.org>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, 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.
+ */
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD: head/usr.bin/m4/lib/ohash_interval.c 228063 2011-11-28 13:32:39Z bapt $");
+
+#include "ohash_int.h"
+
+uint32_t
+ohash_interval(const char *s, const char **e)
+{
+	uint32_t k;
+
+	if (!*e)
+		*e = s + strlen(s);
+	if (s == *e)
+		k = 0;
+	else
+		k = *s++;
+	while (s != *e)
+		k =  ((k << 2) | (k >> 30)) ^ *s++;
+	return k;
+}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.bin/m4/lib/ohash_lookup_interval.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/usr.bin/m4/lib/ohash_lookup_interval.c	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,70 @@
+/* $OpenBSD: ohash_lookup_interval.c,v 1.3 2006/01/16 15:52:25 espie Exp $ */
+/* ex:ts=8 sw=4: 
+ */
+
+/* Copyright (c) 1999, 2004 Marc Espie <espie at openbsd.org>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, 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.
+ */
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD: head/usr.bin/m4/lib/ohash_lookup_interval.c 228063 2011-11-28 13:32:39Z bapt $");
+
+#include "ohash_int.h"
+	
+unsigned int
+ohash_lookup_interval(struct ohash *h, const char *start, const char *end, 
+    uint32_t hv)
+{
+	unsigned int 	i, incr;
+	unsigned int	empty;
+	
+#ifdef STATS_HASH
+	STAT_HASH_LOOKUP++;
+#endif
+	empty = NONE;
+	i = hv % h->size;
+	incr = ((hv % (h->size-2)) & ~1) + 1;
+	while (h->t[i].p != NULL) {
+#ifdef STATS_HASH
+		STAT_HASH_LENGTH++;
+#endif
+		if (h->t[i].p == DELETED) {
+			if (empty == NONE)
+				empty = i;
+		} else if (h->t[i].hv == hv && 
+		    strncmp(h->t[i].p+h->info.key_offset, start, 
+		    	end - start) == 0 &&
+		    (h->t[i].p+h->info.key_offset)[end-start] == '\0') {
+		    	if (empty != NONE) {
+				h->t[empty].hv = hv;
+				h->t[empty].p = h->t[i].p;
+				h->t[i].p = DELETED;
+				return empty;
+			} else {
+#ifdef STATS_HASH
+				STAT_HASH_POSITIVE++;
+#endif
+				return i;
+			}
+		}
+		i += incr;
+		if (i >= h->size) 
+			i -= h->size;
+	}
+
+	/* Found an empty position.  */
+	if (empty != NONE) 
+		i = empty;
+	h->t[i].hv = hv;
+	return i;
+}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.bin/m4/lib/ohash_lookup_memory.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/usr.bin/m4/lib/ohash_lookup_memory.c	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,66 @@
+/* $OpenBSD: ohash_lookup_memory.c,v 1.3 2006/01/16 15:52:25 espie Exp $ */
+/* ex:ts=8 sw=4: 
+ */
+
+/* Copyright (c) 1999, 2004 Marc Espie <espie at openbsd.org>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, 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.
+ */
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD: head/usr.bin/m4/lib/ohash_lookup_memory.c 228063 2011-11-28 13:32:39Z bapt $");
+
+#include "ohash_int.h"
+
+unsigned int
+ohash_lookup_memory(struct ohash *h, const char *k, size_t size, uint32_t hv)
+{
+	unsigned int	i, incr;
+	unsigned int	empty;
+	
+#ifdef STATS_HASH
+	STAT_HASH_LOOKUP++;
+#endif
+	empty = NONE;
+	i = hv % h->size;
+	incr = ((hv % (h->size-2)) & ~1) + 1;
+	while (h->t[i].p != NULL) {
+#ifdef STATS_HASH
+		STAT_HASH_LENGTH++;
+#endif
+		if (h->t[i].p == DELETED) {
+			if (empty == NONE)
+				empty = i;
+		} else if (h->t[i].hv == hv && 
+		    memcmp(h->t[i].p+h->info.key_offset, k, size) == 0) {
+		    	if (empty != NONE) {
+				h->t[empty].hv = hv;
+				h->t[empty].p = h->t[i].p;
+				h->t[i].p = DELETED;
+				return empty;
+			} else {
+#ifdef STATS_HASH
+				STAT_HASH_POSITIVE++;
+#endif
+			}	return i;
+		}
+		i += incr;
+		if (i >= h->size) 
+			i -= h->size;
+	}
+
+	/* Found an empty position.  */
+	if (empty != NONE) 
+		i = empty;
+	h->t[i].hv = hv;
+	return i;
+}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.bin/m4/lib/ohash_qlookup.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/usr.bin/m4/lib/ohash_qlookup.c	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,29 @@
+/* $OpenBSD: ohash_qlookup.c,v 1.2 2004/06/22 20:00:17 espie Exp $ */
+/* ex:ts=8 sw=4: 
+ */
+
+/* Copyright (c) 1999, 2004 Marc Espie <espie at openbsd.org>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, 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.
+ */
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD: head/usr.bin/m4/lib/ohash_qlookup.c 228063 2011-11-28 13:32:39Z bapt $");
+
+#include "ohash_int.h"
+
+unsigned int
+ohash_qlookup(struct ohash *h, const char *s)
+{
+	const char *e = NULL;
+	return ohash_qlookupi(h, s, &e);
+}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.bin/m4/lib/ohash_qlookupi.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/usr.bin/m4/lib/ohash_qlookupi.c	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,31 @@
+/* $OpenBSD: ohash_qlookupi.c,v 1.2 2004/06/22 20:00:17 espie Exp $ */
+/* ex:ts=8 sw=4: 
+ */
+
+/* Copyright (c) 1999, 2004 Marc Espie <espie at openbsd.org>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, 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.
+ */
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD: head/usr.bin/m4/lib/ohash_qlookupi.c 228063 2011-11-28 13:32:39Z bapt $");
+
+#include "ohash_int.h"
+
+unsigned int
+ohash_qlookupi(struct ohash *h, const char *s, const char **e)
+{
+	u_int32_t hv;
+
+	hv = ohash_interval(s, e);
+	return ohash_lookup_interval(h, s, *e, hv);
+}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.bin/m4/look.c
--- a/head/usr.bin/m4/look.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/usr.bin/m4/look.c	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-/*	$OpenBSD: look.c,v 1.10 2002/04/26 16:15:16 espie Exp $	*/
+/*	$OpenBSD: look.c,v 1.22 2010/09/07 19:58:09 marco Exp $	*/
 
 /*
  * Copyright (c) 1989, 1993
@@ -15,7 +15,7 @@
  * 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.
- * 4. Neither the name of the University nor the names of its contributors
+ * 3. Neither the name of the University nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
  *
@@ -31,15 +31,8 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  */
-
-#if 0
-#ifndef lint
-static char sccsid[] = "@(#)look.c	8.1 (Berkeley) 6/6/93";
-#endif /* not lint */
-#endif
-
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/usr.bin/m4/look.c 228063 2011-11-28 13:32:39Z bapt $");
 
 /*
  * look.c
@@ -50,21 +43,52 @@
 #include <sys/types.h>
 #include <stdio.h>
 #include <stdlib.h>
+#include <stdint.h>
 #include <stddef.h>
 #include <string.h>
+#include <ohash.h>
 #include "mdef.h"
 #include "stdd.h"
 #include "extern.h"
 
-static void freent(ndptr);
+static void *hash_alloc(size_t, void *);
+static void hash_free(void *, size_t, void *);
+static void *element_alloc(size_t, void *);
+static void setup_definition(struct macro_definition *, const char *,
+    const char *);
 
-unsigned int
-hash(const char *name)
+static struct ohash_info macro_info = {
+	offsetof(struct ndblock, name),
+	NULL, hash_alloc, hash_free, element_alloc };
+
+struct ohash macros;
+
+/* Support routines for hash tables.  */
+void *
+hash_alloc(size_t s, __unused void *u)
 {
-	unsigned int h = 0;
-	while (*name)
-		h = (h << 5) + h + *name++;
-	return (h);
+	void *storage = xalloc(s, "hash alloc");
+	if (storage)
+		memset(storage, 0, s);
+	return storage;
+}
+
+void
+hash_free(void *p, __unused size_t s, __unused void *u)
+{
+	free(p);
+}
+
+void *
+element_alloc(size_t s, __unused void *u)
+{
+	return xalloc(s, "element alloc");
+}
+
+void
+init_macros(void)
+{
+	ohash_init(&macros, 10, &macro_info);
 }
 
 /*
@@ -73,74 +97,181 @@
 ndptr
 lookup(const char *name)
 {
-	ndptr p;
-	unsigned int h;
-
-	h = hash(name);
-	for (p = hashtab[h % HASHSIZE]; p != nil; p = p->nxtptr)
-		if (h == p->hv && STREQ(name, p->name))
-			break;
-	return (p);
+	return ohash_find(&macros, ohash_qlookup(&macros, name));
 }
 
-/*
- * hash and create an entry in the hash table.
- * The new entry is added in front of a hash bucket.
- */
-ndptr
-addent(const char *name)
+struct macro_definition *
+lookup_macro_definition(const char *name)
 {
-	unsigned int h;
 	ndptr p;
 
-	h = hash(name);
-	p = (ndptr) xalloc(sizeof(struct ndblock));
-	p->nxtptr = hashtab[h % HASHSIZE];
-	hashtab[h % HASHSIZE] = p;
-	p->name = xstrdup(name);
-	p->hv = h;
-	return p;
+	p = ohash_find(&macros, ohash_qlookup(&macros, name));
+	if (p)
+		return p->d;
+	else
+		return NULL;
 }
 
 static void
-freent(ndptr p)
+setup_definition(struct macro_definition *d, const char *defn, const char *name)
 {
-	free((char *) p->name);
-	if (p->defn != null)
-		free((char *) p->defn);
-	free((char *) p);
+	ndptr p;
+
+	if (strncmp(defn, BUILTIN_MARKER, sizeof(BUILTIN_MARKER)-1) == 0 &&
+	    (p = macro_getbuiltin(defn+sizeof(BUILTIN_MARKER)-1)) != NULL) {
+		d->type = macro_builtin_type(p);
+		d->defn = xstrdup(defn+sizeof(BUILTIN_MARKER)-1);
+	} else {
+		if (!*defn)
+			d->defn = __DECONST(char *, null);
+		else
+			d->defn = xstrdup(defn);
+		d->type = MACRTYPE;
+	}
+	if (STREQ(name, defn))
+		d->type |= RECDEF;
 }
 
-/*
- * remove an entry from the hashtable
- */
+static ndptr
+create_entry(const char *name)
+{
+	const char *end = NULL;
+	unsigned int i;
+	ndptr n;
+
+	i = ohash_qlookupi(&macros, name, &end);
+	n = ohash_find(&macros, i);
+	if (n == NULL) {
+		n = ohash_create_entry(&macro_info, name, &end);
+		ohash_insert(&macros, i, n);
+		n->trace_flags = FLAG_NO_TRACE;
+		n->builtin_type = MACRTYPE;
+		n->d = NULL;
+	}
+	return n;
+}
+
 void
-remhash(const char *name, int all)
+macro_define(const char *name, const char *defn)
 {
-	unsigned int h;
-	ndptr xp, tp, mp;
+	ndptr n = create_entry(name);
+	if (n->d != NULL) {
+		if (n->d->defn != null)
+			free(n->d->defn);
+	} else {
+		n->d = xalloc(sizeof(struct macro_definition), NULL);
+		n->d->next = NULL;
+	}
+	setup_definition(n->d, defn, name);
+}
 
-	h = hash(name);
-	mp = hashtab[h % HASHSIZE];
-	tp = nil;
-	while (mp != nil) {
-		if (mp->hv == h && STREQ(mp->name, name)) {
-			mp = mp->nxtptr;
-			if (tp == nil) {
-				freent(hashtab[h % HASHSIZE]);
-				hashtab[h % HASHSIZE] = mp;
-			}
-			else {
-				xp = tp->nxtptr;
-				tp->nxtptr = mp;
-				freent(xp);
-			}
-			if (!all)
-				break;
+void
+macro_pushdef(const char *name, const char *defn)
+{
+	ndptr n;
+	struct macro_definition *d;
+
+	n = create_entry(name);
+	d = xalloc(sizeof(struct macro_definition), NULL);
+	d->next = n->d;
+	n->d = d;
+	setup_definition(n->d, defn, name);
+}
+
+void
+macro_undefine(const char *name)
+{
+	ndptr n = lookup(name);
+	if (n != NULL) {
+		struct macro_definition *r, *r2;
+
+		for (r = n->d; r != NULL; r = r2) {
+			r2 = r->next;
+			if (r->defn != null)
+				free(r->defn);
+			free(r);
 		}
-		else {
-			tp = mp;
-			mp = mp->nxtptr;
+		n->d = NULL;
+	}
+}
+
+void
+macro_popdef(const char *name)
+{
+	ndptr n = lookup(name);
+
+	if (n != NULL) {
+		struct macro_definition *r = n->d;
+		if (r != NULL) {
+			n->d = r->next;
+			if (r->defn != null)
+				free(r->defn);
+			free(r);
 		}
 	}
 }
+
+void
+macro_for_all(void (*f)(const char *, struct macro_definition *))
+{
+	ndptr n;
+	unsigned int i;
+
+	for (n = ohash_first(&macros, &i); n != NULL;
+	    n = ohash_next(&macros, &i))
+		if (n->d != NULL)
+			f(n->name, n->d);
+}
+
+void
+setup_builtin(const char *name, unsigned int type)
+{
+	ndptr n;
+	char *name2;
+
+	if (prefix_builtins) {
+		name2 = xalloc(strlen(name)+3+1, NULL);
+		memcpy(name2, "m4_", 3);
+		memcpy(name2 + 3, name, strlen(name)+1);
+	} else
+		name2 = xstrdup(name);
+
+	n = create_entry(name2);
+	n->builtin_type = type;
+	n->d = xalloc(sizeof(struct macro_definition), NULL);
+	n->d->defn = name2;
+	n->d->type = type;
+	n->d->next = NULL;
+}
+
+void
+mark_traced(const char *name, int on)
+{
+	ndptr p;
+	unsigned int i;
+
+	if (name == NULL) {
+		if (on)
+			trace_flags |= TRACE_ALL;
+		else
+			trace_flags &= ~TRACE_ALL;
+		for (p = ohash_first(&macros, &i); p != NULL;
+		    p = ohash_next(&macros, &i))
+			p->trace_flags = FLAG_NO_TRACE;
+	} else {
+		p = create_entry(name);
+		p->trace_flags = on;
+	}
+}
+
+ndptr
+macro_getbuiltin(const char *name)
+{
+	ndptr p;
+
+	p = lookup(name);
+	if (p == NULL || p->builtin_type == MACRTYPE)
+		return NULL;
+	else
+		return p;
+}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.bin/m4/m4.1
--- a/head/usr.bin/m4/m4.1	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/usr.bin/m4/m4.1	Tue Dec 06 20:26:16 2011 +0200
@@ -1,201 +1,266 @@
-.\"	@(#) $OpenBSD: m4.1,v 1.24 2002/04/18 18:57:23 espie Exp $
-.\" $FreeBSD$
+.\"	$NetBSD: m4.1,v 1.22 2010/05/14 17:14:28 joerg Exp $
+.\"	@(#) $OpenBSD: m4.1,v 1.56 2009/10/14 17:19:47 sthen Exp $
 .\"
-.Dd July 3, 2004
+.\" Copyright (c) 1989, 1993
+.\"	The Regents of the University of California.  All rights reserved.
+.\"
+.\" This code is derived from software contributed to Berkeley by
+.\" Ozan Yigit at York University.
+.\"
+.\" 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 University nor the names of its contributors
+.\"    may be used to endorse or promote products derived from this software
+.\"    without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $FreeBSD: head/usr.bin/m4/m4.1 228063 2011-11-28 13:32:39Z bapt $
+.\"
+.Dd October 14, 2009
 .Dt M4 1
 .Os
 .Sh NAME
 .Nm m4
 .Nd macro language processor
 .Sh SYNOPSIS
-.Nm
+.Nm m4
+.Op Fl gPs
+.Oo
+.Sm off
+.Fl D Ar name Op No = Ar value
+.Sm on
+.Oc
 .Op Fl d Ar flags
-.Op Fl t Ar name
-.Op Fl gs
-.Op Fl D Ar name Ns Op = Ns Ar value
-.Op Fl U Ar name
 .Op Fl I Ar dirname
+.Op Fl o Ar filename
+.Bk -words
+.Op Fl t Ar macro
+.Op Fl U Ns Ar name
 .Op Ar
+.Ek
 .Sh DESCRIPTION
 The
-.Nm
+.Nm m4
 utility is a macro processor that can be used as a front end to any
 language (e.g., C, ratfor, fortran, lex, and yacc).
-The
-.Nm
-utility reads from the standard input and writes
-the processed text to the standard output.
+If no input files are given,
+.Nm m4
+reads from the standard input,
+otherwise files specified on the command line are
+processed in the given order.
+Input files can be regular files, files in the m4 include paths, or a
+single dash
+.Pq Sq - ,
+denoting standard input.
+.Nm m4
+writes
+the processed text to the standard output, unless told otherwise.
 .Pp
-Macro calls have the form
-.Ic name Ns Pq Ar argument1 Ns Op , Ar argument2 , ... , argumentN .
+Macro calls have the form name(argument1[, argument2, ..., argumentN]).
 .Pp
 There cannot be any space following the macro name and the open
 parenthesis
-.Pq Ql \&( .
+.Sq \&( .
 If the macro name is not followed by an open
 parenthesis it is processed with no arguments.
 .Pp
 Macro names consist of a leading alphabetic or underscore
 possibly followed by alphanumeric or underscore characters, e.g.,
 valid macro names match the pattern
-.Dq Li [a-zA-Z_][a-zA-Z0-9_]* .
+.Dq [a-zA-Z_][a-zA-Z0-9_]* .
 .Pp
 In arguments to macros, leading unquoted space, tab, and newline
-.Pq Ql \en
+.Pq Sq \en
 characters are ignored.
-To quote strings, use left and right single
-quotes (e.g.,
-.Sq "\ this is a string with a leading space" ) .
+To quote strings, use left and right single quotes
+.Po e.g.,\ \&
+.Sq "\ this is a string with a leading space"
+.Pc .
 You can change the quote characters with the
 .Ic changequote
 built-in macro.
 .Pp
-Most built-ins do not make any sense without arguments, and hence are not
+Most built-ins don't make any sense without arguments, and hence are not
 recognized as special when not followed by an open parenthesis.
 .Pp
 The options are as follows:
-.Bl -tag -width indent
-.It Fl s
-Emit
-.Ic #line
-directives for
-.Xr cpp 1 .
-.It Fl D Ar name Ns Op = Ns Ar value
+.Bl -tag -width Ds
+.It Fl D Ns Ar name Ns Op Pf = Ns Ar value
 Define the symbol
 .Ar name
 to have some value (or
 .Dv NULL ) .
-.It Fl U Ar name
-Undefine the symbol
-.Ar name .
-.It Fl I Ar dirname
+.It Fl d Ar "flags"
+Set trace flags.
+.Ar flags
+may hold the following:
+.Bl -tag -width Ds
+.It Ar a
+print macro arguments.
+.It Ar c
+print macro expansion over several lines.
+.It Ar e
+print result of macro expansion.
+.It Ar f
+print filename location.
+.It Ar l
+print line number.
+.It Ar q
+quote arguments and expansion with the current quotes.
+.It Ar t
+start with all macros traced.
+.It Ar x
+number macro expansions.
+.It Ar V
+turn on all options.
+.El
+.Pp
+By default, trace is set to
+.Qq eq .
+.It Fl g
+Activate GNU-m4 compatibility mode.
+In this mode, translit handles simple character
+ranges (e.g., a-z), regular expressions mimic emacs behavior,
+multiple m4wrap calls are handled as a stack,
+the number of diversions is unlimited,
+empty names for macro definitions are allowed,
+and eval understands
+.Sq 0rbase:value
+numbers.
+.It Fl I Ar "dirname"
 Add directory
 .Ar dirname
 to the include path.
-.It Fl d Ar flags
-Set trace flags.
-The
-.Ar flags
-argument may hold the following:
-.Pp
-.Bl -tag -width indent -compact
-.It Cm a
-print macro arguments
-.It Cm c
-print macro expansion over several lines
-.It Cm e
-print result of macro expansion
-.It Cm f
-print filename location
-.It Cm l
-print line number
-.It Cm q
-quote arguments and expansion with the current quotes
-.It Cm t
-start with all macros traced
-.It Cm x
-number macro expansions
-.It Cm V
-turn on all options
-.El
-.Pp
-By default, trace is set to
-.Cm eq .
+.It Fl o Ar filename
+Send trace output to
+.Ar filename .
+.It Fl P
+Prefix all built-in macros with
+.Sq m4_ .
+For example, instead of writing
+.Ic define ,
+use
+.Ic m4_define .
+.It Fl s
+Output line synchronization directives, suitable for
+.Xr cpp 1 .
 .It Fl t Ar macro
 Turn tracing on for
 .Ar macro .
-.It Fl g
-Activate GNU-m4 compatibility mode.
-In this mode,
-.Ic changequote
-with two empty parameters deactivates quotes,
-.Ic translit
-handles simple character ranges (e.g.,
-.Li a-z ) ,
-regular expressions mimic
-.Xr emacs 1
-behavior,
-and the number of diversions is unlimited.
+.It Fl "U" Ns Ar "name"
+Undefine the symbol
+.Ar name .
 .El
 .Sh SYNTAX
-The
-.Nm
-utility provides the following built-in macros.
+.Nm m4
+provides the following built-in macros.
 They may be redefined, losing their original meaning.
 Return values are null unless otherwise stated.
-.Bl -tag -width ".Ic changequote"
-.It Ic builtin
-Calls a built-in by its name, overriding possible redefinitions.
-.It Ic changecom
-Changes the start and end comment sequences.
-The default is the pound sign
-.Pq Ql #
+.Bl -tag -width changequote
+.It Fn builtin name
+Calls a built-in by its
+.Fa name ,
+overriding possible redefinitions.
+.It Fn changecom startcomment endcomment
+Changes the start comment and end comment sequences.
+Comment sequences may be up to five characters long.
+The default values are the hash sign
 and the newline character.
-With no arguments, the comment sequence is reset to the default,
-in GNU
-.Nm
-mode, comments are turned off.
-The maximum length for a comment marker is five characters.
-.It Ic changequote
-Defines the quote symbols to be the first and second arguments.
-The symbols may be up to five characters long.
-If no arguments are
-given it restores the default open and close single quotes.
-.It Ic decr
-Decrements the argument by 1.
-The argument must be a valid numeric string.
-.It Ic define
-Define a new macro named by the first argument to have the
-value of the second argument.
+.Bd -literal -offset indent
+# This is a comment
+.Ed
+.Pp
+With no arguments, comments are turned off.
+With one single argument, the end comment sequence is set
+to the newline character.
+.It Fn changequote beginquote endquote
+Defines the open quote and close quote sequences.
+Quote sequences may be up to five characters long.
+The default values are the backquote character and the quote
+character.
+.Bd -literal -offset indent
+`Here is a quoted string'
+.Ed
+.Pp
+With no arguments, the default quotes are restored.
+With one single argument, the close quote sequence is set
+to the newline character.
+.It Fn decr arg
+Decrements the argument
+.Fa arg
+by 1.
+The argument
+.Fa arg
+must be a valid numeric string.
+.It Fn define name value
+Define a new macro named by the first argument
+.Fa name
+to have the
+value of the second argument
+.Fa value .
 Each occurrence of
-.Sq Li $ Ns Ar n
+.Sq $n
 (where
 .Ar n
 is 0 through 9) is replaced by the
 .Ar n Ns 'th
 argument.
-.Ql $0
+.Sq $0
 is the name of the calling macro.
 Undefined arguments are replaced by a null string.
-.Ql $#
+.Sq $#
 is replaced by the number of arguments;
-.Ql $*
+.Sq $*
 is replaced by all arguments comma separated;
-.Ql $@
+.Sq $@
 is the same as
-.Ql $*
+.Sq $*
 but all arguments are quoted against further expansion.
-.It Ic defn
+.It Fn defn name ...
 Returns the quoted definition for each argument.
 This can be used to rename
 macro definitions (even for built-in macros).
-.It Ic divert
+.It Fn divert num
 There are 10 output queues (numbered 0-9).
 At the end of processing
-.Nm
+.Nm m4
 concatenates all the queues in numerical order to produce the
 final output.
 Initially the output queue is 0.
-The
-.Ic divert
+The divert
 macro allows you to select a new output queue (an invalid argument
-passed to
-.Ic divert
-causes output to be discarded).
+passed to divert causes output to be discarded).
 .It Ic divnum
 Returns the current output queue number.
 .It Ic dnl
-Discards input characters up to and including the next newline.
-.It Ic dumpdef
+Discard input characters up to and including the next newline.
+.It Fn dumpdef name ...
 Prints the names and definitions for the named items, or for everything
 if no arguments are passed.
-.It Ic errprint
+.It Fn errprint msg
 Prints the first argument on the standard error output stream.
-.It Ic esyscmd
+.It Fn esyscmd cmd
 Passes its first argument to a shell and returns the shell's standard output.
 Note that the shell shares its standard input and standard error with
-.Nm .
-.It Ic eval
+.Nm m4 .
+.It Fn eval expr
 Computes the first argument as an arithmetic expression using 32-bit
 arithmetic.
 Operators are the standard C ternary, arithmetic, logical,
@@ -203,30 +268,46 @@
 You can specify
 octal, decimal, and hexadecimal numbers as in C.
 The second argument (if any)
-specifies the radix for the result, and the third argument (if any)
+specifies the radix for the result and the third argument (if any)
 specifies the minimum number of digits in the result.
-.It Ic expr
+.It Fn expr expr
 This is an alias for
 .Ic eval .
-.It Ic ifdef
+.It Fn format formatstring arg1 ...
+Returns
+.Fa formatstring
+with escape sequences substituted with
+.Fa arg1
+and following arguments, in a way similar to
+.Xr printf 3 .
+This built-in is only available in GNU-m4 compatibility mode, and the only
+parameters implemented are there for autoconf compatibility:
+left-padding flag, an optional field width, a maximum field width,
+*-specified field widths, and the %s and %c data type.
+.It Fn ifdef name yes no
 If the macro named by the first argument is defined then return the second
 argument, otherwise the third.
 If there is no third argument, the value is
 .Dv NULL .
 The word
-.Ic unix
+.Qq unix
 is predefined.
-.It Ic ifelse
-If the first argument matches the second argument then
-.Ic ifelse
+.It Fn ifelse a b yes ...
+If the first argument
+.Fa a
+matches the second argument
+.Fa b
+then
+.Fn ifelse
 returns
-the third argument.
-If the match fails, the three arguments are
+the third argument
+.Fa yes .
+If the match fails the three arguments are
 discarded and the next three arguments are used until there is
 zero or one arguments left, either this last argument or
 .Dv NULL
 is returned if no other matches were found.
-.It Ic include
+.It Fn include name
 Returns the contents of the file specified in the first argument.
 If the file is not found as is, look through the include path:
 first the directories specified with
@@ -234,114 +315,114 @@
 on the command line, then the environment variable
 .Ev M4PATH ,
 as a colon-separated list of directories.
-Aborts with an error message if the file cannot be included.
-.It Ic incr
+Include aborts with an error message if the file cannot be included.
+.It Fn incr arg
 Increments the argument by 1.
 The argument must be a valid numeric string.
-.It Ic index
+.It Fn index string substring
 Returns the index of the second argument in the first argument (e.g.,
-.Fn index "the quick brown fox jumped" fox
+.Ic index(the quick brown fox jumped, fox)
 returns 16).
 If the second
-argument is not found,
-.Ic index
-returns \-1.
-.It Ic indir
-Indirectly calls the macro whose name is passed as the first arguments,
-with the remaining arguments passed as first, etc.\& arguments.
-.It Ic len
+argument is not found index returns \-1.
+.It Fn indir macro arg1 ...
+Indirectly calls the macro whose name is passed as the first argument,
+with the remaining arguments passed as first, ... arguments.
+.It Fn len arg
 Returns the number of characters in the first argument.
 Extra arguments
 are ignored.
-.It Ic m4exit
+.It Fn m4exit code
 Immediately exits with the return value specified by the first argument,
 0 if none.
-.It Ic m4wrap
+.It Fn m4wrap todo
 Allows you to define what happens at the final
 .Dv EOF ,
 usually for cleanup purposes (e.g.,
-.Fn m4wrap cleanup(tempfile)
-causes the macro
-.Ic cleanup
-to be
+.Ic m4wrap("cleanup(tempfile)")
+causes the macro cleanup to be
 invoked after all other processing is done).
-.It Ic maketemp
-Translates the string
-.Dq Li XXXXX
-in the first argument with the current process
-ID leaving other characters alone.
+.Pp
+Multiple calls to
+.Fn m4wrap
+get inserted in sequence at the final
+.Dv EOF .
+.It Fn maketemp template
+Invokes
+.Xr mkstemp 3
+on the first argument, and returns the modified string.
 This can be used to create unique
 temporary file names.
-.It Ic paste
+.It Fn paste file
 Includes the contents of the file specified by the first argument without
 any macro processing.
 Aborts with an error message if the file cannot be
 included.
-.It Ic patsubst
+.It Fn patsubst string regexp replacement
 Substitutes a regular expression in a string with a replacement string.
 Usual substitution patterns apply: an ampersand
-.Pq Ql &
+.Pq Sq \&&
 is replaced by the string matching the regular expression.
 The string
-.Sq \e Ns Ar # ,
+.Sq \e# ,
 where
-.Ar #
+.Sq #
 is a digit, is replaced by the corresponding back-reference.
-.It Ic popdef
+.It Fn popdef arg ...
 Restores the
 .Ic pushdef Ns ed
 definition for each argument.
-.It Ic pushdef
+.It Fn pushdef macro def
 Takes the same arguments as
 .Ic define ,
 but it saves the definition on a
 stack for later retrieval by
-.Ic popdef .
-.It Ic regexp
+.Fn popdef .
+.It Fn regexp string regexp replacement
 Finds a regular expression in a string.
 If no further arguments are given,
 it returns the first match position or \-1 if no match.
 If a third argument
 is provided, it returns the replacement string, with sub-patterns replaced.
-.It Ic shift
+.It Fn shift arg1 ...
 Returns all but the first argument, the remaining arguments are
 quoted and pushed back with commas in between.
 The quoting
 nullifies the effect of the extra scan that will subsequently be
 performed.
-.It Ic sinclude
+.It Fn sinclude file
 Similar to
 .Ic include ,
 except it ignores any errors.
-.It Ic spaste
+.It Fn spaste file
 Similar to
-.Ic paste ,
+.Fn paste ,
 except it ignores any errors.
-.It Ic substr
+.It Fn substr string offset length
 Returns a substring of the first argument starting at the offset specified
 by the second argument and the length specified by the third argument.
 If no third argument is present it returns the rest of the string.
-.It Ic syscmd
+.It Fn syscmd cmd
 Passes the first argument to the shell.
 Nothing is returned.
 .It Ic sysval
 Returns the return value from the last
 .Ic syscmd .
-.It Ic traceon
+.It Fn traceon arg ...
 Enables tracing of macro expansions for the given arguments, or for all
 macros if no argument is given.
-.It Ic traceoff
+.It Fn traceoff arg ...
 Disables tracing of macro expansions for the given arguments, or for all
 macros if no argument is given.
-.It Ic translit
+.It Fn translit string mapfrom mapto
 Transliterate the characters in the first argument from the set
 given by the second argument to the set given by the third.
 You cannot use
 .Xr tr 1
 style abbreviations.
-.It Ic undefine
+.It Fn undefine name1 ...
 Removes the definition for the macros specified by its arguments.
-.It Ic undivert
+.It Fn undivert arg ...
 Flushes the named output queues (or all queues if no arguments).
 .It Ic unix
 A pre-defined macro for testing the OS platform.
@@ -350,37 +431,20 @@
 .It Ic __file__
 Returns the current file's name.
 .El
-.Sh EXIT STATUS
-.Ex -std
-.Pp
-The
-.Ic m4exit
-macro may be used to change the exit status from the input file.
-.Sh COMPATIBILITY
+.Sh STANDARDS
 The
 .Nm
-utility follows the
-.St -susv2 ,
-along with a few extensions taken from GNU-m4.
-Flags
-.Fl I , d ,
-and
-.Fl t
-are non-standard.
+utility is compliant with the
+.St -p1003.1-2008
+specification.
 .Pp
-The output format of tracing and of
-.Ic dumpdef
-are not specified in any standard,
-are likely to change and should not be relied upon.
-The current format of tracing is closely modeled on GNU-m4,
-to allow
-.Nm autoconf
-to work.
-.Pp
-For portability, one should not use the macros
+The flags
+.Op Fl dgIot
+and the macros
 .Ic builtin ,
 .Ic esyscmd ,
 .Ic expr ,
+.Ic format ,
 .Ic indir ,
 .Ic paste ,
 .Ic patsubst ,
@@ -389,33 +453,43 @@
 .Ic unix ,
 .Ic __line__ ,
 and
-.Ic __file__ .
+.Ic __file__
+are extensions to that specification.
+.Pp
+The output format of tracing and of
+.Ic dumpdef
+are not specified in any standard,
+are likely to change and should not be relied upon.
+The current format of tracing is closely modelled on
+.Nm gnu-m4 ,
+to allow
+.Nm autoconf
+to work.
+.Pp
+The built-ins
+.Ic pushdef
+and
+.Ic popdef
+handle macro definitions as a stack.
+However,
+.Ic define
+interacts with the stack in an undefined way.
+In this implementation,
+.Ic define
+replaces the top-most definition only.
+Other implementations may erase all definitions on the stack instead.
 .Pp
 All built-ins do expand without arguments in many other
-.Nm
-implementations.
+.Nm m4 .
 .Pp
 Many other
 .Nm
-implementations have dire size limitations with respect to buffer sizes.
-.Sh STANDARDS
-The
-.Nm
-utility
-conforms to
-.St -p1003.1-2001 .
-.Sh HISTORY
-An
-.Nm
-command appeared in PWB UNIX.
+have dire size limitations with respect to buffer sizes.
 .Sh AUTHORS
 .An -nosplit
 .An Ozan Yigit Aq oz at sis.yorku.ca
 and
 .An Richard A. O'Keefe Aq ok at goanna.cs.rmit.OZ.AU .
+.Pp
 GNU-m4 compatibility extensions by
 .An Marc Espie Aq espie at cvs.openbsd.org .
-.Sh BUGS
-The
-.Nm
-utility does not recognize multibyte characters.
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.bin/m4/main.c
--- a/head/usr.bin/m4/main.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/usr.bin/m4/main.c	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-/*	$OpenBSD: main.c,v 1.53 2002/04/26 16:15:16 espie Exp $	*/
+/*	$OpenBSD: main.c,v 1.80 2011/09/27 07:24:02 espie Exp $	*/
 /*	$NetBSD: main.c,v 1.12 1997/02/08 23:54:49 cgd Exp $	*/
 
 /*-
@@ -16,7 +16,7 @@
  * 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.
- * 4. Neither the name of the University nor the names of its contributors
+ * 3. Neither the name of the University nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
  *
@@ -33,73 +33,59 @@
  * SUCH DAMAGE.
  */
 
-#ifndef lint
-#if 0
-static char copyright[] =
-"@(#) Copyright (c) 1989, 1993\n\
-	The Regents of the University of California.  All rights reserved.\n";
-#endif
-#endif /* not lint */
-
-#ifndef lint
-#if 0
-static char sccsid[] = "@(#)main.c	8.1 (Berkeley) 6/6/93";
-#else
-#if 0
-static char rcsid[] = "$OpenBSD: main.c,v 1.53 2002/04/26 16:15:16 espie Exp $";
-#endif
-#endif
-#endif /* not lint */
-
-#include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/usr.bin/m4/main.c 227241 2011-11-06 18:49:48Z ed $");
-
 /*
  * main.c
  * Facility: m4 macro processor
  * by: oz
  */
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD: head/usr.bin/m4/main.c 228063 2011-11-28 13:32:39Z bapt $");
 
-#include <sys/types.h>
 #include <assert.h>
 #include <signal.h>
+#include <err.h>
 #include <errno.h>
 #include <unistd.h>
 #include <stdio.h>
 #include <ctype.h>
 #include <string.h>
 #include <stddef.h>
+#include <stdint.h>
 #include <stdlib.h>
-#include <err.h>
-#include <locale.h>
+#include <ohash.h>
 #include "mdef.h"
 #include "stdd.h"
 #include "extern.h"
 #include "pathnames.h"
 
-ndptr hashtab[HASHSIZE];	/* hash table for macros etc.  */
-stae *mstack;		 	/* stack of m4 machine         */
-char *sstack;		 	/* shadow stack, for string space extension */
+stae *mstack;			/* stack of m4 machine         */
+char *sstack;			/* shadow stack, for string space extension */
 static size_t STACKMAX;		/* current maximum size of stack */
-int sp; 			/* current m4  stack pointer   */
-int fp; 			/* m4 call frame pointer       */
+int sp;				/* current m4  stack pointer   */
+int fp;				/* m4 call frame pointer       */
 struct input_file infile[MAXINP];/* input file stack (0=stdin)  */
-char *inname[MAXINP];		/* names of these input files */
-int inlineno[MAXINP];		/* current number in each input file */
 FILE **outfile;			/* diversion array(0=bitbucket)*/
 int maxout;
 FILE *active;			/* active output file pointer  */
-int ilevel = 0; 		/* input file stack pointer    */
-int oindex = 0; 		/* diversion index..	       */
-char null[] = "";		/* as it says.. just a null..  */
-const char *m4wraps = "";       /* m4wrap string default..     */
+int ilevel = 0;			/* input file stack pointer    */
+int oindex = 0;			/* diversion index..	       */
+const char *null = "";                /* as it says.. just a null..  */
+char **m4wraps = NULL;		/* m4wraps array.	       */
+int maxwraps = 0;		/* size of m4wraps array       */
+int wrapindex = 0;		/* current offset in m4wraps   */
 char lquote[MAXCCHARS+1] = {LQUOTE};	/* left quote character  (`)   */
 char rquote[MAXCCHARS+1] = {RQUOTE};	/* right quote character (')   */
 char scommt[MAXCCHARS+1] = {SCOMMT};	/* start character for comment */
 char ecommt[MAXCCHARS+1] = {ECOMMT};	/* end character for comment   */
-int synccpp;			/* Line synchronisation for C preprocessor */
+int  synch_lines = 0;		/* line synchronisation for C preprocessor */
+int  prefix_builtins = 0;	/* -P option to prefix builtin keywords */
 
-static const struct keyblk keywrds[] = { /* m4 keywords to be installed */
+struct keyblk {
+        const char    *knam;          /* keyword name */
+        int     ktyp;           /* keyword type */
+};
+
+struct keyblk keywrds[] = {	/* m4 keywords to be installed */
 	{ "include",      INCLTYPE },
 	{ "sinclude",     SINCTYPE },
 	{ "define",       DEFITYPE },
@@ -120,7 +106,7 @@
 #ifdef EXTENDED
 	{ "paste",        PASTTYPE },
 	{ "spaste",       SPASTYPE },
-    	/* Newer extensions, needed to handle gnu-m4 scripts */
+	/* Newer extensions, needed to handle gnu-m4 scripts */
 	{ "indir",        INDIRTYPE},
 	{ "builtin",      BUILTINTYPE},
 	{ "patsubst",	  PATSTYPE},
@@ -138,6 +124,7 @@
 	{ "undivert",     UNDVTYPE | NOARGS },
 	{ "divnum",       DIVNTYPE | NOARGS },
 	{ "maketemp",     MKTMTYPE },
+	{ "mkstemp",      MKTMTYPE },
 	{ "errprint",     ERRPTYPE | NOARGS },
 	{ "m4wrap",       M4WRTYPE | NOARGS },
 	{ "m4exit",       EXITTYPE | NOARGS },
@@ -170,43 +157,41 @@
 static void initkwds(void);
 static ndptr inspect(int, char *);
 static int do_look_ahead(int, const char *);
+static void reallyoutputstr(const char *);
+static void reallyputchar(int);
 
 static void enlarge_stack(void);
 
+int main(int, char *[]);
+
 int
 main(int argc, char *argv[])
 {
 	int c;
 	int n;
-	int rval;
 	char *p;
 
-	setlocale(LC_ALL, "");
-
-	traceout = stderr;
-
 	if (signal(SIGINT, SIG_IGN) != SIG_IGN)
 		signal(SIGINT, onintr);
 
-	initkwds();
+	init_macros();
 	initspaces();
 	STACKMAX = INITSTACKMAX;
 
-	mstack = (stae *)xalloc(sizeof(stae) * STACKMAX);
-	sstack = (char *)xalloc(STACKMAX);
+	mstack = (stae *)xalloc(sizeof(stae) * STACKMAX, NULL);
+	sstack = (char *)xalloc(STACKMAX, NULL);
 
 	maxout = 0;
 	outfile = NULL;
 	resizedivs(MAXOUT);
 
-	while ((c = getopt(argc, argv, "gst:d:D:U:o:I:")) != -1)
+	while ((c = getopt(argc, argv, "gst:d:D:U:o:I:P")) != -1)
 		switch(c) {
+
 		case 'D':               /* define something..*/
 			for (p = optarg; *p; p++)
 				if (*p == '=')
 					break;
-			if (p == optarg)
-				errx(1, "null variable cannot be defined");
 			if (*p)
 				*p++ = EOS;
 			dodefine(optarg, p);
@@ -214,8 +199,11 @@
 		case 'I':
 			addtoincludepath(optarg);
 			break;
+		case 'P':
+			prefix_builtins = 1;
+			break;
 		case 'U':               /* undefine...       */
-			remhash(optarg, TOP);
+			macro_popdef(optarg);
 			break;
 		case 'g':
 			mimic_gnu = 1;
@@ -224,7 +212,7 @@
 			set_trace_flags(optarg);
 			break;
 		case 's':
-			synccpp = 1;
+			synch_lines = 1;
 			break;
 		case 't':
 			mark_traced(optarg, 1);
@@ -233,51 +221,55 @@
 			trace_file(optarg);
                         break;
 		case '?':
-		default:
 			usage();
 		}
 
         argc -= optind;
         argv += optind;
 
-	rval = 0;
+	initkwds();
+	if (mimic_gnu)
+		setup_builtin("format", FORMATTYPE);
+
 	active = stdout;		/* default active output     */
 	bbase[0] = bufbase;
         if (!argc) {
- 		sp = -1;		/* stack pointer initialized */
-		fp = 0; 		/* frame pointer initialized */
+		sp = -1;		/* stack pointer initialized */
+		fp = 0;			/* frame pointer initialized */
 		set_input(infile+0, stdin, "stdin");
 					/* default input (naturally) */
-		if ((inname[0] = strdup("-")) == NULL)
-			err(1, NULL);
-		inlineno[0] = 1;
-		emitline();
 		macro();
 	} else
 		for (; argc--; ++argv) {
 			p = *argv;
 			if (p[0] == '-' && p[1] == EOS)
 				set_input(infile, stdin, "stdin");
-			else if (fopen_trypath(infile, p) == NULL) {
-				warn("%s", p);
-				rval = 1;
-				continue;
-			}
+			else if (fopen_trypath(infile, p) == NULL)
+				err(1, "%s", p);
 			sp = -1;
 			fp = 0;
-			if ((inname[0] = strdup(p)) == NULL)
-				err(1, NULL);
-			inlineno[0] = 1;
-			emitline();
 			macro();
-		    	release_input(infile);
+			release_input(infile);
 		}
 
-	if (*m4wraps) { 		/* anything for rundown ??   */
+	if (wrapindex) {
+		int i;
+
 		ilevel = 0;		/* in case m4wrap includes.. */
 		bufbase = bp = buf;	/* use the entire buffer   */
-		pbstr(m4wraps); 	/* user-defined wrapup act   */
-		macro();		/* last will and testament   */
+		if (mimic_gnu) {
+			while (wrapindex != 0) {
+				for (i = 0; i < wrapindex; i++)
+					pbstr(m4wraps[i]);
+				wrapindex =0;
+				macro();
+			}
+		} else {
+			for (i = 0; i < wrapindex; i++) {
+				pbstr(m4wraps[i]);
+				macro();
+			}
+		}
 	}
 
 	if (active != stdout)
@@ -290,7 +282,7 @@
 		(void) fclose(outfile[0]);
 	}
 
-	exit(rval);
+	return 0;
 }
 
 /*
@@ -310,17 +302,17 @@
 	for (i = 1; *++token; i++) {
 		t = gpbc();
 		if (t == EOF || (unsigned char)t != (unsigned char)*token) {
-			putback(t);
+			pushback(t);
 			while (--i)
-				putback(*--token);
+				pushback(*--token);
 			return 0;
 		}
 	}
 	return 1;
 }
 
-#define LOOK_AHEAD(t, token) (t != EOF && 		\
-    (unsigned char)(t)==(unsigned char)(token)[0] && 	\
+#define LOOK_AHEAD(t, token) (t != EOF &&		\
+    (unsigned char)(t)==(unsigned char)(token)[0] &&	\
     do_look_ahead(t,token))
 
 /*
@@ -336,61 +328,8 @@
 
 	cycle {
 		t = gpbc();
-		if (t == '_' || isalpha(t)) {
-			p = inspect(t, token);
-			if (p != nil)
-				putback(l = gpbc());
-			if (p == nil || (l != LPAREN &&
-			    (p->type & NEEDARGS) != 0))
-				outputstr(token);
-			else {
-		/*
-		 * real thing.. First build a call frame:
-		 */
-				pushf(fp);	/* previous call frm */
-				pushf(p->type); /* type of the call  */
-				pushf(0);	/* parenthesis level */
-				fp = sp;	/* new frame pointer */
-		/*
-		 * now push the string arguments:
-		 */
-				pushs1(p->defn);	/* defn string */
-				pushs1(p->name);	/* macro name  */
-				pushs(ep);	      	/* start next..*/
 
-				if (l != LPAREN && PARLEV == 0)  {
-				    /* no bracks  */
-					chrsave(EOS);
-
-					if ((uintptr_t)sp == STACKMAX)
-						errx(1, "internal stack overflow");
-					eval((const char **) mstack+fp+1, 2,
-					    CALTYP);
-
-					ep = PREVEP;	/* flush strspace */
-					sp = PREVSP;	/* previous sp..  */
-					fp = PREVFP;	/* rewind stack...*/
-				}
-			}
-		} else if (t == EOF) {
-			if (sp > -1) {
-				warnx( "unexpected end of input, unclosed parenthesis:");
-				dump_stack(paren, PARLEV);
-				exit(1);
-			}
-			if (ilevel <= 0)
-				break;			/* all done thanks.. */
-			release_input(infile+ilevel--);
-			free(inname[ilevel+1]);
-			bufbase = bbase[ilevel];
-			emitline();
-			continue;
-		}
-	/*
-	 * non-alpha token possibly seen..
-	 * [the order of else if .. stmts is important.]
-	 */
-		else if (LOOK_AHEAD(t,lquote)) {	/* strip quotes */
+		if (LOOK_AHEAD(t,lquote)) {	/* strip quotes */
 			nlpar = 0;
 			record(quotes, nlpar++);
 			/*
@@ -416,32 +355,77 @@
 				} else {
 					if (nlpar > 0) {
 						if (sp < 0)
-							putc(l, active);
+							reallyputchar(l);
 						else
 							CHRSAVE(l);
 					}
 				}
 			}
 			while (nlpar != 0);
-		}
-
-		else if (sp < 0 && LOOK_AHEAD(t, scommt)) {
-			fputs(scommt, active);
+		} else if (sp < 0 && LOOK_AHEAD(t, scommt)) {
+			reallyoutputstr(scommt);
 
 			for(;;) {
 				t = gpbc();
 				if (LOOK_AHEAD(t, ecommt)) {
-					fputs(ecommt, active);
+					reallyoutputstr(ecommt);
 					break;
 				}
 				if (t == EOF)
 					break;
-				putc(t, active);
+				reallyputchar(t);
 			}
-		}
+		} else if (t == '_' || isalpha(t)) {
+			p = inspect(t, token);
+			if (p != NULL)
+				pushback(l = gpbc());
+			if (p == NULL || (l != LPAREN &&
+			    (macro_getdef(p)->type & NEEDARGS) != 0))
+				outputstr(token);
+			else {
+		/*
+		 * real thing.. First build a call frame:
+		 */
+				pushf(fp);	/* previous call frm */
+				pushf(macro_getdef(p)->type); /* type of the call  */
+				pushf(is_traced(p));
+				pushf(0);	/* parenthesis level */
+				fp = sp;	/* new frame pointer */
+		/*
+		 * now push the string arguments:
+		 */
+				pushs1(macro_getdef(p)->defn);	/* defn string */
+				pushs1((char *)macro_name(p));	/* macro name  */
+				pushs(ep);			/* start next..*/
 
-		else if (sp < 0) {		/* not in a macro at all */
-			putc(t, active);	/* output directly..	 */
+				if (l != LPAREN && PARLEV == 0) {
+				    /* no bracks  */
+					chrsave(EOS);
+
+					if (sp == (int)STACKMAX)
+						errx(1, "internal stack overflow");
+					eval((const char **) mstack+fp+1, 2,
+					    CALTYP, TRACESTATUS);
+
+					ep = PREVEP;	/* flush strspace */
+					sp = PREVSP;	/* previous sp..  */
+					fp = PREVFP;	/* rewind stack...*/
+				}
+			}
+		} else if (t == EOF) {
+			if (sp > -1 && ilevel <= 0) {
+				warnx( "unexpected end of input, unclosed parenthesis:");
+				dump_stack(paren, PARLEV);
+				exit(1);
+			}
+			if (ilevel <= 0)
+				break;			/* all done thanks.. */
+			release_input(infile+ilevel--);
+			emit_synchline();
+			bufbase = bbase[ilevel];
+			continue;
+		} else if (sp < 0) {		/* not in a macro at all */
+			reallyputchar(t);	/* output directly..	 */
 		}
 
 		else switch(t) {
@@ -449,9 +433,10 @@
 		case LPAREN:
 			if (PARLEV > 0)
 				chrsave(t);
-			while (isspace(l = gpbc()))
-				;		/* skip blank, tab, nl.. */
-			putback(l);
+			while (isspace(l = gpbc())) /* skip blank, tab, nl.. */
+				if (PARLEV > 0)
+					chrsave(l);
+			pushback(l);
 			record(paren, PARLEV++);
 			break;
 
@@ -461,11 +446,11 @@
 			else {			/* end of argument list */
 				chrsave(EOS);
 
-				if ((uintptr_t)sp == STACKMAX)
+				if (sp == (int)STACKMAX)
 					errx(1, "internal stack overflow");
 
 				eval((const char **) mstack+fp+1, sp-fp,
-				    CALTYP);
+				    CALTYP, TRACESTATUS);
 
 				ep = PREVEP;	/* flush strspace */
 				sp = PREVSP;	/* previous sp..  */
@@ -478,7 +463,7 @@
 				chrsave(EOS);		/* new argument   */
 				while (isspace(l = gpbc()))
 					;
-				putback(l);
+				pushback(l);
 				pushs(ep);
 			} else
 				chrsave(t);
@@ -486,14 +471,14 @@
 
 		default:
 			if (LOOK_AHEAD(t, scommt)) {
-				char *pc;
-				for (pc = scommt; *pc; pc++)
-					chrsave(*pc);
+				char *cp;
+				for (cp = scommt; *cp; cp++)
+					chrsave(*cp);
 				for(;;) {
 					t = gpbc();
 					if (LOOK_AHEAD(t, ecommt)) {
-						for (pc = ecommt; *pc; pc++)
-							chrsave(*pc);
+						for (cp = ecommt; *cp; cp++)
+							chrsave(*cp);
 						break;
 					}
 					if (t == EOF)
@@ -514,17 +499,43 @@
 outputstr(const char *s)
 {
 	if (sp < 0)
-		while (*s)
-			putc(*s++, active);
+		reallyoutputstr(s);
 	else
 		while (*s)
 			CHRSAVE(*s++);
 }
 
+void
+reallyoutputstr(const char *s)
+{
+	if (synch_lines) {
+		while (*s) {
+			fputc(*s, active);
+			if (*s++ == '\n') {
+				infile[ilevel].synch_lineno++;
+				if (infile[ilevel].synch_lineno !=
+				    infile[ilevel].lineno)
+					do_emit_synchline();
+			}
+		}
+	} else
+		fputs(s, active);
+}
+
+void
+reallyputchar(int c)
+{
+	putc(c, active);
+	if (synch_lines && c == '\n') {
+		infile[ilevel].synch_lineno++;
+		if (infile[ilevel].synch_lineno != infile[ilevel].lineno)
+			do_emit_synchline();
+	}
+}
+
 /*
  * build an input token..
- * consider only those starting with _ or A-Za-z. This is a
- * combo with lookup to speed things up.
+ * consider only those starting with _ or A-Za-z.
  */
 static ndptr
 inspect(int c, char *tp)
@@ -532,14 +543,13 @@
 	char *name = tp;
 	char *etp = tp+MAXTOK;
 	ndptr p;
-	unsigned int h;
 
-	h = *tp++ = c;
+	*tp++ = c;
 
 	while ((isalnum(c = gpbc()) || c == '_') && tp < etp)
-		h = (h << 5) + h + (*tp++ = c);
+		*tp++ = c;
 	if (c != EOF)
-		PUTBACK(c);
+		PUSHBACK(c);
 	*tp = EOS;
 	/* token is too long, it won't match anything, but it can still
 	 * be output. */
@@ -547,17 +557,19 @@
 		outputstr(name);
 		while (isalnum(c = gpbc()) || c == '_') {
 			if (sp < 0)
-				putc(c, active);
+				reallyputchar(c);
 			else
 				CHRSAVE(c);
 		}
 		*name = EOS;
-		return nil;
+		return NULL;
 	}
 
-	for (p = hashtab[h % HASHSIZE]; p != nil; p = p->nxtptr)
-		if (h == p->hv && STREQ(name, p->name))
-			break;
+	p = ohash_find(&macros, ohash_qlookupi(&macros, name, (const char **)&tp));
+	if (p == NULL)
+		return NULL;
+	if (macro_getdef(p) == NULL)
+		return NULL;
 	return p;
 }
 
@@ -571,45 +583,15 @@
 static void
 initkwds(void)
 {
-	size_t i;
-	unsigned int h;
-	ndptr p;
-
-	for (i = 0; i < MAXKEYS; i++) {
-		h = hash(keywrds[i].knam);
-		p = (ndptr) xalloc(sizeof(struct ndblock));
-		p->nxtptr = hashtab[h % HASHSIZE];
-		hashtab[h % HASHSIZE] = p;
-		p->name = xstrdup(keywrds[i].knam);
-		p->defn = null;
-		p->hv = h;
-		p->type = keywrds[i].ktyp & TYPEMASK;
-		if ((keywrds[i].ktyp & NOARGS) == 0)
-			p->type |= NEEDARGS;
-	}
-}
-
-/* Look up a builtin type, even if overridden by the user */
-int
-builtin_type(const char *key)
-{
+	unsigned int type;
 	int i;
 
-	for (i = 0; i != MAXKEYS; i++)
-		if (STREQ(keywrds[i].knam, key))
-			return keywrds[i].ktyp;
-	return -1;
-}
-
-const char *
-builtin_realname(int n)
-{
-	int i;
-
-	for (i = 0; i != MAXKEYS; i++)
-		if (((keywrds[i].ktyp ^ n) & TYPEMASK) == 0)
-			return keywrds[i].knam;
-	return NULL;
+	for (i = 0; i < (int)MAXKEYS; i++) {
+		type = keywrds[i].ktyp & TYPEMASK;
+		if ((keywrds[i].ktyp & NOARGS) == 0)
+			type |= NEEDARGS;
+		setup_builtin(keywrds[i].knam, type);
+	}
 }
 
 static void
@@ -640,20 +622,11 @@
 static void
 enlarge_stack(void)
 {
-	STACKMAX *= 2;
-	mstack = realloc(mstack, sizeof(stae) * STACKMAX);
-	sstack = realloc(sstack, STACKMAX);
-	if (mstack == NULL || sstack == NULL)
-		errx(1, "Evaluation stack overflow (%lu)",
-		    (unsigned long)STACKMAX);
+	STACKMAX += STACKMAX/2;
+	mstack = xrealloc(mstack, sizeof(stae) * STACKMAX,
+	    "Evaluation stack overflow (%lu)",
+	    (unsigned long)STACKMAX);
+	sstack = xrealloc(sstack, STACKMAX,
+	    "Evaluation stack overflow (%lu)",
+	    (unsigned long)STACKMAX);
 }
-
-/* Emit preprocessor #line directive if -s option used. */
-void
-emitline(void)
-{
-
-	if (synccpp)
-		fprintf(active, "#line %d \"%s\"\n", inlineno[ilevel],
-			inname[ilevel]);
-}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.bin/m4/mdef.h
--- a/head/usr.bin/m4/mdef.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/usr.bin/m4/mdef.h	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-/*	$OpenBSD: mdef.h,v 1.21 2001/09/27 11:40:33 espie Exp $	*/
+/*	$OpenBSD: mdef.h,v 1.31 2011/09/27 07:24:02 espie Exp $	*/
 /*	$NetBSD: mdef.h,v 1.7 1996/01/13 23:25:27 pk Exp $	*/
 
 /*
@@ -16,7 +16,7 @@
  * 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.
- * 4. Neither the name of the University nor the names of its contributors
+ * 3. Neither the name of the University nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
  *
@@ -33,9 +33,15 @@
  * SUCH DAMAGE.
  *
  *	@(#)mdef.h	8.1 (Berkeley) 6/6/93
- * $FreeBSD$
+ * $FreeBSD: head/usr.bin/m4/mdef.h 228063 2011-11-28 13:32:39Z bapt $
  */
 
+#ifdef __GNUC__
+# define UNUSED	__attribute__((__unused__))
+#else
+# define UNUSED
+#endif
+
 #define MACRTYPE        1
 #define DEFITYPE        2
 #define EXPRTYPE        3
@@ -79,7 +85,9 @@
 #define ESYSCMDTYPE	41
 #define TRACEONTYPE	42
 #define TRACEOFFTYPE	43
+#define FORMATTYPE	44
 
+#define BUILTIN_MARKER	"__builtin_"
 
 #define TYPEMASK	63	/* Keep bits really corresponding to a type. */
 #define RECDEF		256	/* Pure recursive def, don't expand it */
@@ -108,13 +116,12 @@
  */
 
 #define EOS             '\0'
-#define MAXINP          10              /* maximum include files   	    */
-#define MAXOUT          10              /* maximum # of diversions 	    */
+#define MAXINP          10              /* maximum include files	    */
+#define MAXOUT          10              /* maximum # of diversions	    */
 #define BUFSIZE         4096            /* starting size of pushback buffer */
-#define INITSTACKMAX    4096           	/* starting size of call stack      */
+#define INITSTACKMAX    4096		/* starting size of call stack      */
 #define STRSPMAX        4096            /* starting size of string space    */
-#define MAXTOK          512          	/* maximum chars in a tokn 	    */
-#define HASHSIZE        199             /* maximum size of hashtab 	    */
+#define MAXTOK          512		/* maximum chars in a tokn	    */
 #define MAXCCHARS	5		/* max size of comment/quote delim  */
 
 #define ALL             1
@@ -130,31 +137,31 @@
 
 typedef struct ndblock *ndptr;
 
-struct ndblock {		/* hastable structure         */
-	char		*name;	/* entry name..               */
+struct macro_definition {
+	struct macro_definition *next;
 	char		*defn;	/* definition..               */
 	unsigned int	type;	/* type of the entry..        */
-	unsigned int 	hv;	/* hash function value..      */
-	ndptr		nxtptr;	/* link to next entry..       */
 };
 
-#define nil     ((ndptr) 0)
 
-struct keyblk {
-        const char    *knam;    /* keyword name */
-        int     ktyp;           /* keyword type */
+struct ndblock {			/* hashtable structure         */
+	unsigned int		builtin_type;
+	unsigned int		trace_flags;
+	struct macro_definition *d;
+	char		name[1];	/* entry name..               */
 };
 
 typedef union {			/* stack structure */
 	int	sfra;		/* frame entry  */
-	char 	*sstr;		/* string entry */
+	char	*sstr;		/* string entry */
 } stae;
 
 struct input_file {
-	FILE 		*file;
-	char 		*name;
-	unsigned long 	lineno;
-	int 		c;
+	FILE		*file;
+	char		*name;
+	unsigned long	lineno;
+	unsigned long   synch_lineno;	/* used for -s */
+	int		c;
 };
 
 #define CURRENT_NAME	(infile[ilevel].name)
@@ -162,31 +169,33 @@
 /*
  * macros for readibility and/or speed
  *
+ *      gpbc()  - get a possibly pushed-back character
  *      pushf() - push a call frame entry onto stack
  *      pushs() - push a string pointer onto stack
  */
-#define pushf(x) 					\
-	do {						\
-		if ((uintptr_t)++sp == STACKMAX) 	\
-			enlarge_stack();		\
-		mstack[sp].sfra = (x);			\
-		sstack[sp] = 0;				\
+#define gpbc()	 (bp > bufbase) ? *--bp : obtain_char(infile+ilevel)
+#define pushf(x)			\
+	do {				\
+		if (++sp == (int)STACKMAX)	\
+			enlarge_stack();\
+		mstack[sp].sfra = (x);	\
+		sstack[sp] = 0; \
 	} while (0)
 
-#define pushs(x) 					\
-	do {						\
-		if ((uintptr_t)++sp == STACKMAX) 	\
-			enlarge_stack();		\
-		mstack[sp].sstr = (x);			\
-		sstack[sp] = 1;				\
+#define pushs(x)			\
+	do {				\
+		if (++sp == (int)STACKMAX)	\
+			enlarge_stack();\
+		mstack[sp].sstr = (x);	\
+		sstack[sp] = 1; \
 	} while (0)
 
-#define pushs1(x) 					\
-	do {						\
-		if ((uintptr_t)++sp == STACKMAX) 	\
-			enlarge_stack();		\
-		mstack[sp].sstr = (x);			\
-		sstack[sp] = 0;				\
+#define pushs1(x)			\
+	do {				\
+		if (++sp == (int)STACKMAX)	\
+			enlarge_stack();\
+		mstack[sp].sstr = (x);	\
+		sstack[sp] = 0; \
 	} while (0)
 
 /*
@@ -195,25 +204,26 @@
  *	+-------+			+-----+
  *	| arg 3 ----------------------->| str |
  *	+-------+			|  .  |
- *	| arg 2 ---PREVEP-----+ 	   .
+ *	| arg 2 ---PREVEP-----+		   .
  *	+-------+	      |
  *	    .		      |		|     |
- *	+-------+	      | 	+-----+
+ *	+-------+	      |		+-----+
  *	| plev	|  PARLEV     +-------->| str |
  *	+-------+			|  .  |
  *	| type	|  CALTYP		   .
  *	+-------+
  *	| prcf	---PREVFP--+
- *	+-------+  	   |
+ *	+-------+	   |
  *	|   .	|  PREVSP  |
- *	    .	   	   |
+ *	    .		   |
  *	+-------+	   |
  *	|	<----------+
  *	+-------+
  *
  */
 #define PARLEV  (mstack[fp].sfra)
-#define CALTYP  (mstack[fp-1].sfra)
+#define CALTYP  (mstack[fp-2].sfra)
+#define TRACESTATUS (mstack[fp-1].sfra)
 #define PREVEP	(mstack[fp+3].sstr)
-#define PREVSP	(fp-3)
-#define PREVFP	(mstack[fp-2].sfra)
+#define PREVSP	(fp-4)
+#define PREVFP	(mstack[fp-3].sfra)
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.bin/m4/misc.c
--- a/head/usr.bin/m4/misc.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/usr.bin/m4/misc.c	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-/*	$OpenBSD: misc.c,v 1.27 2002/04/26 16:15:16 espie Exp $	*/
+/*	$OpenBSD: misc.c,v 1.42 2010/09/07 19:58:09 marco Exp $	*/
 /*	$NetBSD: misc.c,v 1.6 1995/09/28 05:37:41 tls Exp $	*/
 
 /*
@@ -16,7 +16,7 @@
  * 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.
- * 4. Neither the name of the University nor the names of its contributors
+ * 3. Neither the name of the University nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
  *
@@ -32,23 +32,13 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  */
-
-#ifndef lint
-#if 0
-static char sccsid[] = "@(#)misc.c	8.1 (Berkeley) 6/6/93";
-#else
-#if 0
-static char rcsid[] = "$OpenBSD: misc.c,v 1.27 2002/04/26 16:15:16 espie Exp $";
-#endif
-#endif
-#endif /* not lint */
-
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/usr.bin/m4/misc.c 228063 2011-11-28 13:32:39Z bapt $");
 
 #include <sys/types.h>
 #include <errno.h>
 #include <unistd.h>
+#include <stdarg.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <stddef.h>
@@ -66,11 +56,11 @@
 static size_t strsize = STRSPMAX;
 static size_t bufsize = BUFSIZE;
 
-char *buf;			/* push-back buffer	       */
-char *bufbase;			/* the base for current ilevel */
-char *bbase[MAXINP];		/* the base for each ilevel    */
-char *bp; 			/* first available character   */
-char *endpbb;			/* end of push-back buffer     */
+unsigned char *buf;			/* push-back buffer	       */
+unsigned char *bufbase;			/* the base for current ilevel */
+unsigned char *bbase[MAXINP];		/* the base for each ilevel    */
+unsigned char *bp;			/* first available character   */
+unsigned char *endpbb;			/* end of push-back buffer     */
 
 
 /*
@@ -88,10 +78,10 @@
 		return (t - s1);
 }
 /*
- *  putback - push character back onto input
+ *  pushback - push character back onto input
  */
 void
-putback(int c)
+pushback(int c)
 {
 	if (c == EOF)
 		return;
@@ -102,7 +92,7 @@
 
 /*
  *  pbstr - push string back onto input
- *          putback is replicated to improve
+ *          pushback is replicated to improve
  *          performance.
  */
 void
@@ -111,7 +101,7 @@
 	size_t n;
 
 	n = strlen(s);
-	while ((size_t)(endpbb - bp) <= n)
+	while (endpbb - bp <= (long)n)
 		enlarge_bufspace();
 	while (n > 0)
 		*bp++ = s[--n];
@@ -123,16 +113,36 @@
 void
 pbnum(int n)
 {
+	pbnumbase(n, 10, 0);
+}
+
+void
+pbnumbase(int n, int base, int d)
+{
+	static char digits[36] = "0123456789abcdefghijklmnopqrstuvwxyz";
 	int num;
+	int printed = 0;
+
+	if (base > 36)
+		m4errx(1, "base %d > 36: not supported.", base);
+
+	if (base < 2)
+		m4errx(1, "bad base %d for conversion.", base);
 
 	num = (n < 0) ? -n : n;
 	do {
-		putback(num % 10 + '0');
+		pushback(digits[num % base]);
+		printed++;
 	}
-	while ((num /= 10) > 0);
+	while ((num /= base) > 0);
 
 	if (n < 0)
-		putback('-');
+		printed++;
+	while (printed++ < d)
+		pushback('0');
+
+	if (n < 0)
+		pushback('-');
 }
 
 /*
@@ -142,7 +152,7 @@
 pbunsigned(unsigned long n)
 {
 	do {
-		putback(n % 10 + '0');
+		pushback(n % 10 + '0');
 	}
 	while ((n /= 10) > 0);
 }
@@ -152,10 +162,10 @@
 {
 	int i;
 
-	strspace = xalloc(strsize+1);
+	strspace = xalloc(strsize+1, NULL);
 	ep = strspace;
 	endest = strspace+strsize;
-	buf = (char *)xalloc(bufsize);
+	buf = (unsigned char *)xalloc(bufsize, NULL);
 	bufbase = buf;
 	bp = buf;
 	endpbb = buf + bufsize;
@@ -187,13 +197,11 @@
 void
 enlarge_bufspace(void)
 {
-	char *newbuf;
+	unsigned char *newbuf;
 	int i;
 
-	bufsize *= 2;
-	newbuf = realloc(buf, bufsize);
-	if (!newbuf)
-		errx(1, "too many characters pushed back");
+	bufsize += bufsize/2;
+	newbuf = xrealloc(buf, bufsize, "too many characters pushed back");
 	for (i = 0; i < MAXINP; i++)
 		bbase[i] = (bbase[i]-buf)+newbuf;
 	bp = (bp-buf)+newbuf;
@@ -222,7 +230,7 @@
 	int c;
 
 	if (active == outfile[n])
-		errx(1, "undivert: diversion still active");
+		m4errx(1, "undivert: diversion still active.");
 	rewind(outfile[n]);
 	while ((c = getc(outfile[n])) != EOF)
 		putc(c, active);
@@ -231,7 +239,7 @@
 }
 
 void
-onintr(int signo __unused)
+onintr(__unused int signo)
 {
 #define intrmessage	"m4: interrupted.\n"
 	write(STDERR_FILENO, intrmessage, sizeof(intrmessage)-1);
@@ -252,6 +260,24 @@
 		}
 }
 
+extern char *__progname;
+
+void
+m4errx(int evaluation, const char *fmt, ...)
+{
+	fprintf(stderr, "%s: ", __progname);
+	fprintf(stderr, "%s at line %lu: ", CURRENT_NAME, CURRENT_LINE);
+	if (fmt != NULL) {
+		va_list ap;
+
+		va_start(ap, fmt);
+		vfprintf(stderr, fmt, ap);
+		va_end(ap);
+	}
+	fprintf(stderr, "\n");
+	exit(evaluation);
+}
+
 /*
  * resizedivs: allocate more diversion files */
 void
@@ -259,21 +285,49 @@
 {
 	int i;
 
-	outfile = (FILE **)realloc(outfile, sizeof(FILE *) * n);
-	if (outfile == NULL)
-		    errx(1, "too many diverts %d", n);
+	outfile = (FILE **)xrealloc(outfile, sizeof(FILE *) * n,
+	    "too many diverts %d", n);
 	for (i = maxout; i < n; i++)
 		outfile[i] = NULL;
 	maxout = n;
 }
 
 void *
-xalloc(size_t n)
+xalloc(size_t n, const char *fmt, ...)
 {
-	char *p = malloc(n);
+	void *p = malloc(n);
 
-	if (p == NULL)
-		err(1, "malloc");
+	if (p == NULL) {
+		if (fmt == NULL)
+			err(1, "malloc");
+		else {
+			va_list va;
+
+			va_start(va, fmt);
+			verr(1, fmt, va);
+			va_end(va);
+		}
+	}
+	return p;
+}
+
+void *
+xrealloc(void *old, size_t n, const char *fmt, ...)
+{
+	char *p = realloc(old, n);
+
+	if (p == NULL) {
+		free(old);
+		if (fmt == NULL)
+			err(1, "realloc");
+		else {
+			va_list va;
+
+			va_start(va, fmt);
+			verr(1, fmt, va);
+			va_end(va);
+		}
+	}
 	return p;
 }
 
@@ -289,9 +343,9 @@
 void
 usage(void)
 {
-	fprintf(stderr,
-"usage: m4 [-d flags] [-t name] [-gs] [-D name[=value]]...\n"
-"          [-U name]... [-I dirname]... file...\n");
+	fprintf(stderr, "usage: m4 [-gPs] [-Dname[=value]] [-d flags] "
+			"[-I dirname] [-o filename]\n"
+			"\t[-t macro] [-Uname] [file ...]\n");
 	exit(1);
 }
 
@@ -300,10 +354,11 @@
 {
 	if (f->c == EOF)
 		return EOF;
-	else if (f->c == '\n')
+
+	f->c = fgetc(f->file);
+	if (f->c == '\n')
 		f->lineno++;
 
-	f->c = fgetc(f->file);
 	return f->c;
 }
 
@@ -314,6 +369,15 @@
 	f->lineno = 1;
 	f->c = 0;
 	f->name = xstrdup(name);
+	emit_synchline();
+}
+
+void
+do_emit_synchline(void)
+{
+	fprintf(active, "#line %lu \"%s\"\n",
+	    infile[ilevel].lineno, infile[ilevel].name);
+	infile[ilevel].synch_lineno = infile[ilevel].lineno;
 }
 
 void
@@ -356,8 +420,8 @@
 void
 dump_buffer(FILE *f, size_t m)
 {
-	char *s;
+	unsigned char *s;
 
-	for (s = bp; s - buf > (int)m;)
+	for (s = bp; s-buf > (long)m;)
 		fputc(*--s, f);
 }
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.bin/m4/parser.y
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/usr.bin/m4/parser.y	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,83 @@
+%{
+/* $OpenBSD: parser.y,v 1.6 2008/08/21 21:00:14 espie Exp $ */
+/*
+ * Copyright (c) 2004 Marc Espie <espie at cvs.openbsd.org>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, 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.
+ *
+ * $FreeBSD: head/usr.bin/m4/parser.y 228063 2011-11-28 13:32:39Z bapt $
+ */
+#include <stdint.h>
+#define YYSTYPE	int32_t
+extern int32_t end_result;
+extern int yylex(void);
+extern int yyerror(const char *);
+extern int yyparse(void);
+%}
+%token NUMBER
+%token ERROR
+%left LOR
+%left LAND
+%left '|'
+%left '^'
+%left '&'
+%left EQ NE
+%left '<' LE '>' GE
+%left LSHIFT RSHIFT
+%left '+' '-'
+%left '*' '/' '%'
+%right UMINUS UPLUS '!' '~'
+
+%%
+
+top	: expr { end_result = $1; }
+	;
+expr 	: expr '+' expr { $$ = $1 + $3; }
+     	| expr '-' expr { $$ = $1 - $3; }
+     	| expr '*' expr { $$ = $1 * $3; }
+	| expr '/' expr {
+		if ($3 == 0) {
+			yyerror("division by zero");
+			exit(1);
+		}
+		$$ = $1 / $3;
+	}
+	| expr '%' expr { 
+		if ($3 == 0) {
+			yyerror("modulo zero");
+			exit(1);
+		}
+		$$ = $1 % $3;
+	}
+	| expr LSHIFT expr { $$ = $1 << $3; }
+	| expr RSHIFT expr { $$ = $1 >> $3; }
+	| expr '<' expr { $$ = $1 < $3; }
+	| expr '>' expr { $$ = $1 > $3; }
+	| expr LE expr { $$ = $1 <= $3; }
+	| expr GE expr { $$ = $1 >= $3; }
+	| expr EQ expr { $$ = $1 == $3; }
+	| expr NE expr { $$ = $1 != $3; }
+	| expr '&' expr { $$ = $1 & $3; }
+	| expr '^' expr { $$ = $1 ^ $3; }
+	| expr '|' expr { $$ = $1 | $3; }
+	| expr LAND expr { $$ = $1 && $3; }
+	| expr LOR expr { $$ = $1 || $3; }
+	| '(' expr ')' { $$ = $2; }
+	| '-' expr %prec UMINUS { $$ = -$2; }
+	| '+' expr %prec UPLUS  { $$ = $2; }
+	| '!' expr { $$ = !$2; }
+	| '~' expr { $$ = ~$2; }
+	| NUMBER
+	;
+%%
+
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.bin/m4/pathnames.h
--- a/head/usr.bin/m4/pathnames.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/usr.bin/m4/pathnames.h	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-/*	$OpenBSD: pathnames.h,v 1.4 1997/04/04 18:41:29 deraadt Exp $	*/
+/*	$OpenBSD: pathnames.h,v 1.5 2003/06/03 02:56:10 millert Exp $	*/
 /*	$NetBSD: pathnames.h,v 1.6 1995/09/29 00:27:55 cgd Exp $	*/
 
 /*
@@ -16,7 +16,7 @@
  * 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.
- * 4. Neither the name of the University nor the names of its contributors
+ * 3. Neither the name of the University nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
  *
@@ -33,7 +33,7 @@
  * SUCH DAMAGE.
  *
  *	@(#)pathnames.h	8.1 (Berkeley) 6/6/93
- * $FreeBSD$
+ * $FreeBSD: head/usr.bin/m4/pathnames.h 228063 2011-11-28 13:32:39Z bapt $
  */
 
 /*
@@ -46,8 +46,7 @@
 #define	UNIQUE		3			/* unique char location */
 #endif
 
-#if defined(unix) || defined(__FreeBSD__) || defined(__NetBSD__) || \
-	defined(__OpenBSD__)
+#if defined(unix) || defined(__NetBSD__) || defined(__OpenBSD__)
 #define _PATH_DIVNAME	"/tmp/m4.0XXXXXXXXXX"	/* unix diversion files */
 #define UNIQUE		8			/* unique char location */
 #endif
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.bin/m4/stdd.h
--- a/head/usr.bin/m4/stdd.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/usr.bin/m4/stdd.h	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-/*	$OpenBSD: stdd.h,v 1.4 1999/11/09 18:16:18 deraadt Exp $	*/
+/*	$OpenBSD: stdd.h,v 1.6 2010/09/07 19:58:09 marco Exp $	*/
 /*	$NetBSD: stdd.h,v 1.2 1995/09/28 05:37:50 tls Exp $	*/
 
 /*-
@@ -16,7 +16,7 @@
  * 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.
- * 4. Neither the name of the University nor the names of its contributors
+ * 3. Neither the name of the University nor the names of its contributors
  *    may be used to endorse or promote products derived from this software
  *    without specific prior written permission.
  *
@@ -33,7 +33,7 @@
  * SUCH DAMAGE.
  *
  *	@(#)stdd.h	8.1 (Berkeley) 6/6/93
- * $FreeBSD$
+ * $FreeBSD: head/usr.bin/m4/stdd.h 228063 2011-11-28 13:32:39Z bapt $
  */
 
 /*
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.bin/m4/tokenizer.l
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/usr.bin/m4/tokenizer.l	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,111 @@
+%option nounput noinput
+%{
+/* $OpenBSD: tokenizer.l,v 1.7 2010/03/22 20:40:44 espie Exp $ */
+/*
+ * Copyright (c) 2004 Marc Espie <espie at cvs.openbsd.org>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, 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.
+ *
+ * $FreeBSD: head/usr.bin/m4/tokenizer.l 228063 2011-11-28 13:32:39Z bapt $
+ */
+#include "parser.h"
+#include <assert.h>
+#include <stdlib.h>
+#include <errno.h>
+#include <stdint.h>
+#include <limits.h>
+
+extern int mimic_gnu;
+extern int32_t yylval;
+
+int32_t number(void);
+int32_t parse_radix(void);
+extern int yylex(void);
+%}
+
+delim 	[ \t\n]
+ws	{delim}+
+hex	0[xX][0-9a-fA-F]+
+oct	0[0-7]*
+dec	[1-9][0-9]*
+radix	0[rR][0-9]+:[0-9a-zA-Z]+
+
+%%
+{ws}			{/* just skip it */}
+{hex}|{oct}|{dec}	{ yylval = number(); return(NUMBER); }
+{radix}			{ if (mimic_gnu) {
+				yylval = parse_radix(); return(NUMBER);
+			  } else {
+			  	return(ERROR);
+			  }
+			}
+"<="			{ return(LE); }
+">="			{ return(GE); }
+"<<"			{ return(LSHIFT); }
+">>"			{ return(RSHIFT); }
+"=="			{ return(EQ); }
+"!="			{ return(NE); }
+"&&"			{ return(LAND); }
+"||"			{ return(LOR); }
+.			{ return yytext[0]; }
+%%
+
+int32_t
+number(void)
+{
+	long l;
+
+	errno = 0;
+	l = strtol(yytext, NULL, 0);
+	if (((l == LONG_MAX || l == LONG_MIN) && errno == ERANGE) ||
+	    l > INT32_MAX || l < INT32_MIN) {
+		fprintf(stderr, "m4: numeric overflow in expr: %s\n", yytext);
+	}
+	return l;
+}
+
+int32_t
+parse_radix(void)
+{
+	long base;
+	char *next;
+	long l;
+	int d;
+
+	l = 0;
+	base = strtol(yytext+2, &next, 0);
+	if (base > 36 || next == NULL) {
+		fprintf(stderr, "m4: error in number %s\n", yytext);
+	} else {
+		next++;
+		while (*next != 0) {
+			if (*next >= '0' && *next <= '9')
+				d = *next - '0';
+			else if (*next >= 'a' && *next <= 'z')
+				d = *next - 'a' + 10;
+			else {
+				assert(*next >= 'A' && *next <= 'Z');
+				d = *next - 'A' + 10;
+			}
+			if (d >= base) {
+				fprintf(stderr, 
+				    "m4: error in number %s\n", yytext);
+				return 0;
+			}
+			l = base * l + d;
+			next++;
+		}
+	}
+	return l;
+}
+
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.bin/m4/trace.c
--- a/head/usr.bin/m4/trace.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/usr.bin/m4/trace.c	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-/* $OpenBSD: trace.c,v 1.6 2002/04/26 16:15:16 espie Exp $ */
+/* $OpenBSD: trace.c,v 1.16 2010/09/07 19:58:09 marco Exp $ */
 /*
  * Copyright (c) 2001 Marc Espie.
  *
@@ -23,25 +23,21 @@
  * (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 <sys/cdefs.h>
+__FBSDID("$FreeBSD: head/usr.bin/m4/trace.c 228063 2011-11-28 13:32:39Z bapt $");
 
-#include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
-
-#include <sys/types.h>
+#include <err.h>
 #include <stddef.h>
+#include <stdint.h>
 #include <stdio.h>
-#include <err.h>
 #include <stdlib.h>
-#include <string.h>
 #include "mdef.h"
 #include "stdd.h"
 #include "extern.h"
 
 FILE *traceout;
 
-int traced_macros = 0;
-
-#define TRACE_ARGS 	1
+#define TRACE_ARGS	1
 #define TRACE_EXPANSION 2
 #define TRACE_QUOTE	4
 #define TRACE_FILENAME	8
@@ -50,81 +46,19 @@
 #define TRACE_ID	64
 #define TRACE_NEWFILE	128	/* not implemented yet */
 #define TRACE_INPUT	256	/* not implemented yet */
-#define TRACE_ALL	512
-
-static struct t {
-	struct t *next;
-	char 	 *name;
-	int	  on;
-} *l;
 
 static unsigned int letter_to_flag(int);
 static void print_header(struct input_file *);
-static struct t *find_trace_entry(const char *);
 static int frame_level(void);
 
-static unsigned int flags = TRACE_QUOTE | TRACE_EXPANSION;
 
-static struct t *
-find_trace_entry(const char *name)
-{
-	struct t *n;
-
-	for (n = l; n != NULL; n = n->next)
-		if (STREQ(n->name, name))
-			return n;
-	return NULL;
-}
-
-
-void
-mark_traced(const char *name, int on)
-{
-	struct t *n, *n2;
-
-	traced_macros = 1;
-
-	if (name == NULL) {
-		if (on)
-			flags |= TRACE_ALL;
-		else {
-			flags &= ~TRACE_ALL;
-			traced_macros = 0;
-		}
-		for (n = l; n != NULL; n = n2) {
-			n2 = n->next;
-			free(n->name);
-			free(n);
-		}
-		l = NULL;
-	} else {
-	    n = find_trace_entry(name);
-	    if (n == NULL) {
-		    n = xalloc(sizeof(struct t));
-		    n->name = xstrdup(name);
-		    n->next = l;
-		    l = n;
-	    }
-	    n->on = on;
-	}
-}
-
-int
-is_traced(const char *name)
-{
-	struct t *n;
-
-	for (n = l; n != NULL; n = n->next)
-		if (STREQ(n->name, name))
-			return n->on;
-	return (flags & TRACE_ALL) ? 1 : 0;
-}
+unsigned int trace_flags = TRACE_QUOTE | TRACE_EXPANSION;
 
 void
 trace_file(const char *name)
 {
 
-	if (traceout != stderr)
+	if (traceout && traceout != stderr)
 		fclose(traceout);
 	traceout = fopen(name, "w");
 	if (!traceout)
@@ -168,21 +102,19 @@
 	char mode = 0;
 	unsigned int f = 0;
 
-	traced_macros = 1;
-
 	if (*s == '+' || *s == '-')
 		mode = *s++;
 	while (*s)
 		f |= letter_to_flag(*s++);
 	switch(mode) {
 	case 0:
-		flags = f;
+		trace_flags = f;
 		break;
 	case '+':
-		flags |= f;
+		trace_flags |= f;
 		break;
 	case '-':
-		flags &= ~f;
+		trace_flags &= ~f;
 		break;
 	}
 }
@@ -194,7 +126,7 @@
 	int framep;
 
 	for (framep = fp, level = 0; framep != 0;
-		level++,framep = mstack[framep-2].sfra)
+		level++,framep = mstack[framep-3].sfra)
 		;
 	return level;
 }
@@ -203,25 +135,27 @@
 print_header(struct input_file *inp)
 {
 	fprintf(traceout, "m4trace:");
-	if (flags & TRACE_FILENAME)
+	if (trace_flags & TRACE_FILENAME)
 		fprintf(traceout, "%s:", inp->name);
-	if (flags & TRACE_LINENO)
+	if (trace_flags & TRACE_LINENO)
 		fprintf(traceout, "%lu:", inp->lineno);
 	fprintf(traceout, " -%d- ", frame_level());
-	if (flags & TRACE_ID)
+	if (trace_flags & TRACE_ID)
 		fprintf(traceout, "id %lu: ", expansion_id);
 }
 
-ssize_t
+size_t
 trace(const char *argv[], int argc, struct input_file *inp)
 {
+	if (!traceout)
+		traceout = stderr;
 	print_header(inp);
-	if (flags & TRACE_CONT) {
+	if (trace_flags & TRACE_CONT) {
 		fprintf(traceout, "%s ...\n", argv[1]);
 		print_header(inp);
 	}
 	fprintf(traceout, "%s", argv[1]);
-	if ((flags & TRACE_ARGS) && argc > 2) {
+	if ((trace_flags & TRACE_ARGS) && argc > 2) {
 		char delim[3];
 		int i;
 
@@ -229,25 +163,25 @@
 		delim[1] = EOS;
 		for (i = 2; i < argc; i++) {
 			fprintf(traceout, "%s%s%s%s", delim,
-			    (flags & TRACE_QUOTE) ? lquote : "",
+			    (trace_flags & TRACE_QUOTE) ? lquote : "",
 			    argv[i],
-			    (flags & TRACE_QUOTE) ? rquote : "");
+			    (trace_flags & TRACE_QUOTE) ? rquote : "");
 			delim[0] = COMMA;
 			delim[1] = ' ';
 			delim[2] = EOS;
 		}
 		fprintf(traceout, "%c", RPAREN);
 	}
-	if (flags & TRACE_CONT) {
+	if (trace_flags & TRACE_CONT) {
 		fprintf(traceout, " -> ???\n");
 		print_header(inp);
 		fprintf(traceout, argc > 2 ? "%s(...)" : "%s", argv[1]);
 	}
-	if (flags & TRACE_EXPANSION)
+	if (trace_flags & TRACE_EXPANSION)
 		return buffer_mark();
 	else {
 		fprintf(traceout, "\n");
-		return -1;
+		return SIZE_MAX;
 	}
 }
 
@@ -255,10 +189,10 @@
 finish_trace(size_t mark)
 {
 	fprintf(traceout, " -> ");
-	if (flags & TRACE_QUOTE)
+	if (trace_flags & TRACE_QUOTE)
 		fprintf(traceout, "%s", lquote);
 	dump_buffer(traceout, mark);
-	if (flags & TRACE_QUOTE)
+	if (trace_flags & TRACE_QUOTE)
 		fprintf(traceout, "%s", rquote);
 	fprintf(traceout, "\n");
 }
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.bin/make/Makefile
--- a/head/usr.bin/make/Makefile	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/usr.bin/make/Makefile	Tue Dec 06 20:26:16 2011 +0200
@@ -1,6 +1,6 @@
 #	@(#)Makefile	5.2 (Berkeley) 12/28/90
 #	$Id: Makefile,v 1.6 1994/06/30 05:33:39 cgd Exp $
-# $FreeBSD$
+# $FreeBSD: head/usr.bin/make/Makefile 228157 2011-11-30 18:07:38Z fjoe $
 
 PROG=	make
 CFLAGS+=-I${.CURDIR}
@@ -10,7 +10,9 @@
 
 NO_SHARED?=	YES
 
-CFLAGS+=-DMAKE_VERSION=\"5200408120\"
+# Version has the RYYYYMMDDX format, where R is from RELENG_<R>
+CFLAGS+=-DMAKE_VERSION=\"5201111300\"
+
 # There is no obvious performance improvement currently.
 # CFLAGS+=-DUSE_KQUEUE
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.bin/make/job.c
--- a/head/usr.bin/make/job.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/usr.bin/make/job.c	Tue Dec 06 20:26:16 2011 +0200
@@ -40,7 +40,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/usr.bin/make/job.c 228157 2011-11-30 18:07:38Z fjoe $");
 
 /*-
  * job.c --
@@ -381,7 +381,7 @@
 static void JobDoOutput(Job *, Boolean);
 static void JobInterrupt(int, int);
 static void JobRestartJobs(void);
-static int Compat_RunCommand(char *, struct GNode *);
+static int Compat_RunCommand(LstNode *, struct GNode *);
 
 static GNode	    *curTarg = NULL;
 static GNode	    *ENDNode;
@@ -647,7 +647,7 @@
  *	numCommands is incremented if the command is actually printed.
  */
 static int
-JobPrintCommand(char *cmd, Job *job)
+JobPrintCommand(LstNode *cmdNode, Job *job)
 {
 	Boolean	noSpecials;	/* true if we shouldn't worry about
 				 * inserting special commands into
@@ -658,40 +658,30 @@
 				 * off before printing the command
 				 * and need to turn it back on */
 	const char *cmdTemplate;/* Template to use when printing the command */
-	char	*cmdStart;	/* Start of expanded command */
-	LstNode	*cmdNode;	/* Node for replacing the command */
+	char	*cmd;		/* Expanded command */
 
 	noSpecials = (noExecute && !(job->node->type & OP_MAKE));
 
+#define	DBPRINTF(fmt, arg)			\
+	DEBUGF(JOB, (fmt, arg));		\
+	fprintf(job->cmdFILE, fmt, arg);	\
+	fflush(job->cmdFILE);
+
+	/*
+	 * For debugging, we replace each command with the result of expanding
+	 * the variables in the command.
+	 */
+	cmd = Buf_Peel(Var_Subst(Lst_Datum(cmdNode), job->node, FALSE));
 	if (strcmp(cmd, "...") == 0) {
+		free(cmd);
 		job->node->type |= OP_SAVE_CMDS;
 		if ((job->flags & JOB_IGNDOTS) == 0) {
-			job->tailCmds =
-			    Lst_Succ(Lst_Member(&job->node->commands, cmd));
+			job->tailCmds = Lst_Succ(cmdNode);
 			return (1);
 		}
 		return (0);
 	}
-
-#define	DBPRINTF(fmt, arg)			\
-	DEBUGF(JOB, (fmt, arg));		\
-	fprintf(job->cmdFILE, fmt, arg);	\
-	fflush(job->cmdFILE);
-
-	numCommands += 1;
-
-	/*
-	 * For debugging, we replace each command with the result of expanding
-	 * the variables in the command.
-	 */
-	cmdNode = Lst_Member(&job->node->commands, cmd);
-
-	cmd = Buf_Peel(Var_Subst(cmd, job->node, FALSE));
-	cmdStart = cmd;
-
-	Lst_Replace(cmdNode, cmdStart);
-
-	cmdTemplate = "%s\n";
+	Lst_Replace(cmdNode, cmd);
 
 	/*
 	 * Check for leading @', -' or +'s to control echoing, error checking,
@@ -715,7 +705,7 @@
 				 * but this one needs to be - use compat mode
 				 * just for it.
 				 */
-				Compat_RunCommand(cmd, job->node);
+				Compat_RunCommand(cmdNode, job->node);
 				return (0);
 			}
 			break;
@@ -726,6 +716,16 @@
 	while (isspace((unsigned char)*cmd))
 		cmd++;
 
+	/*
+	 * Ignore empty commands
+	 */
+	if (*cmd == '\0') {
+		return (0);
+	}
+
+	cmdTemplate = "%s\n";
+	numCommands += 1;
+
 	if (shutUp) {
 		if (!(job->flags & JOB_SILENT) && !noSpecials &&
 		    commandShell->hasEchoCtl) {
@@ -1665,7 +1665,7 @@
 				    Lst_Succ(gn->compat_command);
 
 			if (gn->compat_command == NULL ||
-			    JobPrintCommand(Lst_Datum(gn->compat_command), job))
+			    JobPrintCommand(gn->compat_command, job))
 				noExec = TRUE;
 
 			if (noExec && !(job->flags & JOB_FIRST)) {
@@ -1689,7 +1689,7 @@
 			 */
 			numCommands = 0;
 			LST_FOREACH(ln, &gn->commands) {
-				if (JobPrintCommand(Lst_Datum(ln), job))
+				if (JobPrintCommand(ln, job))
 					break;
 			}
 
@@ -1723,7 +1723,7 @@
 		 */
 		if (cmdsOK) {
 			LST_FOREACH(ln, &gn->commands) {
-				if (JobPrintCommand(Lst_Datum(ln), job))
+				if (JobPrintCommand(ln, job))
 					break;
 			}
 		}
@@ -2809,7 +2809,7 @@
 		gn = Targ_FindNode(".INTERRUPT", TARG_NOCREATE);
 		if (gn != NULL) {
 			LST_FOREACH(ln, &gn->commands) {
-				if (Compat_RunCommand(Lst_Datum(ln), gn))
+				if (Compat_RunCommand(ln, gn))
 					break;
 			}
 		}
@@ -2884,16 +2884,15 @@
  *	The node's 'made' field may be set to ERROR.
  */
 static int
-Compat_RunCommand(char *cmd, GNode *gn)
+Compat_RunCommand(LstNode *cmdNode, GNode *gn)
 {
 	ArgArray	aa;
-	char		*cmdStart;	/* Start of expanded command */
+	char		*cmd;		/* Expanded command */
 	Boolean		silent;		/* Don't print command */
 	Boolean		doit;		/* Execute even in -n */
 	Boolean		errCheck;	/* Check errors */
 	int		reason;		/* Reason for child's death */
 	int		status;		/* Description of child's death */
-	LstNode		*cmdNode;	/* Node where current cmd is located */
 	char		**av;		/* Argument vector for thing to exec */
 	ProcStuff	ps;
 
@@ -2901,31 +2900,16 @@
 	errCheck = !(gn->type & OP_IGNORE);
 	doit = FALSE;
 
-	cmdNode = Lst_Member(&gn->commands, cmd);
-	cmdStart = Buf_Peel(Var_Subst(cmd, gn, FALSE));
-
-	/*
-	 * brk_string will return an argv with a NULL in av[0], thus causing
-	 * execvp() to choke and die horribly. Besides, how can we execute a
-	 * null command? In any case, we warn the user that the command
-	 * expanded to nothing (is this the right thing to do?).
-	 */
-	if (*cmdStart == '\0') {
-		free(cmdStart);
-		Error("%s expands to empty string", cmd);
+	cmd = Buf_Peel(Var_Subst(Lst_Datum(cmdNode), gn, FALSE));
+	if ((gn->type & OP_SAVE_CMDS) && (gn != ENDNode)) {
+		Lst_AtEnd(&ENDNode->commands, cmd);
 		return (0);
-	} else {
-		cmd = cmdStart;
-	}
-	Lst_Replace(cmdNode, cmdStart);
-
-	if ((gn->type & OP_SAVE_CMDS) && (gn != ENDNode)) {
-		Lst_AtEnd(&ENDNode->commands, cmdStart);
-		return (0);
-	} else if (strcmp(cmdStart, "...") == 0) {
+	} else if (strcmp(cmd, "...") == 0) {
+		free(cmd);
 		gn->type |= OP_SAVE_CMDS;
 		return (0);
 	}
+	Lst_Replace(cmdNode, cmd);
 
 	while (*cmd == '@' || *cmd == '-' || *cmd == '+') {
 		switch (*cmd) {
@@ -2949,6 +2933,13 @@
 		cmd++;
 
 	/*
+	 * Ignore empty commands
+	 */
+	if (*cmd == '\0') {
+		return (0);
+	}
+
+	/*
 	 * Print the command before echoing if we're not supposed to be quiet
 	 * for this one. We also print the command if -n given, but not if '+'.
 	 */
@@ -3022,7 +3013,8 @@
 		 * therefore do not free it when debugging.
 		 */
 		if (!DEBUG(GRAPH2)) {
-			free(cmdStart);
+			free(Lst_Datum(cmdNode));
+			Lst_Replace(cmdNode, NULL);
 		}
 
 		/*
@@ -3166,8 +3158,7 @@
 			if (!touchFlag) {
 				curTarg = gn;
 				LST_FOREACH(ln, &gn->commands) {
-					if (Compat_RunCommand(Lst_Datum(ln),
-					    gn))
+					if (Compat_RunCommand(ln, gn))
 						break;
 				}
 				curTarg = NULL;
@@ -3345,7 +3336,7 @@
 		gn = Targ_FindNode(".BEGIN", TARG_NOCREATE);
 		if (gn != NULL) {
 			LST_FOREACH(ln, &gn->commands) {
-				if (Compat_RunCommand(Lst_Datum(ln), gn))
+				if (Compat_RunCommand(ln, gn))
 					break;
 			}
 			if (gn->made == ERROR) {
@@ -3386,7 +3377,7 @@
 	 */
 	if (makeErrors == 0) {
 		LST_FOREACH(ln, &ENDNode->commands) {
-			if (Compat_RunCommand(Lst_Datum(ln), ENDNode))
+			if (Compat_RunCommand(ln, ENDNode))
 				break;
 		}
 	}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.bin/procstat/Makefile
--- a/head/usr.bin/procstat/Makefile	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/usr.bin/procstat/Makefile	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-# $FreeBSD: head/usr.bin/procstat/Makefile 227838 2011-11-22 20:59:52Z trociny $
+# $FreeBSD: head/usr.bin/procstat/Makefile 227956 2011-11-24 20:54:06Z trociny $
 
 PROG=	procstat
 MAN=	procstat.1
@@ -10,6 +10,7 @@
 	procstat_cred.c		\
 	procstat_files.c	\
 	procstat_kstack.c	\
+	procstat_rlimit.c	\
 	procstat_sigs.c		\
 	procstat_threads.c	\
 	procstat_vm.c
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.bin/procstat/procstat.1
--- a/head/usr.bin/procstat/procstat.1	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/usr.bin/procstat/procstat.1	Tue Dec 06 20:26:16 2011 +0200
@@ -23,9 +23,9 @@
 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 .\" SUCH DAMAGE.
 .\"
-.\" $FreeBSD: head/usr.bin/procstat/procstat.1 227838 2011-11-22 20:59:52Z trociny $
+.\" $FreeBSD: head/usr.bin/procstat/procstat.1 228090 2011-11-28 19:45:47Z trociny $
 .\"
-.Dd November 22, 2011
+.Dd November 28, 2011
 .Dt PROCSTAT 1
 .Os
 .Sh NAME
@@ -37,7 +37,7 @@
 .Op Fl n
 .Op Fl C
 .Op Fl w Ar interval
-.Op Fl b | c | f | i | j | k | s | t | v
+.Op Fl b | c | e | f | i | j | k | l | s | t | v | x
 .Op Fl a | Ar pid ...
 .Sh DESCRIPTION
 The
@@ -69,6 +69,8 @@
 threads currently running on a CPU and threads with stacks swapped to disk.
 If the flag is repeated, function offsets as well as function names are
 printed.
+.It Fl l
+Display resource limits for the process.
 .It Fl s
 Display security credential information for the process.
 .It Fl t
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.bin/procstat/procstat.c
--- a/head/usr.bin/procstat/procstat.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/usr.bin/procstat/procstat.c	Tue Dec 06 20:26:16 2011 +0200
@@ -23,7 +23,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: head/usr.bin/procstat/procstat.c 227838 2011-11-22 20:59:52Z trociny $
+ * $FreeBSD: head/usr.bin/procstat/procstat.c 227956 2011-11-24 20:54:06Z trociny $
  */
 
 #include <sys/param.h>
@@ -39,8 +39,8 @@
 
 #include "procstat.h"
 
-static int aflag, bflag, cflag, eflag, fflag, iflag, jflag, kflag, sflag, tflag;
-static int vflag, xflag;
+static int aflag, bflag, cflag, eflag, fflag, iflag, jflag, kflag, lflag, sflag;
+static int tflag, vflag, xflag;
 int	hflag, nflag, Cflag;
 
 static void
@@ -50,7 +50,7 @@
 	fprintf(stderr, "usage: procstat [-h] [-C] [-M core] [-N system] "
 	    "[-w interval] \n");
 	fprintf(stderr, "                [-b | -c | -e | -f | -i | -j | -k | "
-	    "-s | -t | -v | -x] [-a | pid ...]\n");
+	    "-l | -s | -t | -v | -x] [-a | pid ...]\n");
 	exit(EX_USAGE);
 }
 
@@ -72,6 +72,8 @@
 		procstat_threads_sigs(prstat, kipp);
 	else if (kflag)
 		procstat_kstack(kipp, kflag);
+	else if (lflag)
+		procstat_rlimit(kipp);
 	else if (sflag)
 		procstat_cred(kipp);
 	else if (tflag)
@@ -123,7 +125,7 @@
 
 	interval = 0;
 	memf = nlistf = NULL;
-	while ((ch = getopt(argc, argv, "CN:M:abcefijkhstvw:x")) != -1) {
+	while ((ch = getopt(argc, argv, "CN:M:abcefijklhstvw:x")) != -1) {
 		switch (ch) {
 		case 'C':
 			Cflag++;
@@ -167,6 +169,10 @@
 			kflag++;
 			break;
 
+		case 'l':
+			lflag++;
+			break;
+
 		case 'n':
 			nflag++;
 			break;
@@ -210,8 +216,8 @@
 	argv += optind;
 
 	/* We require that either 0 or 1 mode flags be set. */
-	tmp = bflag + cflag + eflag + fflag + (kflag ? 1 : 0) + sflag + tflag +
-	    vflag + xflag;
+	tmp = bflag + cflag + eflag + fflag + (kflag ? 1 : 0) + lflag + sflag +
+	    tflag + vflag + xflag;
 	if (!(tmp == 0 || tmp == 1))
 		usage();
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.bin/procstat/procstat.h
--- a/head/usr.bin/procstat/procstat.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/usr.bin/procstat/procstat.h	Tue Dec 06 20:26:16 2011 +0200
@@ -23,7 +23,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: head/usr.bin/procstat/procstat.h 227838 2011-11-22 20:59:52Z trociny $
+ * $FreeBSD: head/usr.bin/procstat/procstat.h 227956 2011-11-24 20:54:06Z trociny $
  */
 
 #ifndef PROCSTAT_H
@@ -42,6 +42,7 @@
 void	procstat_env(struct kinfo_proc *kipp);
 void	procstat_files(struct procstat *prstat, struct kinfo_proc *kipp);
 void	procstat_kstack(struct kinfo_proc *kipp, int kflag);
+void	procstat_rlimit(struct kinfo_proc *kipp);
 void	procstat_sigs(struct procstat *prstat, struct kinfo_proc *kipp);
 void	procstat_threads(struct kinfo_proc *kipp);
 void	procstat_threads_sigs(struct procstat *prstat, struct kinfo_proc *kipp);
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.bin/procstat/procstat_auxv.c
--- a/head/usr.bin/procstat/procstat_auxv.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/usr.bin/procstat/procstat_auxv.c	Tue Dec 06 20:26:16 2011 +0200
@@ -23,13 +23,16 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: head/usr.bin/procstat/procstat_auxv.c 227873 2011-11-23 07:34:09Z trociny $
+ * $FreeBSD: head/usr.bin/procstat/procstat_auxv.c 228289 2011-12-05 19:39:15Z trociny $
  */
 
 #include <sys/param.h>
+#include <sys/elf.h>
 #include <sys/sysctl.h>
 #include <sys/user.h>
 
+#include <vm/vm.h>
+
 #include <err.h>
 #include <errno.h>
 #include <libprocstat.h>
@@ -38,11 +41,15 @@
 #include <stdlib.h>
 #include <string.h>
 
-#include <machine/elf.h>
-
 #include "procstat.h"
 
 static Elf_Auxinfo auxv[256];
+static char prefix[256];
+
+#define	PRINT(name, spec, val)		\
+	printf("%s %-16s " #spec "\n", prefix, #name, (val))
+#define	PRINT_UNKNOWN(type, val)	\
+	printf("%s %16ld %#lx\n", prefix, (long)type, (u_long)(val))
 
 void
 procstat_auxv(struct kinfo_proc *kipp)
@@ -51,7 +58,7 @@
 	size_t len, i;
 
 	if (!hflag)
-		printf("%5s %-16s %-53s\n", "PID", "COMM", "AUXV");
+		printf("%5s %-16s %-16s %-16s\n", "PID", "COMM", "AUXV", "VALUE");
 
 	name[0] = CTL_KERN;
 	name[1] = KERN_PROC;
@@ -59,128 +66,105 @@
 	name[3] = kipp->ki_pid;
 	len = sizeof(auxv) * sizeof(*auxv);
 	error = sysctl(name, 4, auxv, &len, NULL, 0);
-	if (error < 0 && errno != ESRCH) {
+	if (error < 0 && errno != ESRCH && errno != EPERM) {
 		warn("sysctl: kern.proc.auxv: %d: %d", kipp->ki_pid, errno);
 		return;
 	}
-	if (error < 0)
+	if (error < 0 || len == 0)
 		return;
-	printf("%5d ", kipp->ki_pid);
-	printf("%-16s", kipp->ki_comm);
 	if (len == 0) {
 		printf(" -\n");
 		return;
 	}
+	snprintf(prefix, sizeof(prefix), "%5d %-16s", kipp->ki_pid,
+	    kipp->ki_comm);
 	for (i = 0; i < len; i++) {
 		switch(auxv[i].a_type) {
 		case AT_NULL:
-			printf(" (%zu)\n", i + 1);
 			return;
 		case AT_IGNORE:
-			printf(" AT_IGNORE=0x%lu",
-			    (unsigned long)auxv[i].a_un.a_val);
 			break;
 		case AT_EXECFD:
-			printf(" AT_EXECFD=0x%lu",
-			    (unsigned long)auxv[i].a_un.a_val);
+			PRINT(AT_EXECFD, %ld, (long)auxv[i].a_un.a_val);
 			break;
 		case AT_PHDR:
-			printf(" AT_PHDR=0x%lu",
-			    (unsigned long)auxv[i].a_un.a_val);
+			PRINT(AT_PHDR, %p, auxv[i].a_un.a_ptr);
 			break;
 		case AT_PHENT:
-			printf(" AT_PHENT=0x%lu",
-			    (unsigned long)auxv[i].a_un.a_val);
+			PRINT(AT_PHENT, %ld, (long)auxv[i].a_un.a_val);
 			break;
 		case AT_PHNUM:
-			printf(" AT_PHNUM=0x%lu",
-			    (unsigned long)auxv[i].a_un.a_val);
+			PRINT(AT_PHNUM, %ld, (long)auxv[i].a_un.a_val);
 			break;
 		case AT_PAGESZ:
-			printf(" AT_PAGESZ=0x%lu",
-			    (unsigned long)auxv[i].a_un.a_val);
+			PRINT(AT_PAGESZ, %ld, (long)auxv[i].a_un.a_val);
 			break;
 		case AT_BASE:
-			printf(" AT_BASE=0x%lu",
-			    (unsigned long)auxv[i].a_un.a_val);
+			PRINT(AT_BASE, %p, auxv[i].a_un.a_ptr);
 			break;
 		case AT_FLAGS:
-			printf(" AT_FLAGS=0x%lu",
-			    (unsigned long)auxv[i].a_un.a_val);
+			PRINT(AT_FLAGS, %#lx, (u_long)auxv[i].a_un.a_val);
 			break;
 		case AT_ENTRY:
-			printf(" AT_ENTRY=0x%lu",
-			    (unsigned long)auxv[i].a_un.a_val);
+			PRINT(AT_ENTRY, %p, auxv[i].a_un.a_ptr);
 			break;
 #ifdef AT_NOTELF
 		case AT_NOTELF:
-			printf(" AT_NOTELF=0x%lu",
-			    (unsigned long)auxv[i].a_un.a_val);
+			PRINT(AT_NOTELF, %ld, (long)auxv[i].a_un.a_val);
 			break;
 #endif
 #ifdef AT_UID
 		case AT_UID:
-			printf(" AT_UID=0x%lu",
-			    (unsigned long)auxv[i].a_un.a_val);
+			PRINT(AT_UID, %ld, (long)auxv[i].a_un.a_val);
 			break;
 #endif
 #ifdef AT_EUID
 		case AT_EUID:
-			printf(" AT_EUID=0x%lu",
-			    (unsigned long)auxv[i].a_un.a_val);
+			PRINT(AT_EUID, %ld, (long)auxv[i].a_un.a_val);
 			break;
 #endif
 #ifdef AT_GID
 		case AT_GID:
-			printf(" AT_GID=0x%lu",
-			    (unsigned long)auxv[i].a_un.a_val);
+			PRINT(AT_GID, %ld, (long)auxv[i].a_un.a_val);
 			break;
 #endif
 #ifdef AT_EGID
 		case AT_EGID:
-			printf(" AT_EGID=0x%lu",
-			    (unsigned long)auxv[i].a_un.a_val);
+			PRINT(AT_EGID, %ld, (long)auxv[i].a_un.a_val);
 			break;
 #endif
 		case AT_EXECPATH:
-			printf(" AT_EXECPATH=0x%lu",
-			    (unsigned long)auxv[i].a_un.a_val);
+			PRINT(AT_EXECPATH, %p, auxv[i].a_un.a_ptr);
 			break;
 		case AT_CANARY:
-			printf(" AT_CANARY=0x%lu",
-			    (unsigned long)auxv[i].a_un.a_val);
+			PRINT(AT_CANARY, %p, auxv[i].a_un.a_ptr);
 			break;
 		case AT_CANARYLEN:
-			printf(" AT_CANARYLEN=0x%lu",
-			    (unsigned long)auxv[i].a_un.a_val);
+			PRINT(AT_CANARYLEN, %ld, (long)auxv[i].a_un.a_val);
 			break;
 		case AT_OSRELDATE:
-			printf(" AT_OSRELDATE=0x%lu",
-			    (unsigned long)auxv[i].a_un.a_val);
+			PRINT(AT_OSRELDATE, %ld, (long)auxv[i].a_un.a_val);
 			break;
 		case AT_NCPUS:
-			printf(" AT_NCPUS=0x%lu",
-			    (unsigned long)auxv[i].a_un.a_val);
+			PRINT(AT_NCPUS, %ld, (long)auxv[i].a_un.a_val);
 			break;
 		case AT_PAGESIZES:
-			printf(" AT_PAGESIZES=0x%lu",
-			    (unsigned long)auxv[i].a_un.a_val);
+			PRINT(AT_PAGESIZES, %p, auxv[i].a_un.a_ptr);
 			break;
 		case AT_PAGESIZESLEN:
-			printf(" AT_PAGESIZESLEN=0x%lu",
-			    (unsigned long)auxv[i].a_un.a_val);
+			PRINT(AT_PAGESIZESLEN, %ld, (long)auxv[i].a_un.a_val);
 			break;
 		case AT_STACKPROT:
-			printf(" AT_STACKPROT=0x%lu",
-			    (unsigned long)auxv[i].a_un.a_val);
+			if ((auxv[i].a_un.a_val & VM_PROT_EXECUTE) != 0)
+				PRINT(AT_STACKPROT, %s, "NONEXECUTABLE");
+			else
+				PRINT(AT_STACKPROT, %s, "EXECUTABLE");
 			break;
 		case AT_COUNT:
-			printf(" AT_COUNT=0x%lu",
-			    (unsigned long)auxv[i].a_un.a_val);
+			PRINT(AT_COUNT, %ld, (long)auxv[i].a_un.a_val);
 			break;
 		default:
-			printf(" %ld=0x%lu", (long)auxv[i].a_type,
-			    (unsigned long)auxv[i].a_un.a_val);
+			PRINT_UNKNOWN(auxv[i].a_type, auxv[i].a_un.a_val);
 			break;
 		}
 	}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.bin/procstat/procstat_rlimit.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/head/usr.bin/procstat/procstat_rlimit.c	Tue Dec 06 20:26:16 2011 +0200
@@ -0,0 +1,78 @@
+/*-
+ * Copyright (c) 2011 Mikolaj Golub
+ * 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: head/usr.bin/procstat/procstat_rlimit.c 227956 2011-11-24 20:54:06Z trociny $
+ */
+
+#include <sys/param.h>
+#include <sys/time.h>
+#define _RLIMIT_IDENT
+#include <sys/resourcevar.h>
+#include <sys/sysctl.h>
+#include <sys/user.h>
+
+#include <err.h>
+#include <errno.h>
+#include <libprocstat.h>
+#include <limits.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "procstat.h"
+
+static struct rlimit rlimit[RLIM_NLIMITS];
+
+void
+procstat_rlimit(struct kinfo_proc *kipp)
+{
+	int error, i, name[4];
+	size_t len;
+
+	if (!hflag)
+		printf("%5s %-16s %-10s %12s %12s\n", "PID", "COMM", "RLIMIT",
+		    "CURRENT", "MAX");
+	name[0] = CTL_KERN;
+	name[1] = KERN_PROC;
+	name[2] = KERN_PROC_RLIMIT;
+	name[3] = kipp->ki_pid;
+	len = sizeof(rlimit);
+	error = sysctl(name, 4, rlimit, &len, NULL, 0);
+	if (error < 0 && errno != ESRCH) {
+		warn("sysctl: kern.proc.rlimit: %d", kipp->ki_pid);
+		return;
+	}
+	if (error < 0 || len != sizeof(rlimit))
+		return;
+
+	for (i = 0; i < RLIM_NLIMITS; i++) {
+		printf("%5d %-16s %-10s %12jd %12jd\n", kipp->ki_pid,
+		    kipp->ki_comm, rlimit_ident[i],
+		    rlimit[i].rlim_cur == RLIM_INFINITY ?
+		    -1 : rlimit[i].rlim_cur,
+		    rlimit[i].rlim_max == RLIM_INFINITY ?
+		    -1 : rlimit[i].rlim_max);
+        }
+}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.bin/truss/setup.c
--- a/head/usr.bin/truss/setup.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/usr.bin/truss/setup.c	Tue Dec 06 20:26:16 2011 +0200
@@ -30,7 +30,7 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD$");
+__FBSDID("$FreeBSD: head/usr.bin/truss/setup.c 228261 2011-12-04 18:43:09Z kib $");
 
 /*
  * Various setup functions for truss.  Not the cleanest-written code,
@@ -202,9 +202,19 @@
 		find_thread(info, lwpinfo.pl_lwpid);
 		switch(WSTOPSIG(waitval)) {
 		case SIGTRAP:
-			info->pr_why = info->curthread->in_syscall?S_SCX:S_SCE;
-			info->curthread->in_syscall = 1 - info->curthread->in_syscall;
-			break;
+			if (lwpinfo.pl_flags & PL_FLAG_SCE) {
+				info->pr_why = S_SCE;
+				info->curthread->in_syscall = 1;
+				break;
+			} else if (lwpinfo.pl_flags & PL_FLAG_SCX) {
+				info->pr_why = S_SCX;
+				info->curthread->in_syscall = 0;
+				break;
+			} else {
+				errx(1,
+		   "pl_flags %x contains neither PL_FLAG_SCE nor PL_FLAG_SCX",
+				    lwpinfo.pl_flags);
+			}
 		default:
 			info->pr_why = S_SIG;
 			info->pr_data = WSTOPSIG(waitval);
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.sbin/acpi/Makefile.inc
--- a/head/usr.sbin/acpi/Makefile.inc	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/usr.sbin/acpi/Makefile.inc	Tue Dec 06 20:26:16 2011 +0200
@@ -1,5 +1,5 @@
 # $Id: Makefile.inc,v 1.1 2000/07/14 18:16:22 iwasaki Exp $
-# $FreeBSD$
+# $FreeBSD: head/usr.sbin/acpi/Makefile.inc 228110 2011-11-28 23:36:48Z jkim $
 
 ACPICA_DIR= ${.CURDIR}/../../../sys/contrib/dev/acpica
 CFLAGS+= -I${.CURDIR}/../../../sys
@@ -8,17 +8,18 @@
 .include "${.CURDIR}/../../Makefile.inc"
 .endif
 
-.PATH:	${ACPICA_DIR}			\
-	${ACPICA_DIR}/common		\
-	${ACPICA_DIR}/compiler		\
-	${ACPICA_DIR}/debugger		\
-	${ACPICA_DIR}/disassembler	\
-	${ACPICA_DIR}/dispatcher	\
-	${ACPICA_DIR}/events		\
-	${ACPICA_DIR}/executer		\
-	${ACPICA_DIR}/hardware		\
-	${ACPICA_DIR}/namespace		\
-	${ACPICA_DIR}/parser		\
-	${ACPICA_DIR}/resources		\
-	${ACPICA_DIR}/tables		\
+.PATH:	${ACPICA_DIR}					\
+	${ACPICA_DIR}/common				\
+	${ACPICA_DIR}/compiler				\
+	${ACPICA_DIR}/debugger				\
+	${ACPICA_DIR}/disassembler			\
+	${ACPICA_DIR}/dispatcher			\
+	${ACPICA_DIR}/events				\
+	${ACPICA_DIR}/executer				\
+	${ACPICA_DIR}/hardware				\
+	${ACPICA_DIR}/namespace				\
+	${ACPICA_DIR}/os_specific/service_layers	\
+	${ACPICA_DIR}/parser				\
+	${ACPICA_DIR}/resources				\
+	${ACPICA_DIR}/tables				\
 	${ACPICA_DIR}/utilities
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.sbin/acpi/acpidb/Makefile
--- a/head/usr.sbin/acpi/acpidb/Makefile	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/usr.sbin/acpi/acpidb/Makefile	Tue Dec 06 20:26:16 2011 +0200
@@ -1,8 +1,7 @@
-# $FreeBSD: head/usr.sbin/acpi/acpidb/Makefile 220663 2011-04-15 18:34:27Z jkim $
+# $FreeBSD: head/usr.sbin/acpi/acpidb/Makefile 228110 2011-11-28 23:36:48Z jkim $
 
 PROG=	acpidb
 SRCS=	acpidb.c
-SRCS+=	osunixxf.c
 
 # debugger
 SRCS+=	dbcmds.c dbdisply.c dbexec.c dbfileio.c dbhistry.c	\
@@ -11,7 +10,7 @@
 
 # disassembler
 SRCS+=	dmbuffer.c dmnames.c dmobject.c dmopcode.c dmresrc.c	\
-	dmresrcl.c dmresrcs.c dmutils.c dmwalk.c
+	dmresrcl.c dmresrcl2.c dmresrcs.c dmutils.c dmwalk.c
 
 # events
 SRCS+=	evevent.c evglock.c evgpe.c evgpeblk.c evgpeinit.c	\
@@ -44,10 +43,13 @@
 	nsrepair.c nsrepair2.c nssearch.c nsutils.c nswalk.c	\
 	nsxfeval.c nsxfname.c nsxfobj.c
 
+# os_specific/service_layers
+SRCS+=	osunixxf.c
+
 # resources
 SRCS+=	rsaddr.c rscalc.c rscreate.c rsdump.c rsinfo.c		\
 	rsio.c rsirq.c rslist.c rsmemory.c rsmisc.c		\
-	rsutils.c rsxface.c
+	rsserial.c rsutils.c rsxface.c
 
 # tables
 SRCS+=	tbfadt.c tbfind.c tbinstal.c tbutils.c tbxface.c	\
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.sbin/acpi/acpidb/acpidb.c
--- a/head/usr.sbin/acpi/acpidb/acpidb.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/usr.sbin/acpi/acpidb/acpidb.c	Tue Dec 06 20:26:16 2011 +0200
@@ -23,7 +23,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- *	$FreeBSD: head/usr.sbin/acpi/acpidb/acpidb.c 227876 2011-11-23 10:27:18Z kevlo $
+ *	$FreeBSD: head/usr.sbin/acpi/acpidb/acpidb.c 228110 2011-11-28 23:36:48Z jkim $
  */
 
 #include <sys/param.h>
@@ -43,7 +43,8 @@
 #include <unistd.h>
 
 #include <contrib/dev/acpica/include/acpi.h>
-#include <contrib/dev/acpica/tools/acpiexec/aecommon.h>
+#include <contrib/dev/acpica/include/accommon.h>
+#include <contrib/dev/acpica/include/acdebug.h>
 
 /*
  * Dummy DSDT Table Header
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.sbin/acpi/iasl/Makefile
--- a/head/usr.sbin/acpi/iasl/Makefile	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/usr.sbin/acpi/iasl/Makefile	Tue Dec 06 20:26:16 2011 +0200
@@ -1,8 +1,7 @@
-# $FreeBSD: head/usr.sbin/acpi/iasl/Makefile 220682 2011-04-15 21:47:10Z jkim $
+# $FreeBSD: head/usr.sbin/acpi/iasl/Makefile 228110 2011-11-28 23:36:48Z jkim $
 
 PROG=	iasl
 SRCS=	adfile.c adisasm.c adwalk.c
-SRCS+=	osunixxf.c
 
 # common
 SRCS+=	dmextern.c dmrestag.c dmtable.c dmtbdump.c dmtbinfo.c	\
@@ -16,18 +15,19 @@
 	aslopcodes.c asloperands.c aslopt.c aslpredef.c		\
 	aslresource.c aslrestype1.c aslrestype1i.c		\
 	aslrestype2.c aslrestype2d.c aslrestype2e.c		\
-	aslrestype2q.c aslrestype2w.c aslstartup.c aslstubs.c	\
-	asltransform.c asltree.c aslutils.c asluuid.c		\
-	aslwalks.c dtcompile.c dtexpress.c dtfield.c dtio.c	\
-	dtparser.y.h dtparserlex.c dtparserparse.c dtsubtable.c	\
-	dttable.c dttemplate.c dtutils.c
+	aslrestype2q.c aslrestype2s.c aslrestype2w.c		\
+	aslstartup.c aslstubs.c	asltransform.c asltree.c	\
+	aslutils.c asluuid.c aslwalks.c dtcompile.c dtexpress.c	\
+	dtfield.c dtio.c dtparser.y.h dtparserlex.c		\
+	dtparserparse.c dtsubtable.c dttable.c dttemplate.c	\
+	dtutils.c
 
 # debugger
 SRCS+=	dbfileio.c
 
 # disassembler
 SRCS+=	dmbuffer.c dmnames.c dmobject.c dmopcode.c dmresrc.c	\
-	dmresrcl.c dmresrcs.c dmutils.c dmwalk.c
+	dmresrcl.c dmresrcl2.c dmresrcs.c dmutils.c dmwalk.c
 
 # interpreter/dispatcher
 SRCS+=	dsargs.c dscontrol.c dsfield.c dsobject.c dsopcode.c	\
@@ -48,6 +48,9 @@
 SRCS+=	nsaccess.c nsalloc.c nsdump.c nsnames.c nsobject.c	\
 	nsparse.c nssearch.c nsutils.c nswalk.c nsxfobj.c
 
+# os_specific/service_layers
+SRCS+=	osunixxf.c
+
 # tables
 SRCS+=	tbfadt.c tbinstal.c tbutils.c tbxface.c
 
@@ -64,8 +67,6 @@
 CFLAGS+= -DACPI_ASL_COMPILER -I.
 LFLAGS= -i -s
 YFLAGS= -d
-DPADD=	${LIBPTHREAD}
-LDADD=	-lpthread
 
 CLEANFILES= aslcompiler.y.h aslcompilerlex.c aslcompilerparse.c	\
 	aslcompilerparse.h dtparser.y.h dtparserlex.c		\
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.sbin/bsdinstall/distextract/distextract.c
--- a/head/usr.sbin/bsdinstall/distextract/distextract.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/usr.sbin/bsdinstall/distextract/distextract.c	Tue Dec 06 20:26:16 2011 +0200
@@ -23,7 +23,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD$
+ * $FreeBSD: head/usr.sbin/bsdinstall/distextract/distextract.c 228048 2011-11-28 05:34:16Z kevlo $
  */
 
 #include <sys/param.h>
@@ -49,6 +49,7 @@
 	dists = calloc(ndists, sizeof(const char *));
 	if (dists == NULL) {
 		fprintf(stderr, "Out of memory!\n");
+		free(diststring);
 		return (1);
 	}
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.sbin/bsdinstall/distfetch/distfetch.c
--- a/head/usr.sbin/bsdinstall/distfetch/distfetch.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/usr.sbin/bsdinstall/distfetch/distfetch.c	Tue Dec 06 20:26:16 2011 +0200
@@ -23,7 +23,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD$
+ * $FreeBSD: head/usr.sbin/bsdinstall/distfetch/distfetch.c 228048 2011-11-28 05:34:16Z kevlo $
  */
 
 #include <sys/param.h>
@@ -48,6 +48,7 @@
 	urls = calloc(ndists, sizeof(const char *));
 	if (urls == NULL) {
 		fprintf(stderr, "Out of memory!\n");
+		free(diststring);
 		return (1);
 	}
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.sbin/bsdinstall/partedit/gpart_ops.c
--- a/head/usr.sbin/bsdinstall/partedit/gpart_ops.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/usr.sbin/bsdinstall/partedit/gpart_ops.c	Tue Dec 06 20:26:16 2011 +0200
@@ -23,7 +23,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: head/usr.sbin/bsdinstall/partedit/gpart_ops.c 226666 2011-10-23 16:57:10Z nwhitehorn $
+ * $FreeBSD: head/usr.sbin/bsdinstall/partedit/gpart_ops.c 228048 2011-11-28 05:34:16Z kevlo $
  */
 
 #include <sys/param.h>
@@ -301,7 +301,7 @@
 		return;
 
 	bootfd = open(bootcode, O_RDONLY);
-	if (bootfd <= 0) {
+	if (bootfd < 0) {
 		dialog_msgbox("Bootcode Error", strerror(errno), 0, 0,
 		    TRUE);
 		return;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.sbin/bsdinstall/scripts/auto
--- a/head/usr.sbin/bsdinstall/scripts/auto	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/usr.sbin/bsdinstall/scripts/auto	Tue Dec 06 20:26:16 2011 +0200
@@ -24,7 +24,7 @@
 # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 # SUCH DAMAGE.
 #
-# $FreeBSD: head/usr.sbin/bsdinstall/scripts/auto 226507 2011-10-18 11:29:10Z kensmith $
+# $FreeBSD: head/usr.sbin/bsdinstall/scripts/auto 228194 2011-12-02 02:05:26Z nwhitehorn $
 
 echo "Begun Installation at $(date)" > $BSDINSTALL_LOG
 
@@ -157,7 +157,7 @@
 	exec 3>&1
 	REVISIT=$(dialog --backtitle "FreeBSD Installer" \
 	    --title "Final Configuration" --no-cancel --menu \
-	    "Setup of your FreeBSD system is nearly complete. You can now modify your configuration choices or apply more complex changes using a shell." 0 0 0 \
+	    "Setup of your FreeBSD system is nearly complete. You can now modify your configuration choices. After this screen, you will have an opportunity to make more complex changes using a shell." 0 0 0 \
 		"Exit" "Apply configuration and exit installer" \
 		"Add User" "Add a user to the system" \
 		"Root Password" "Change root password" \
@@ -165,8 +165,7 @@
 		"Network" "Networking configuration" \
 		"Services" "Set daemons to run on startup" \
 		"Time Zone" "Set system timezone" \
-		"Handbook" "Install FreeBSD Handbook (requires network)" \
-		"Shell" "Open a shell in the new system" 2>&1 1>&3)
+		"Handbook" "Install FreeBSD Handbook (requires network)" 2>&1 1>&3)
 	exec 3>&-
 
 	case "$REVISIT" in
@@ -198,15 +197,6 @@
 		bsdinstall docsinstall
 		finalconfig
 		;;
-	"Shell")
-		clear
-		echo This shell is operating in a chroot in the new system. \
-		    When finished making configuration changes, type \"exit\".
-		chroot "$BSDINSTALL_CHROOT" /bin/sh 2>&1
-		# Don't hose local rc.conf changes
-		cp $BSDINSTALL_CHROOT/etc/rc.conf $BSDINSTALL_TMPETC/rc.conf.manual
-		finalconfig
-		;;
 	esac
 }
 
@@ -222,5 +212,14 @@
 	rm -rf "$BSDINSTALL_FETCHDEST"
 fi
 
+dialog --backtitle "FreeBSD Installer" --title "Manual Configuration" \
+    --yesno "The installation is now finished. Before exiting the installer, would you like to open a shell in the new system to make any final manual modifications?" 0 0
+if [ $? -eq 0 ]; then
+	clear
+	echo This shell is operating in a chroot in the new system. \
+	    When finished making configuration changes, type \"exit\".
+	chroot "$BSDINSTALL_CHROOT" /bin/sh 2>&1
+fi
+
 echo "Installation Completed at $(date)" >> $BSDINSTALL_LOG
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.sbin/bsdinstall/scripts/services
--- a/head/usr.sbin/bsdinstall/scripts/services	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/usr.sbin/bsdinstall/scripts/services	Tue Dec 06 20:26:16 2011 +0200
@@ -24,7 +24,9 @@
 # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 # SUCH DAMAGE.
 #
-# $FreeBSD$
+# $FreeBSD: head/usr.sbin/bsdinstall/scripts/services 228192 2011-12-02 00:38:47Z kensmith $
+
+: ${DIALOG_OK=0}
 
 if [ -f $BSDINSTALL_TMPETC/rc.conf.services ]; then
 	eval `sed -e s/YES/on/I -e s/NO/off/I $BSDINSTALL_TMPETC/rc.conf.services`
@@ -51,3 +53,15 @@
 	echo ${daemon}_enable=\"YES\" >> $BSDINSTALL_TMPETC/rc.conf.services
 done
 
+echo \# Set dumpdev to \"AUTO\" to enable crash dumps, \"NO\" to disable >> \
+	$BSDINSTALL_TMPETC/rc.conf.services
+
+dialog --backtitle "FreeBSD Installer" --title "Dumpdev Configuration" \
+	--nocancel --yesno \
+	"Would you like to enable crash dumps?  If you start having problems with the system it can help the FreeBSD developers debug the problem.  But the crash dumps can take up a lot of disk space in /var." 0 0
+
+if [ $? -eq $DIALOG_OK ]; then
+	echo dumpdev=\"AUTO\" >> $BSDINSTALL_TMPETC/rc.conf.services
+else
+	echo dumpdev=\"NO\" >> $BSDINSTALL_TMPETC/rc.conf.services
+fi
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.sbin/config/mkmakefile.c
--- a/head/usr.sbin/config/mkmakefile.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/usr.sbin/config/mkmakefile.c	Tue Dec 06 20:26:16 2011 +0200
@@ -32,7 +32,7 @@
 static char sccsid[] = "@(#)mkmakefile.c	8.1 (Berkeley) 6/6/93";
 #endif
 static const char rcsid[] =
-  "$FreeBSD: head/usr.sbin/config/mkmakefile.c 227429 2011-11-10 21:07:14Z rstone $";
+  "$FreeBSD: head/usr.sbin/config/mkmakefile.c 228153 2011-11-30 13:33:09Z fjoe $";
 #endif /* not lint */
 
 /*
@@ -775,7 +775,7 @@
 			fprintf(f, "\t%s\n", compilewith);
 
 		if (!(ftp->f_flags & NO_OBJ))
-			fprintf(f, "\t@${NORMAL_CTFCONVERT}\n\n");
+			fprintf(f, "\t${NORMAL_CTFCONVERT}\n\n");
 		else
 			fprintf(f, "\n");
 	}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.sbin/cron/crontab/crontab.5
--- a/head/usr.sbin/cron/crontab/crontab.5	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/usr.sbin/cron/crontab/crontab.5	Tue Dec 06 20:26:16 2011 +0200
@@ -15,7 +15,7 @@
 .\" * Paul Vixie          <paul at vix.com>          uunet!decwrl!vixie!paul
 .\" */
 .\"
-.\" $FreeBSD$
+.\" $FreeBSD: head/usr.sbin/cron/crontab/crontab.5 227981 2011-11-25 17:41:12Z wblock $
 .\"
 .Dd July 31, 2005
 .Dt CRONTAB 5
@@ -224,7 +224,7 @@
 .Bd -literal -offset indent
 string		meaning
 ------		-------
- at reboot		Run once, at startup.
+ at reboot		Run once, at startup of cron.
 @yearly		Run once a year, "0 0 1 1 *".
 @annually	(same as @yearly)
 @monthly	Run once a month, "0 0 1 * *".
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.sbin/makefs/Makefile
--- a/head/usr.sbin/makefs/Makefile	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/usr.sbin/makefs/Makefile	Tue Dec 06 20:26:16 2011 +0200
@@ -3,6 +3,7 @@
 PROG=	makefs
 
 CFLAGS+=-I${.CURDIR} -g
+LDLAGS+=-g
 
 SRCS=	cd9660.c ffs.c \
 	getid.c \
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.sbin/mergemaster/mergemaster.sh
--- a/head/usr.sbin/mergemaster/mergemaster.sh	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/usr.sbin/mergemaster/mergemaster.sh	Tue Dec 06 20:26:16 2011 +0200
@@ -8,7 +8,7 @@
 # Copyright 1998-2011 Douglas Barton
 # dougb at FreeBSD.org
 
-# $FreeBSD: head/usr.sbin/mergemaster/mergemaster.sh 227013 2011-11-02 07:40:23Z dougb $
+# $FreeBSD: head/usr.sbin/mergemaster/mergemaster.sh 228122 2011-11-29 08:22:12Z dougb $
 
 PATH=/bin:/usr/bin:/usr/sbin
 
@@ -1336,14 +1336,14 @@
 
 if [ -e "${DESTDIR}/etc/localtime" ]; then	# Ignore if TZ == UTC
   echo ''
+  [ -n "${DESTDIR}" ] && tzs_args="-C ${DESTDIR}"
   if [ -f "${DESTDIR}/var/db/zoneinfo" ]; then
     echo "*** Reinstalling `cat ${DESTDIR}/var/db/zoneinfo` as ${DESTDIR}/etc/localtime"
-    [ -n "${DESTDIR}" ] && tzs_args="-C ${DESTDIR}"
     tzsetup $tzs_args -r
   else
     echo "*** There is no ${DESTDIR}/var/db/zoneinfo file to update ${DESTDIR}/etc/localtime."
     echo '    You should run tzsetup'
-    run_it_now tzsetup
+    run_it_now "tzsetup $tzs_args"
   fi
 fi
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.sbin/mfiutil/mfi_config.c
--- a/head/usr.sbin/mfiutil/mfi_config.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/usr.sbin/mfiutil/mfi_config.c	Tue Dec 06 20:26:16 2011 +0200
@@ -26,7 +26,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: head/usr.sbin/mfiutil/mfi_config.c 227893 2011-11-23 17:02:27Z emaste $
+ * $FreeBSD: head/usr.sbin/mfiutil/mfi_config.c 228119 2011-11-29 08:16:14Z delphij $
  */
 
 #include <sys/param.h>
@@ -820,9 +820,11 @@
 	free(config);
 	free(state.volumes);
 	free(state.arrays);
-	for (i = 0; i < narrays; i++)
-		free(arrays[i].drives);
-	free(arrays);
+	if (arrays != NULL) {
+		for (i = 0; i < narrays; i++)
+			free(arrays[i].drives);
+		free(arrays);
+	}
 	close(fd);
 
 	return (error);
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.sbin/mfiutil/mfi_evt.c
--- a/head/usr.sbin/mfiutil/mfi_evt.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/usr.sbin/mfiutil/mfi_evt.c	Tue Dec 06 20:26:16 2011 +0200
@@ -26,7 +26,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: head/usr.sbin/mfiutil/mfi_evt.c 222899 2011-06-09 19:52:28Z bz $
+ * $FreeBSD: head/usr.sbin/mfiutil/mfi_evt.c 228278 2011-12-05 15:11:35Z jhb $
  */
 
 #include <sys/types.h>
@@ -438,7 +438,7 @@
 		printf(": ");
 		break;
 	case MR_EVT_ARGS_LD_STRIP:
-		printf("VOL %s", volume_name(fd, &detail->args.ld_prog.ld));
+		printf("VOL %s", volume_name(fd, &detail->args.ld_strip.ld));
 		if (verbose) {
 			printf(" strip %lld",
 			    (long long)detail->args.ld_strip.strip);
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.sbin/sade/Makefile
--- a/head/usr.sbin/sade/Makefile	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/usr.sbin/sade/Makefile	Tue Dec 06 20:26:16 2011 +0200
@@ -1,4 +1,4 @@
-# $FreeBSD$
+# $FreeBSD: head/usr.sbin/sade/Makefile 227962 2011-11-25 07:10:59Z fjoe $
 
 .if ${MACHINE_CPUARCH} != "ia64"
 _wizard=	wizard.c
@@ -6,8 +6,8 @@
 
 PROG=	sade
 MAN=	sade.8
-SRCS=	command.c config.c devices.c \
-	disks.c dispatch.c dmenu.c \
+SRCS=	command.c devices.c \
+	disks.c dmenu.c \
 	globals.c install.c \
 	label.c main.c menus.c misc.c \
 	msg.c system.c termcap.c \
@@ -19,9 +19,9 @@
 .if ${MACHINE} == "pc98"
 CFLAGS+= -DPC98
 .endif
-CFLAGS+= -I${.CURDIR}/../../gnu/lib/libodialog -I.
+CFLAGS+= -I${.CURDIR}/../../contrib/dialog -I.
 
-DPADD=	${LIBODIALOG} ${LIBNCURSES} ${LIBUTIL} ${LIBDISK}
-LDADD=	-lodialog -lncurses -lutil -ldisk
+DPADD=	${LIBDIALOG} ${LIBNCURSESW} ${LIBM} ${LIBUTIL} ${LIBDISK}
+LDADD=	-ldialog -lncursesw -lm -lutil -ldisk
 
 .include <bsd.prog.mk>
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.sbin/sade/config.c
--- a/head/usr.sbin/sade/config.c	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,333 +0,0 @@
-/*
- * $FreeBSD$
- *
- * Copyright (c) 1995
- *	Jordan Hubbard.  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,
- *    verbatim and that no modifications are made prior to this
- *    point in the file.
- * 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 JORDAN HUBBARD ``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 JORDAN HUBBARD OR HIS PETS 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, LIFE 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 "sade.h"
-#include <sys/disklabel.h>
-#include <sys/wait.h>
-#include <sys/errno.h>
-#include <sys/ioctl.h>
-#include <sys/fcntl.h>
-#include <sys/param.h>
-#include <sys/stat.h>
-#include <unistd.h>
-#include <sys/mount.h>
-#include <libdisk.h>
-#include <time.h>
-#include <kenv.h>
-
-static Chunk *chunk_list[MAX_CHUNKS];
-static int nchunks;
-static int rootdev_is_od;
-
-/* arg to sort */
-static int
-chunk_compare(Chunk *c1, Chunk *c2)
-{
-    if (!c1 && !c2)
-	return 0;
-    else if (!c1 && c2)
-	return 1;
-    else if (c1 && !c2)
-	return -1;
-    else if (!c1->private_data && !c2->private_data)
-	return 0;
-    else if (c1->private_data && !c2->private_data)
-	return 1;
-    else if (!c1->private_data && c2->private_data)
-	return -1;
-    else
-	return strcmp(((PartInfo *)(c1->private_data))->mountpoint, ((PartInfo *)(c2->private_data))->mountpoint);
-}
-
-static void
-chunk_sort(void)
-{
-    int i, j;
-
-    for (i = 0; i < nchunks; i++) {
-	for (j = 0; j < nchunks; j++) {
-	    if (chunk_compare(chunk_list[j], chunk_list[j + 1]) > 0) {
-		Chunk *tmp = chunk_list[j];
-
-		chunk_list[j] = chunk_list[j + 1];
-		chunk_list[j + 1] = tmp;
-	    }
-	}
-    }
-}
-
-static void
-check_rootdev(Chunk **list, int n)
-{
-	int i;
-	Chunk *c;
-
-	rootdev_is_od = 0;
-	for (i = 0; i < n; i++) {
-		c = *list++;
-		if (c->type == part && (c->flags & CHUNK_IS_ROOT)
-		    && strncmp(c->disk->name, "od", 2) == 0)
-			rootdev_is_od = 1;
-	}
-}
-
-static char *
-name_of(Chunk *c1)
-{
-    return c1->name;
-}
-
-static char *
-mount_point(Chunk *c1)
-{
-    if (c1->type == part && c1->subtype == FS_SWAP)
-	return "none";
-    else if (c1->type == part || c1->type == fat || c1->type == efi)
-	return ((PartInfo *)c1->private_data)->mountpoint;
-    return "/bogus";
-}
-
-static char *
-fstype(Chunk *c1)
-{
-    if (c1->type == fat || c1->type == efi)
-	return "msdosfs";
-    else if (c1->type == part) {
-	if (c1->subtype != FS_SWAP)
-	    return "ufs";
-	else
-	    return "swap";
-    }
-    return "bogus";
-}
-
-static char *
-fstype_short(Chunk *c1)
-{
-    if (c1->type == part) {
-	if (c1->subtype != FS_SWAP) {
-	    if (rootdev_is_od == 0 && strncmp(c1->name, "od", 2) == 0)
-		return "rw,noauto";
-	    else
-		return "rw";
-	}
-	else
-	    return "sw";
-    }
-    else if (c1->type == fat) {
-	if (strncmp(c1->name, "od", 2) == 0)
-	    return "ro,noauto";
-	else
-	    return "ro";
-    }
-    else if (c1->type == efi)
-	return "rw";
-
-    return "bog";
-}
-
-static int
-seq_num(Chunk *c1)
-{
-    if (c1->type == part && c1->subtype != FS_SWAP) {
-	if (rootdev_is_od == 0 && strncmp(c1->name, "od", 2) == 0)
-	    return 0;
-	else if (c1->flags & CHUNK_IS_ROOT)
-	    return 1;
-	else
-	    return 2;
-    }
-    return 0;
-}
-
-int
-configFstab(dialogMenuItem *self)
-{
-    Device **devs;
-    Disk *disk;
-    FILE *fstab;
-    int i;
-    Chunk *c1, *c2;
-
-	if (file_readable("/etc/fstab"))
-	    return DITEM_SUCCESS;
-	else {
-	    msgConfirm("Attempting to rebuild your /etc/fstab file.  Warning: If you had\n"
-		       "any CD devices in use before running %s then they may NOT\n"
-		       "be found by this run!", ProgName);
-	}
-
-    devs = deviceFind(NULL, DEVICE_TYPE_DISK);
-    if (!devs) {
-	msgConfirm("No disks found!");
-	return DITEM_FAILURE;
-    }
-
-    /* Record all the chunks */
-    nchunks = 0;
-    for (i = 0; devs[i]; i++) {
-	if (!devs[i]->enabled)
-	    continue;
-	disk = (Disk *)devs[i]->private;
-	if (!disk->chunks)
-	    msgFatal("No chunk list found for %s!", disk->name);
-	for (c1 = disk->chunks->part; c1; c1 = c1->next) {
-#ifdef __powerpc__
-	    if (c1->type == apple) {
-#else
-	    if (c1->type == freebsd) {
-#endif
-		for (c2 = c1->part; c2; c2 = c2->next) {
-		    if (c2->type == part && (c2->subtype == FS_SWAP || c2->private_data))
-			chunk_list[nchunks++] = c2;
-		}
-	    }
-	    else if (((c1->type == fat || c1->type == efi || c1->type == part) &&
-		    c1->private_data) || (c1->type == part && c1->subtype == FS_SWAP))
-		chunk_list[nchunks++] = c1;
-	}
-    }
-    chunk_list[nchunks] = 0;
-    chunk_sort();
-    
-    fstab = fopen("/etc/fstab", "w");
-    if (!fstab) {
-	msgConfirm("Unable to create a new /etc/fstab file!  Manual intervention\n"
-		   "will be required.");
-	return DITEM_FAILURE;
-    }
-    
-    check_rootdev(chunk_list, nchunks);
-    
-    /* Go for the burn */
-    msgDebug("Generating /etc/fstab file\n");
-    fprintf(fstab, "# Device\t\tMountpoint\tFStype\tOptions\t\tDump\tPass#\n");
-    for (i = 0; i < nchunks; i++)
-	fprintf(fstab, "/dev/%s\t\t%s\t\t%s\t%s\t\t%d\t%d\n", name_of(chunk_list[i]), mount_point(chunk_list[i]),
-		fstype(chunk_list[i]), fstype_short(chunk_list[i]), seq_num(chunk_list[i]), seq_num(chunk_list[i]));
-    
-    
-    fclose(fstab);
-    if (isDebug())
-	msgDebug("Wrote out /etc/fstab file\n");
-    return DITEM_SUCCESS;
-}
-
-#if 0
-/* Do the work of sucking in a config file.
- * config is the filename to read in.
- * lines is a fixed (max) sized array of char*
- * returns number of lines read.  line contents
- * are malloc'd and must be freed by the caller.
- */
-static int
-readConfig(char *config, char **lines, int max)
-{
-    FILE *fp;
-    char line[256];
-    int i, nlines;
-
-    fp = fopen(config, "r");
-    if (!fp)
-	return -1;
-
-    nlines = 0;
-    /* Read in the entire file */
-    for (i = 0; i < max; i++) {
-	if (!fgets(line, sizeof line, fp))
-	    break;
-	lines[nlines++] = strdup(line);
-    }
-    fclose(fp);
-    if (isDebug())
-	msgDebug("readConfig: Read %d lines from %s.\n", nlines, config);
-    return nlines;
-}
-#endif
-
-#define MAX_LINES  2000 /* Some big number we're not likely to ever reach - I'm being really lazy here, I know */
-
-#if 0
-static void
-readConfigFile(char *config, int marked)
-{
-    char *lines[MAX_LINES], *cp, *cp2;
-    int i, nlines;
-
-    nlines = readConfig(config, lines, MAX_LINES);
-    if (nlines == -1)
-	return;
-
-    for (i = 0; i < nlines; i++) {
-	/* Skip the comments & non-variable settings */
-	if (lines[i][0] == '#' || !(cp = index(lines[i], '='))) {
-	    free(lines[i]);
-	    continue;
-	}
-	*cp++ = '\0';
-	/* Find quotes */
-	if ((cp2 = index(cp, '"')) || (cp2 = index(cp, '\047'))) {
-	    cp = cp2 + 1;
-	    cp2 = index(cp, *cp2);
-	}
-	/* If valid quotes, use it */
-	if (cp2) {
-	    *cp2 = '\0';
-	    /* If we have a legit value, set it */
-	    if (strlen(cp))
-		variable_set2(lines[i], cp, marked);
-	}
-	free(lines[i]);
-    }
-}
-
-/* Load the environment from rc.conf file(s) */
-void
-configEnvironmentRC_conf(void)
-{
-    static struct {
-	char *fname;
-	int marked;
-    } configs[] = {
-	{ "/etc/defaults/rc.conf", 0 },
-	{ "/etc/rc.conf", 0 },
-	{ "/etc/rc.conf.local", 0 },
-	{ NULL, 0 },
-    };
-    int i;
-
-    for (i = 0; configs[i].fname; i++) {
-	if (file_readable(configs[i].fname))
-	    readConfigFile(configs[i].fname, configs[i].marked);
-    }
-}
-#endif
-
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.sbin/sade/devices.c
--- a/head/usr.sbin/sade/devices.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/usr.sbin/sade/devices.c	Tue Dec 06 20:26:16 2011 +0200
@@ -1,5 +1,5 @@
 /*
- * $FreeBSD$
+ * $FreeBSD: head/usr.sbin/sade/devices.c 227944 2011-11-24 18:37:16Z fjoe $
  *
  * Copyright (c) 1995
  *	Jordan Hubbard.  All rights reserved.
@@ -29,7 +29,6 @@
  *
  */
 
-#include "sade.h"
 #include <sys/fcntl.h>
 #include <sys/param.h>
 #include <sys/socket.h>
@@ -40,6 +39,8 @@
 #include <ctype.h>
 #include <libdisk.h>
 
+#include "sade.h"
+
 /* how much to bias minor number for a given /dev/<ct#><un#>s<s#> slice */
 #define SLICE_DELTA	(0x10000)
 
@@ -122,7 +123,7 @@
 
 /* Register a new device in the devices array */
 Device *
-deviceRegister(char *name, char *desc, char *devname, DeviceType type, Boolean enabled,
+deviceRegister(char *name, char *desc, char *devname, DeviceType type,
 	       Boolean (*init)(Device *), FILE * (*get)(Device *, char *, Boolean),
 	       void (*shutdown)(Device *), void *private)
 {
@@ -135,7 +136,6 @@
 	newdev->description = desc;
 	newdev->devname = devname;
 	newdev->type = type;
-	newdev->enabled = enabled;
 	newdev->init = init ? init : dummyInit;
 	newdev->get = get ? get : dummyGet;
 	newdev->shutdown = shutdown ? shutdown : dummyShutdown;
@@ -223,7 +223,7 @@
 		continue;
 	    }
 
-	    deviceRegister(names[i], names[i], d->name, DEVICE_TYPE_DISK, FALSE,
+	    deviceRegister(names[i], names[i], d->name, DEVICE_TYPE_DISK,
 			   dummyInit, dummyGet, dummyShutdown, d);
 	    if (isDebug())
 		msgDebug("Found a disk device named %s\n", names[i]);
@@ -237,7 +237,7 @@
 
 		    /* Got one! */
 		    snprintf(devname, sizeof devname, "/dev/%s", c1->name);
-		    dev = deviceRegister(c1->name, c1->name, strdup(devname), DEVICE_TYPE_DOS, TRUE,
+		    dev = deviceRegister(c1->name, c1->name, strdup(devname), DEVICE_TYPE_DOS,
 			mediaInitDOS, mediaGetDOS, mediaShutdownDOS, NULL);
 		    dev->private = c1;
 		    if (isDebug())
@@ -248,7 +248,7 @@
 	}
 	free(names);
     }
-    dialog_clear_norefresh();
+    dlg_clear();
 }
 
 /* Rescan all devices, after closing previous set - convenience function */
@@ -314,7 +314,7 @@
  * menu is cloned.
  */
 DMenu *
-deviceCreateMenu(DMenu *menu, DeviceType type, int (*hook)(dialogMenuItem *d), int (*check)(dialogMenuItem *d))
+deviceCreateMenu(DMenu *menu, DeviceType type, int (*hook)(dialogMenuItem *d))
 {
     Device **devs;
     int numdevs;
@@ -338,7 +338,6 @@
 	if (j == numDevs)
 	    tmp->items[i].title = "<unknown device type>";
 	tmp->items[i].fire = hook;
-	tmp->items[i].checked = check;
     }
     tmp->items[i].title = NULL;
     return tmp;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.sbin/sade/disks.c
--- a/head/usr.sbin/sade/disks.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/usr.sbin/sade/disks.c	Tue Dec 06 20:26:16 2011 +0200
@@ -1,5 +1,5 @@
 /*
- * $FreeBSD$
+ * $FreeBSD: head/usr.sbin/sade/disks.c 227944 2011-11-24 18:37:16Z fjoe $
  *
  * Copyright (c) 1995
  *	Jordan Hubbard.  All rights reserved.
@@ -113,7 +113,7 @@
     if (d->bios_cyl > 65536 || d->bios_hd > 256 || d->bios_sect >= 64)
 #endif
     {
-	dialog_clear_norefresh();
+	dlg_clear();
 	sg = msgYesNo("WARNING:  It is safe to use a geometry of %lu/%lu/%lu for %s on\n"
 		      "computers with modern BIOS versions.  If this disk is to be used\n"
 		      "on an old machine it is recommended that it does not have more\n"
@@ -223,21 +223,21 @@
     char *cp;
     int i = 0;
 
+    dlg_clr_result();
     cp = variable_get(VAR_BOOTMGR);
     if (!cp) {
 	/* Figure out what kind of IPL the user wants */
 	sprintf(str, "Install Boot Manager for drive %s?", dname);
 	MenuIPLType.title = str;
-	i = dmenuOpenSimple(&MenuIPLType, FALSE);
+	i = dmenuOpen(&MenuIPLType);
     } else {
 	if (!strncmp(cp, "boot", 4))
-	    BootMgr = 0;
+            dlg_add_result(MenuIPLType.items[0].prompt);
 	else
-	    BootMgr = 1;
+            dlg_add_result(MenuIPLType.items[1].prompt);
     }
     if (cp || i) {
-	switch (BootMgr) {
-	case 0:
+        if (!strcmp(dialog_vars.input_result, MenuIPLType.items[0].prompt)) {
 	    if (!boot0) boot0 = bootalloc("boot0", &boot0_size);
 	    *bootipl = boot0;
 	    *bootipl_size = boot0_size;
@@ -245,10 +245,7 @@
 	    *bootmenu = boot05;
 	    *bootmenu_size = boot05_size;
 	    return;
-	case 1:
-	default:
-	    break;
-	}
+        }
     }
     *bootipl = NULL;
     *bootipl_size = 0;
@@ -266,36 +263,33 @@
     char *cp;
     int i = 0;
 
+    dlg_clr_result();
     cp = variable_get(VAR_BOOTMGR);
     if (!cp) {
 	/* Figure out what kind of MBR the user wants */
 	sprintf(str, "Install Boot Manager for drive %s?", dname);
 	MenuMBRType.title = str;
-	i = dmenuOpenSimple(&MenuMBRType, FALSE);
+	i = dmenuOpen(&MenuMBRType);
     }
     else {
+	if (!strcmp(cp, "standard"))
+            dlg_add_result(MenuMBRType.items[0].prompt);
 	if (!strncmp(cp, "boot", 4))
-	    BootMgr = 0;
-	else if (!strcmp(cp, "standard"))
-	    BootMgr = 1;
+            dlg_add_result(MenuMBRType.items[1].prompt);
 	else
-	    BootMgr = 2;
+            dlg_add_result(MenuMBRType.items[2].prompt);
     }
     if (cp || i) {
-	switch (BootMgr) {
-	case 0:
+        if (!strcmp(dialog_vars.input_result, MenuMBRType.items[0].prompt)) {
+	    if (!mbr) mbr = bootalloc("mbr", &mbr_size);
+	    *bootCode = mbr;
+	    *bootCodeSize = mbr_size;
+	    return;
+	} else if (!strcmp(dialog_vars.input_result, MenuMBRType.items[1].prompt)) {
 	    if (!boot0) boot0 = bootalloc("boot0", &boot0_size);
 	    *bootCode = boot0;
 	    *bootCodeSize = boot0_size;
 	    return;
-	case 1:
-	    if (!mbr) mbr = bootalloc("mbr", &mbr_size);
-	    *bootCode = mbr;
-	    *bootCodeSize = mbr_size;
-	    return;
-	case 2:
-	default:
-	    break;
 	}
     }
 #endif
@@ -305,25 +299,6 @@
 #endif
 #endif /* WITH_SLICES */
 
-int
-diskGetSelectCount(Device ***devs)
-{
-    int i, cnt, enabled;
-    char *cp;
-    Device **dp;
-
-    cp = variable_get(VAR_DISK);
-    dp = *devs = deviceFind(cp, DEVICE_TYPE_DISK);
-    cnt = deviceCount(dp);
-    if (!cnt)
-	return -1;
-    for (i = 0, enabled = 0; i < cnt; i++) {
-	if (dp[i]->enabled)
-	    ++enabled;
-    }
-    return enabled;
-}
-
 #ifdef WITH_SLICES
 void
 diskPartition(Device *dev)
@@ -352,7 +327,7 @@
 
     /* Flush both the dialog and curses library views of the screen
        since we don't always know who called us */
-    dialog_clear_norefresh(), clear();
+    dlg_clear(), clear();
     current_chunk = 0;
 
     /* Set up the chunk array */
@@ -641,7 +616,7 @@
 		Set_Boot_Mgr(d, mbrContents, mbrSize);
 #endif
 
-		if (DITEM_STATUS(diskPartitionWrite(NULL)) != DITEM_SUCCESS)
+		if (DITEM_STATUS(diskPartitionWrite(dev)) != DITEM_SUCCESS)
 		    msgConfirm("Disk partition write returned an error status!");
 		else
 		    msgConfirm("Wrote FDISK partition information out successfully.");
@@ -724,12 +699,15 @@
     p = CheckRules(d);
     if (p) {
 	char buf[FILENAME_MAX];
-	
-        use_helpline("Press F1 to read more about disk slices.");
-	use_helpfile(systemHelpFile("partition", buf));
+	DIALOG_VARS save_vars;
+
+	dlg_save_vars(&save_vars);
+        dialog_vars.help_line = "Press F1 to read more about disk slices.";
+	dialog_vars.help_file = systemHelpFile("partition", buf);
 	if (!variable_get(VAR_NO_WARN))
-	    dialog_mesgbox("Disk slicing warning:", p, -1, -1);
+	    xdialog_msgbox("Disk slicing warning:", p, -1, -1, 1);
 	free(p);
+	dlg_restore_vars(&save_vars);
     }
     restorescr(w);
 }
@@ -781,58 +759,28 @@
 	msgConfirm("Unable to find disk %s!", selected->prompt);
 	return DITEM_FAILURE;
     }
-    /* Toggle enabled status? */
-    if (!devs[0]->enabled) {
-	devs[0]->enabled = TRUE;
-	diskPartition(devs[0]);
-    }
-    else
-	devs[0]->enabled = FALSE;
+    diskPartition(devs[0]);
     return DITEM_SUCCESS;
 }
 
-static int
-partitionCheck(dialogMenuItem *selected)
-{
-    Device **devs = NULL;
-
-    devs = deviceFind(selected->prompt, DEVICE_TYPE_DISK);
-    if (!devs || devs[0]->enabled == FALSE)
-	return FALSE;
-    return TRUE;
-}
-
 int
 diskPartitionEditor(dialogMenuItem *self)
 {
     DMenu *menu;
     Device **devs;
-    int i, cnt, devcnt;
 
-    cnt = diskGetSelectCount(&devs);
-    devcnt = deviceCount(devs);
-    if (cnt == -1) {
+    devs = deviceFind(variable_get(VAR_DISK), DEVICE_TYPE_DISK);
+    if (devs == NULL) {
 	msgConfirm("No disks found!  Please verify that your disk controller is being\n"
 		   "properly probed at boot time.  See the Hardware Guide on the\n"
 		   "Documentation menu for clues on diagnosing this type of problem.");
 	return DITEM_FAILURE;
     }
-    else if (cnt) {
-	/* Some are already selected */
-	for (i = 0; i < devcnt; i++) {
-	    if (devs[i]->enabled) {
-		if (variable_get(VAR_NONINTERACTIVE) &&
-		  !variable_get(VAR_DISKINTERACTIVE))
-		    diskPartitionNonInteractive(devs[i]);
-		else
-		    diskPartition(devs[i]);
-	    }
-	}
-    }
     else {
 	/* No disks are selected, fall-back case now */
-	if (devcnt == 1) {
-	    devs[0]->enabled = TRUE;
+        int cnt = deviceCount(devs);
+
+	if (cnt == 1) {
 	    if (variable_get(VAR_NONINTERACTIVE) &&
 	      !variable_get(VAR_DISKINTERACTIVE))
 		diskPartitionNonInteractive(devs[0]);
@@ -841,7 +789,9 @@
 	    return DITEM_SUCCESS;
 	}
 	else {
-	    menu = deviceCreateMenu(&MenuDiskDevices, DEVICE_TYPE_DISK, partitionHook, partitionCheck);
+            int result;
+
+	    menu = deviceCreateMenu(&MenuDiskDevices, DEVICE_TYPE_DISK, partitionHook);
 	    if (!menu) {
 		msgConfirm("No devices suitable for installation found!\n\n"
 			   "Please verify that your disk controller (and attached drives)\n"
@@ -850,11 +800,10 @@
 			   "the boot messages.  Press [Scroll Lock] again to return.");
 		return DITEM_FAILURE;
 	    }
-	    else {
-		i = dmenuOpenSimple(menu, FALSE) ? DITEM_SUCCESS : DITEM_FAILURE;
-		free(menu);
-	    }
-	    return i;
+
+	    result = dmenuOpen(menu) ? DITEM_SUCCESS : DITEM_FAILURE;
+	    free(menu);
+	    return result;
 	}
     }
     return DITEM_SUCCESS;
@@ -862,48 +811,34 @@
 #endif /* WITH_SLICES */
 
 int
-diskPartitionWrite(dialogMenuItem *self)
+diskPartitionWrite(Device *dev)
 {
-    Device **devs;
-    int i;
+    Disk *d = (Disk *)dev->private;
+#if !defined(__ia64__)
+    static u_char *boot1;
+#endif
+#if defined(__i386__) || defined(__amd64__)
+    static u_char *boot2;
+#endif
 
     if (!variable_cmp(DISK_PARTITIONED, "written"))
 	return DITEM_SUCCESS;
 
-    devs = deviceFind(NULL, DEVICE_TYPE_DISK);
-    if (!devs) {
-	msgConfirm("Unable to find any disks to write to??");
-	return DITEM_FAILURE;
-    }
-    if (isDebug())
-	msgDebug("diskPartitionWrite: Examining %d devices\n", deviceCount(devs));
-    for (i = 0; devs[i]; i++) {
-	Disk *d = (Disk *)devs[i]->private;
-#if !defined(__ia64__)
-	static u_char *boot1;
-#endif
 #if defined(__i386__) || defined(__amd64__)
-	static u_char *boot2;
+    if (!boot1) boot1 = bootalloc("boot1", NULL);
+    if (!boot2) boot2 = bootalloc("boot2", NULL);
+    Set_Boot_Blocks(d, boot1, boot2);
+#elif !defined(__ia64__)
+    if (!boot1) boot1 = bootalloc("boot1", NULL);
+    Set_Boot_Blocks(d, boot1, NULL);
 #endif
 
-	if (!devs[i]->enabled)
-	    continue;
+    msgNotify("Writing partition information to drive %s", d->name);
+    if (!Fake && Write_Disk(d)) {
+        msgConfirm("ERROR: Unable to write data to disk %s!", d->name);
+        return DITEM_FAILURE;
+    }
 
-#if defined(__i386__) || defined(__amd64__)
-	if (!boot1) boot1 = bootalloc("boot1", NULL);
-	if (!boot2) boot2 = bootalloc("boot2", NULL);
-	Set_Boot_Blocks(d, boot1, boot2);
-#elif !defined(__ia64__)
-	if (!boot1) boot1 = bootalloc("boot1", NULL);
-	Set_Boot_Blocks(d, boot1, NULL);
-#endif
-
-	msgNotify("Writing partition information to drive %s", d->name);
-	if (!Fake && Write_Disk(d)) {
-	    msgConfirm("ERROR: Unable to write data to disk %s!", d->name);
-	    return DITEM_FAILURE;
-	}
-    }
     /* Now it's not "yes", but "written" */
     variable_set2(DISK_PARTITIONED, "written", 0);
     return DITEM_SUCCESS | DITEM_RESTORE;
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.sbin/sade/dispatch.c
--- a/head/usr.sbin/sade/dispatch.c	Tue Dec 06 20:03:07 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,161 +0,0 @@
-/*
- * $FreeBSD$
- *
- * Copyright (c) 1995
- *	Jordan Hubbard.  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,
- *    verbatim and that no modifications are made prior to this
- *    point in the file.
- * 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 JORDAN HUBBARD ``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 JORDAN HUBBARD OR HIS PETS 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, LIFE 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 "sade.h"
-#include <ctype.h>
-#include <errno.h>
-#include <sys/signal.h>
-#include <sys/fcntl.h>
-
-#include "list.h"
-
-static int dispatch_systemExecute(dialogMenuItem *unused);
-static int dispatch_msgConfirm(dialogMenuItem *unused);
-
-static struct _word {
-    char *name;
-    int (*handler)(dialogMenuItem *self);
-} resWords[] = {
-#ifdef WITH_SLICES
-    { "diskPartitionEditor",	diskPartitionEditor	},
-#endif
-    { "diskPartitionWrite",	diskPartitionWrite	},
-    { "diskLabelEditor",	diskLabelEditor		},
-    { "diskLabelCommit",	diskLabelCommit		},
-    { "msgConfirm",		dispatch_msgConfirm	},
-    { "system",			dispatch_systemExecute	},
-    { "dumpVariables",		dump_variables		},
-    { NULL, NULL },
-};
-
-/*
- * Helper routines for buffering data.
- *
- * We read an entire configuration into memory before executing it
- * so that we are truely standalone and can do things like nuke the
- * file or disk we're working on.
- */
-
-typedef struct command_buffer_ {
-    qelement	queue;
-    char *	string;
-} command_buffer;
-
-/*
- * Command processing
- */
-
-static int
-dispatch_systemExecute(dialogMenuItem *unused)
-{
-    char *cmd = variable_get(VAR_COMMAND);
-
-    if (cmd)
-	return systemExecute(cmd) ? DITEM_FAILURE : DITEM_SUCCESS;
-    else
-	msgDebug("_systemExecute: No command passed in `command' variable.\n");
-    return DITEM_FAILURE;
-}
-
-static int
-dispatch_msgConfirm(dialogMenuItem *unused)
-{
-    char *msg = variable_get(VAR_COMMAND);
-
-    if (msg) {
-	msgConfirm("%s", msg);
-	return DITEM_SUCCESS;
-    }
-
-    msgDebug("_msgConfirm: No message passed in `command' variable.\n");
-    return DITEM_FAILURE;
-}
-
-static int
-call_possible_resword(char *name, dialogMenuItem *value, int *status)
-{
-    int i, rval;
-
-    rval = 0;
-    for (i = 0; resWords[i].name; i++) {
-	if (!strcmp(name, resWords[i].name)) {
-	    *status = resWords[i].handler(value);
-	    rval = 1;
-	    break;
-	}
-    }
-    return rval;
-}
-
-/* For a given string, call it or spit out an undefined command diagnostic */
-int
-dispatchCommand(char *str)
-{
-    int i;
-    char *cp;
-
-    if (!str || !*str) {
-	msgConfirm("Null or zero-length string passed to dispatchCommand");
-	return DITEM_FAILURE;
-    }
-    /* If it's got a newline, trim it */
-    if ((cp = index(str, '\n')) != NULL)
-	*cp = '\0';
-
-    /* If it's got a `=' sign in there, assume it's a variable setting */
-    if (index(str, '=')) {
-	if (isDebug())
-	    msgDebug("dispatch: setting variable `%s'\n", str);
-	variable_set(str, 0);
-	i = DITEM_SUCCESS;
-    }
-    else {
-	/* A command might be a pathname if it's encoded in argv[0], which
-	   we also support */
-	if ((cp = rindex(str, '/')) != NULL)
-	    str = cp + 1;
-	if (isDebug())
-	    msgDebug("dispatch: calling resword `%s'\n", str);
-	if (!call_possible_resword(str, NULL, &i)) {
-	    msgNotify("Warning: No such command ``%s''", str);
-	    i = DITEM_FAILURE;
-	}
-	/*
-	 * Allow a user to prefix a command with "noError" to cause
-	 * us to ignore any errors for that one command.
-	 */
-	if (i != DITEM_SUCCESS && variable_get(VAR_NO_ERROR))
-	    i = DITEM_SUCCESS;
-	variable_unset(VAR_NO_ERROR);
-    }
-    return i;
-}
-
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.sbin/sade/dmenu.c
--- a/head/usr.sbin/sade/dmenu.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/usr.sbin/sade/dmenu.c	Tue Dec 06 20:26:16 2011 +0200
@@ -1,5 +1,5 @@
 /*
- * $FreeBSD$
+ * $FreeBSD: head/usr.sbin/sade/dmenu.c 227944 2011-11-24 18:37:16Z fjoe $
  *
  * Copyright (c) 1995
  *	Jordan Hubbard.  All rights reserved.
@@ -34,196 +34,6 @@
 
 #define MAX_MENU		15
 
-static Boolean exited;
-
-int
-dmenuDisplayFile(dialogMenuItem *tmp)
-{
-    systemDisplayHelp((char *)tmp->data);
-    return DITEM_SUCCESS;
-}
-
-int
-dmenuSubmenu(dialogMenuItem *tmp)
-{
-    return (dmenuOpenSimple((DMenu *)(tmp->data), FALSE) ? DITEM_SUCCESS : DITEM_FAILURE);
-}
-
-int
-dmenuSystemCommand(dialogMenuItem *self)
-{
-    WINDOW *w = NULL;	/* Keep lint happy */
-
-    /* If aux is set, the command is known not to produce any screen-spoiling output */
-    if (!self->aux)
-	w = savescr();
-    systemExecute((char *)self->data);
-    if (!self->aux)
-	restorescr(w);
-    return DITEM_SUCCESS;
-}
-
-int
-dmenuSystemCommandBox(dialogMenuItem *tmp)
-{
-    WINDOW *w = savescr();
-    
-    use_helpfile(NULL);
-    use_helpline("Select OK to dismiss this dialog");
-    dialog_prgbox(tmp->title, (char *)tmp->data, 22, 76, 1, 1);
-    restorescr(w);
-    return DITEM_SUCCESS;
-}
-
-int
-dmenuExit(dialogMenuItem *tmp)
-{
-    exited = TRUE;
-    return DITEM_LEAVE_MENU;
-}
-
-int
-dmenuSetVariable(dialogMenuItem *tmp)
-{
-    variable_set((char *)tmp->data, *((char *)tmp->data) != '_');
-    return DITEM_SUCCESS;
-}
-
-int
-dmenuSetVariables(dialogMenuItem *tmp)
-{
-    char *cp1, *cp2;
-    char *copy = strdup((char *)tmp->data);
-
-    for (cp1 = copy; cp1 != NULL;) {
-	cp2 = index(cp1, ',');
-	if (cp2 != NULL) *cp2++ = '\0';
-	variable_set(cp1, *cp1 != '_');
-	cp1 = cp2;
-    }
-    free(copy);
-    return DITEM_SUCCESS;
-}
-
-int
-dmenuToggleVariable(dialogMenuItem *tmp)
-{
-    char *var, *cp;
-    int status;
-
-    if (!(var = strdup((char *)tmp->data))) {
-	msgConfirm("Incorrect data field for `%s'!", tmp->title);
-	return DITEM_FAILURE;
-    }
-    if (!(cp = index(var, '='))) {
-	msgConfirm("Data field for %s is not in var=value format!", tmp->title);
-	return DITEM_FAILURE;
-    }
-    status = variable_check(var);
-    *cp = '\0';
-    variable_set2(var, status ? "NO" : "YES", *var != '_');
-    free(var);
-    return DITEM_SUCCESS;
-}
-
-int
-dmenuISetVariable(dialogMenuItem *tmp)
-{
-    char *ans, *var;
-
-    if (!(var = (char *)tmp->data)) {
-	msgConfirm("Incorrect data field for `%s'!", tmp->title);
-	return DITEM_FAILURE;
-    }
-    ans = msgGetInput(variable_get(var), tmp->title, 1);
-    if (!ans)
-	return DITEM_FAILURE;
-    else if (!*ans)
-	variable_unset(var);
-    else
-	variable_set2(var, ans, *var != '_');
-    return DITEM_SUCCESS;
-}
-
-int
-dmenuSetFlag(dialogMenuItem *tmp)
-{
-    if (*((unsigned int *)tmp->data) & tmp->aux)
-	*((unsigned int *)tmp->data) &= ~tmp->aux;
-    else
-	*((unsigned int *)tmp->data) |= tmp->aux;
-    return DITEM_SUCCESS;
-}
-
-int
-dmenuSetValue(dialogMenuItem *tmp)
-{
-    *((unsigned int *)tmp->data) = tmp->aux;
-    return DITEM_SUCCESS;
-}
-
-/* Traverse menu but give user no control over positioning */
-Boolean
-dmenuOpenSimple(DMenu *menu, Boolean buttons)
-{
-    int choice, scroll, curr, max;
-
-    choice = scroll = curr = max = 0;
-    return dmenuOpen(menu, &choice, &scroll, &curr, &max, buttons);
-}
-
-/* Work functions for the state hook */
-int
-dmenuFlagCheck(dialogMenuItem *item)
-{
-    return (*((unsigned int *)item->data) & item->aux);
-}
-
-int
-dmenuVarCheck(dialogMenuItem *item)
-{
-    char *w;
-
-    w = (char *)item->aux;
-    if (!w)
-	w = (char *)item->data;
-    return variable_check(w);
-}
-
-int
-dmenuVarsCheck(dialogMenuItem *item)
-{
-    int res, init;
-    char *w, *cp1, *cp2;
-    char *copy;
-
-    w = (char *)item->aux;
-    if (!w)
-	w = (char *)item->data;
-    if (!w)
-	return FALSE;
-    
-    copy = strdup(w);
-    res = TRUE;
-    init = FALSE;
-    for (cp1 = copy; cp1 != NULL;) {
-        init = TRUE;
-	cp2 = index(cp1, ',');
-	if (cp2 != NULL)
-	    *cp2++ = '\0';
-	res = res && variable_check(cp1);
-	cp1 = cp2;
-    }
-    free(copy);
-    return res && init;
-}
-
-int
-dmenuRadioCheck(dialogMenuItem *item)
-{
-    return (*((long *)item->data) == item->aux);
-}
-
 static int
 menu_height(DMenu *menu, int n)
 {
@@ -242,54 +52,42 @@
 
 /* Traverse over an internal menu */
 Boolean
-dmenuOpen(DMenu *menu, int *choice, int *scroll, int *curr, int *max, Boolean buttons)
+dmenuOpen(DMenu *menu)
 {
     int n, rval = 0;
-    dialogMenuItem *items;
 
-    items = menu->items;
-    if (buttons)
-	items += 2;
     /* Count up all the items */
-    for (n = 0; items[n].title; n++);
+    for (n = 0; menu->items[n].title; n++)
+	    ;
 
     while (1) {
 	char buf[FILENAME_MAX];
+	DIALOG_VARS save_vars;
 	WINDOW *w = savescr();
 
 	/* Any helpful hints, put 'em up! */
-	use_helpline(menu->helpline);
-	use_helpfile(systemHelpFile(menu->helpfile, buf));
-	dialog_clear_norefresh();
+	dlg_save_vars(&save_vars);
+	dialog_vars.help_line = menu->helpline;
+	dialog_vars.help_file = systemHelpFile(menu->helpfile, buf);
+	dlg_clear();
 	/* Pop up that dialog! */
-	if (menu->type & DMENU_NORMAL_TYPE)
-	    rval = dialog_menu((u_char *)menu->title, (u_char *)menu->prompt,
-		-1, -1, menu_height(menu, n), -n, items,
-		(char *)(uintptr_t)buttons, choice, scroll);
-
-	else if (menu->type & DMENU_RADIO_TYPE)
-	    rval = dialog_radiolist((u_char *)menu->title,
-		(u_char *)menu->prompt, -1, -1, menu_height(menu, n), -n,
-		items, (char *)(uintptr_t)buttons);
-
-	else if (menu->type & DMENU_CHECKLIST_TYPE)
-	    rval = dialog_checklist((u_char *)menu->title,
-		(u_char *)menu->prompt, -1, -1, menu_height(menu, n), -n,
-		items, (char *)(uintptr_t)buttons);
-	else
+	if (menu->type & DMENU_NORMAL_TYPE) {
+	    rval = xdialog_menu(menu->title, menu->prompt,
+		-1, -1, menu_height(menu, n), n, menu->items);
+	} else if (menu->type & DMENU_RADIO_TYPE) {
+	    rval = xdialog_radiolist(menu->title, menu->prompt,
+		-1, -1, menu_height(menu, n), n, menu->items);
+	} else {
 	    msgFatal("Menu: `%s' is of an unknown type\n", menu->title);
-	if (exited) {
-	    exited = FALSE;
+	}
+	dlg_restore_vars(&save_vars);
+	if (rval) {
+	    restorescr(w);
+	    return FALSE;
+	} else if (menu->type & DMENU_SELECTION_RETURNS) {
 	    restorescr(w);
 	    return TRUE;
-	}
-	else if (rval) {
-	    restorescr(w);
-	    return FALSE;
-	}
-	else if (menu->type & DMENU_SELECTION_RETURNS) {
-	    restorescr(w);
-	    return TRUE;
-	}
+	} else
+	    delwin(w);
     }
 }
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.sbin/sade/install.c
--- a/head/usr.sbin/sade/install.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/usr.sbin/sade/install.c	Tue Dec 06 20:26:16 2011 +0200
@@ -1,5 +1,5 @@
 /*
- * $FreeBSD$
+ * $FreeBSD: head/usr.sbin/sade/install.c 227944 2011-11-24 18:37:16Z fjoe $
  *
  * Copyright (c) 1995
  *	Jordan Hubbard.  All rights reserved.
@@ -29,7 +29,6 @@
  *
  */
 
-#include "sade.h"
 #include <ctype.h>
 #include <sys/consio.h>
 #include <sys/disklabel.h>
@@ -51,6 +50,8 @@
 #include <unistd.h>
 #include <termios.h>
 
+#include "sade.h"
+
 #define TERMCAP_FILE	"/usr/share/misc/termcap"
 
 Boolean
@@ -113,12 +114,10 @@
 
 /* Go newfs and/or mount all the filesystems we've been asked to */
 int
-installFilesystems(dialogMenuItem *self)
+installFilesystems(Device *dev)
 {
-    int i;
-    Disk *disk;
+    Disk *disk = (Disk *)dev->private;
     Chunk *c1, *c2;
-    Device **devs;
     PartInfo *root;
     char dname[80];
     Boolean upgrade = FALSE;
@@ -136,89 +135,82 @@
     command_clear();
 
     /* Now buzz through the rest of the partitions and mount them too */
-    devs = deviceFind(NULL, DEVICE_TYPE_DISK);
-    for (i = 0; devs[i]; i++) {
-	if (!devs[i]->enabled)
-	    continue;
+    if (!disk->chunks) {
+        msgConfirm("No chunk list found for %s!", disk->name);
+        return DITEM_FAILURE | DITEM_RESTORE;
+    }
+    for (c1 = disk->chunks->part; c1; c1 = c1->next) {
+#ifdef __ia64__
+    if (c1->type == part) {
+        c2 = c1;
+        {
+#elif defined(__powerpc__)
+        if (c1->type == apple) {
+            for (c2 = c1->part; c2; c2 = c2->next) {
+#else
+        if (c1->type == freebsd) {
+            for (c2 = c1->part; c2; c2 = c2->next) {
+#endif
+                if (c2->type == part && c2->subtype != FS_SWAP && c2->private_data) {
+                    PartInfo *tmp = (PartInfo *)c2->private_data;
 
-	disk = (Disk *)devs[i]->private;
-	if (!disk->chunks) {
-	    msgConfirm("No chunk list found for %s!", disk->name);
-	    return DITEM_FAILURE | DITEM_RESTORE;
-	}
-	for (c1 = disk->chunks->part; c1; c1 = c1->next) {
-#ifdef __ia64__
-	if (c1->type == part) {
-		c2 = c1;
-		{
-#elif defined(__powerpc__)
-	    if (c1->type == apple) {
-		for (c2 = c1->part; c2; c2 = c2->next) {
-#else
-	    if (c1->type == freebsd) {
-		for (c2 = c1->part; c2; c2 = c2->next) {
+                    /* Already did root */
+                    if (c2 == RootChunk)
+                        continue;
+
+                    sprintf(dname, "/dev/%s", c2->name);
+
+                    if (tmp->do_newfs && (!upgrade ||
+                        !msgNoYes("You are upgrading - are you SURE you"
+                        " want to newfs /dev/%s?", c2->name)))
+                            performNewfs(tmp, dname, QUEUE_YES);
+                    else
+                        command_shell_add(tmp->mountpoint,
+                            "fsck_ffs -y /dev/%s", c2->name);
+                    command_func_add(tmp->mountpoint, Mount, c2->name);
+                }
+                else if (c2->type == part && c2->subtype == FS_SWAP) {
+                    char fname[80];
+                    int i;
+
+                    if (c2 == SwapChunk)
+                        continue;
+                    sprintf(fname, "/dev/%s", c2->name);
+                    i = (Fake || swapon(fname));
+                    if (!i) {
+                        dlg_clear();
+                        msgNotify("Added %s as an additional swap device", fname);
+                    }
+                    else {
+                        msgConfirm("Unable to add %s as a swap device: %s", fname, strerror(errno));
+                    }
+                }
+            }
+        }
+        else if (c1->type == fat && c1->private_data &&
+            (root->do_newfs || upgrade)) {
+            char name[FILENAME_MAX];
+
+            sprintf(name, "/%s", ((PartInfo *)c1->private_data)->mountpoint);
+            Mkdir(name);
+        }
+#if defined(__ia64__)
+        else if (c1->type == efi && c1->private_data) {
+            PartInfo *pi = (PartInfo *)c1->private_data;
+
+            sprintf(dname, "/dev/%s", c1->name);
+
+            if (pi->do_newfs && (!upgrade ||
+                !msgNoYes("You are upgrading - are you SURE you want to "
+                "newfs /dev/%s?", c1->name)))
+                    performNewfs(pi, dname, QUEUE_YES);
+        }
 #endif
-		    if (c2->type == part && c2->subtype != FS_SWAP && c2->private_data) {
-			PartInfo *tmp = (PartInfo *)c2->private_data;
-
-			/* Already did root */
-			if (c2 == RootChunk)
-			    continue;
-
-			sprintf(dname, "/dev/%s", c2->name);
-
-			if (tmp->do_newfs && (!upgrade ||
-			    !msgNoYes("You are upgrading - are you SURE you"
-			    " want to newfs /dev/%s?", c2->name)))
-				performNewfs(tmp, dname, QUEUE_YES);
-			else
-			    command_shell_add(tmp->mountpoint,
-				"fsck_ffs -y /dev/%s", c2->name);
-			command_func_add(tmp->mountpoint, Mount, c2->name);
-		    }
-		    else if (c2->type == part && c2->subtype == FS_SWAP) {
-			char fname[80];
-			int i;
-
-			if (c2 == SwapChunk)
-			    continue;
-			sprintf(fname, "/dev/%s", c2->name);
-			i = (Fake || swapon(fname));
-			if (!i) {
-			    dialog_clear_norefresh();
-			    msgNotify("Added %s as an additional swap device", fname);
-			}
-			else {
-			    msgConfirm("Unable to add %s as a swap device: %s", fname, strerror(errno));
-			}
-		    }
-		}
-	    }
-	    else if (c1->type == fat && c1->private_data &&
-		(root->do_newfs || upgrade)) {
-		char name[FILENAME_MAX];
-
-		sprintf(name, "/%s", ((PartInfo *)c1->private_data)->mountpoint);
-		Mkdir(name);
-	    }
-#if defined(__ia64__)
-	    else if (c1->type == efi && c1->private_data) {
-		PartInfo *pi = (PartInfo *)c1->private_data;
-
-		sprintf(dname, "/dev/%s", c1->name);
-
-		if (pi->do_newfs && (!upgrade ||
-		    !msgNoYes("You are upgrading - are you SURE you want to "
-		    "newfs /dev/%s?", c1->name)))
-			performNewfs(pi, dname, QUEUE_YES);
-	    }
-#endif
-	}
     }
 
     command_sort();
     command_execute();
-    dialog_clear_norefresh();
+    dlg_clear();
     return DITEM_SUCCESS | DITEM_RESTORE;
 }
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.sbin/sade/label.c
--- a/head/usr.sbin/sade/label.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/usr.sbin/sade/label.c	Tue Dec 06 20:26:16 2011 +0200
@@ -1,5 +1,5 @@
 /*
- * $FreeBSD$
+ * $FreeBSD: head/usr.sbin/sade/label.c 227944 2011-11-24 18:37:16Z fjoe $
  *
  * Copyright (c) 1995
  *	Jordan Hubbard.  All rights reserved.
@@ -29,7 +29,7 @@
  *
  */
 
-#include "sade.h"
+#include <sys/types.h>
 #include <ctype.h>
 #include <inttypes.h>
 #include <libdisk.h>
@@ -37,6 +37,8 @@
 #include <sys/param.h>
 #include <sys/sysctl.h>
 
+#include "sade.h"
+
 #define AUTO_HOME	0	/* do not create /home automatically */
 
 /*
@@ -110,7 +112,7 @@
 
 static int diskLabel(Device *dev);
 static int diskLabelNonInteractive(Device *dev);
-static char *try_auto_label(Device **devs, Device *dev, int perc, int *req);
+static char *try_auto_label(Device *dev, int perc, int *req);
 
 static int
 labelHook(dialogMenuItem *selected)
@@ -122,86 +124,59 @@
 	msgConfirm("Unable to find disk %s!", selected->prompt);
 	return DITEM_FAILURE;
     }
-    /* Toggle enabled status? */
-    if (!devs[0]->enabled) {
-	devs[0]->enabled = TRUE;
-	diskLabel(devs[0]);
-    }
-    else
-	devs[0]->enabled = FALSE;
+    diskLabel(devs[0]);
     return DITEM_SUCCESS;
 }
 
-static int
-labelCheck(dialogMenuItem *selected)
-{
-    Device **devs = NULL;
-
-    devs = deviceFind(selected->prompt, DEVICE_TYPE_DISK);
-    if (!devs || devs[0]->enabled == FALSE)
-	return FALSE;
-    return TRUE;
-}
-
 int
 diskLabelEditor(dialogMenuItem *self)
 {
     DMenu *menu;
     Device **devs;
-    int i, cnt;
+    int result;
 
-    i = 0;
-    cnt = diskGetSelectCount(&devs);
-    if (cnt == -1) {
+    devs = deviceFind(variable_get(VAR_DISK), DEVICE_TYPE_DISK);
+    if (devs == NULL) {
 	msgConfirm("No disks found!  Please verify that your disk controller is being\n"
 		   "properly probed at boot time.  See the Hardware Guide on the\n"
 		   "Documentation menu for clues on diagnosing this type of problem.");
 	return DITEM_FAILURE;
     }
-    else if (cnt) {
-	/* Some are already selected */
-	if (variable_get(VAR_NONINTERACTIVE) &&
-	  !variable_get(VAR_DISKINTERACTIVE))
-	    i = diskLabelNonInteractive(NULL);
-	else
-	    i = diskLabel(NULL);
-    }
     else {
 	/* No disks are selected, fall-back case now */
-	cnt = deviceCount(devs);
+	int cnt = deviceCount(devs);
 	if (cnt == 1) {
-	    devs[0]->enabled = TRUE;
 	    if (variable_get(VAR_NONINTERACTIVE) &&
 	      !variable_get(VAR_DISKINTERACTIVE))
-		i = diskLabelNonInteractive(devs[0]);
+		result = diskLabelNonInteractive(devs[0]);
 	    else
-		i = diskLabel(devs[0]);
+		result = diskLabel(devs[0]);
 	}
 	else {
-	    menu = deviceCreateMenu(&MenuDiskDevices, DEVICE_TYPE_DISK, labelHook, labelCheck);
+	    menu = deviceCreateMenu(&MenuDiskDevices, DEVICE_TYPE_DISK, labelHook);
 	    if (!menu) {
 		msgConfirm("No devices suitable for installation found!\n\n"
 			   "Please verify that your disk controller (and attached drives)\n"
 			   "were detected properly.  This can be done by pressing the\n"
 			   "[Scroll Lock] key and using the Arrow keys to move back to\n"
 			   "the boot messages.  Press [Scroll Lock] again to return.");
-		i = DITEM_FAILURE;
+		result = DITEM_FAILURE;
 	    }
 	    else {
-		i = dmenuOpenSimple(menu, FALSE) ? DITEM_SUCCESS : DITEM_FAILURE;
+		result = dmenuOpen(menu) ? DITEM_SUCCESS : DITEM_FAILURE;
 		free(menu);
 	    }
 	}
     }
-    if (DITEM_STATUS(i) != DITEM_FAILURE) {
+    if (DITEM_STATUS(result) != DITEM_FAILURE) {
 	if (variable_cmp(DISK_LABELLED, "written"))
 	    variable_set2(DISK_LABELLED, "yes", 0);
     }
-    return i;
+    return result;
 }
 
 int
-diskLabelCommit(dialogMenuItem *self)
+diskLabelCommit(Device *dev)
 {
     char *cp;
     int i;
@@ -214,9 +189,9 @@
 	i = DITEM_FAILURE;
     }
     /* The routine will guard against redundant writes, just as this one does */
-    else if (DITEM_STATUS(diskPartitionWrite(self)) != DITEM_SUCCESS)
+    else if (DITEM_STATUS(diskPartitionWrite(dev)) != DITEM_SUCCESS)
 	i = DITEM_FAILURE;
-    else if (DITEM_STATUS(installFilesystems(self)) != DITEM_SUCCESS)
+    else if (DITEM_STATUS(installFilesystems(dev)) != DITEM_SUCCESS)
 	i = DITEM_FAILURE;
     else {
 	msgInfo("All filesystem information written successfully.");
@@ -258,98 +233,87 @@
 
 /* Snapshot the current situation into the displayed chunks structure */
 static void
-record_label_chunks(Device **devs, Device *dev)
+record_label_chunks(Device *dev)
 {
-    int i, j, p;
+    int j, p;
     struct chunk *c1, *c2;
-    Disk *d;
+    Disk *d = (Disk *)dev->private;
 
     j = p = 0;
     /* First buzz through and pick up the FreeBSD slices */
-    for (i = 0; devs[i]; i++) {
-	if ((dev && devs[i] != dev) || !devs[i]->enabled)
-	    continue;
-	d = (Disk *)devs[i]->private;
-	if (!d->chunks)
-	    msgFatal("No chunk list found for %s!", d->name);
+    if (!d->chunks)
+        msgFatal("No chunk list found for %s!", d->name);
 
 #ifdef __ia64__
-	label_chunk_info[j].type = PART_SLICE;
-	label_chunk_info[j].c = d->chunks;
-	j++;
+    label_chunk_info[j].type = PART_SLICE;
+    label_chunk_info[j].c = d->chunks;
+    j++;
 #endif
 
-	/* Put the slice entries first */
-	for (c1 = d->chunks->part; c1; c1 = c1->next) {
-	    if (c1->type == freebsd) {
-		label_chunk_info[j].type = PART_SLICE;
-		label_chunk_info[j].c = c1;
-		++j;
-	    }
+    /* Put the slice entries first */
+    for (c1 = d->chunks->part; c1; c1 = c1->next) {
+        if (c1->type == freebsd) {
+            label_chunk_info[j].type = PART_SLICE;
+            label_chunk_info[j].c = c1;
+            ++j;
+        }
 #ifdef __powerpc__
-	    if (c1->type == apple) {
-    	        label_chunk_info[j].type = PART_SLICE;
-		label_chunk_info[j].c = c1;
-		++j;
-	    }
+        if (c1->type == apple) {
+            label_chunk_info[j].type = PART_SLICE;
+            label_chunk_info[j].c = c1;
+            ++j;
+        }
 #endif
-	}
     }
 
-    /* Now run through again and get the FreeBSD partition entries */
-    for (i = 0; devs[i]; i++) {
-	if (!devs[i]->enabled)
-	    continue;
-	d = (Disk *)devs[i]->private;
-	/* Then buzz through and pick up the partitions */
-	for (c1 = d->chunks->part; c1; c1 = c1->next) {
-	    if (c1->type == freebsd) {
-		for (c2 = c1->part; c2; c2 = c2->next) {
-		    if (c2->type == part) {
-			if (c2->subtype == FS_SWAP)
-			    label_chunk_info[j].type = PART_SWAP;
-			else
-			    label_chunk_info[j].type = PART_FILESYSTEM;
-			label_chunk_info[j].c = c2;
-			++j;
-		    }
-		}
-	    }
-	    else if (c1->type == fat) {
-		label_chunk_info[j].type = PART_FAT;
-		label_chunk_info[j].c = c1;
-		++j;
-	    }
+    /* Then buzz through and pick up the partitions */
+    for (c1 = d->chunks->part; c1; c1 = c1->next) {
+        if (c1->type == freebsd) {
+            for (c2 = c1->part; c2; c2 = c2->next) {
+                if (c2->type == part) {
+                    if (c2->subtype == FS_SWAP)
+                        label_chunk_info[j].type = PART_SWAP;
+                    else
+                        label_chunk_info[j].type = PART_FILESYSTEM;
+                    label_chunk_info[j].c = c2;
+                    ++j;
+                }
+            }
+        }
+        else if (c1->type == fat) {
+            label_chunk_info[j].type = PART_FAT;
+            label_chunk_info[j].c = c1;
+            ++j;
+        }
 #ifdef __ia64__
-	    else if (c1->type == efi) {
-		label_chunk_info[j].type = PART_EFI;
-		label_chunk_info[j].c = c1;
-		++j;
-	    }
-	    else if (c1->type == part) {
-		if (c1->subtype == FS_SWAP)
-		    label_chunk_info[j].type = PART_SWAP;
-		else
-		    label_chunk_info[j].type = PART_FILESYSTEM;
-		label_chunk_info[j].c = c1;
-		++j;
-	    }
+        else if (c1->type == efi) {
+            label_chunk_info[j].type = PART_EFI;
+            label_chunk_info[j].c = c1;
+            ++j;
+        }
+        else if (c1->type == part) {
+            if (c1->subtype == FS_SWAP)
+                label_chunk_info[j].type = PART_SWAP;
+            else
+                label_chunk_info[j].type = PART_FILESYSTEM;
+            label_chunk_info[j].c = c1;
+            ++j;
+        }
 #endif
 #ifdef __powerpc__
-	    else if (c1->type == apple) {
-	        for (c2 = c1->part; c2; c2 = c2->next) {
-		    if (c2->type == part) {
-		        if (c2->subtype == FS_SWAP)
-			    label_chunk_info[j].type = PART_SWAP;
-			else
-			    label_chunk_info[j].type = PART_FILESYSTEM;
-			label_chunk_info[j].c = c2;
-			++j;
-		    }
-		}
-	    }
+        else if (c1->type == apple) {
+            for (c2 = c1->part; c2; c2 = c2->next) {
+                if (c2->type == part) {
+                    if (c2->subtype == FS_SWAP)
+                        label_chunk_info[j].type = PART_SWAP;
+                    else
+                        label_chunk_info[j].type = PART_FILESYSTEM;
+                    label_chunk_info[j].c = c2;
+                    ++j;
+                }
+            }
+        }
 #endif
-	}
     }
     label_chunk_info[j].c = NULL;
     if (here >= j) {
@@ -455,9 +419,8 @@
 static PartType
 get_partition_type(void)
 {
-    char selection[20];
     int i;
-    static unsigned char *fs_types[] = {
+    static char *fs_types[] = {
 #ifdef __ia64__
 	"EFI",	"An EFI system partition",
 #endif
@@ -466,6 +429,7 @@
     };
     WINDOW *w = savescr();
 
+    dlg_clr_result();
     i = dialog_menu("Please choose a partition type",
 	"If you want to use this partition for swap space, select Swap.\n"
 	"If you want to put a filesystem on it, choose FS.",
@@ -475,16 +439,16 @@
 #else
 	2, 2,
 #endif
-	fs_types, selection, NULL, NULL);
+	fs_types);
     restorescr(w);
     if (!i) {
 #ifdef __ia64__
-	if (!strcmp(selection, "EFI"))
+	if (!strcmp(dialog_vars.input_result, "EFI"))
 	    return PART_EFI;
 #endif
-	if (!strcmp(selection, "FS"))
+	if (!strcmp(dialog_vars.input_result, "FS"))
 	    return PART_FILESYSTEM;
-	else if (!strcmp(selection, "Swap"))
+	else if (!strcmp(dialog_vars.input_result, "Swap"))
 	    return PART_SWAP;
     }
     return PART_NONE;
@@ -845,22 +809,15 @@
     char *msg = NULL;
     PartInfo *p, *oldp;
     PartType type;
-    Device **devs;
     WINDOW *w = savescr();
 
     label_focus = 0;
     pslice_focus = 0;
     here = 0;
 
-    devs = deviceFind(NULL, DEVICE_TYPE_DISK);
-    if (!devs) {
-	msgConfirm("No disks found!");
-	restorescr(w);
-	return DITEM_FAILURE;
-    }
     labeling = TRUE;
     keypad(stdscr, TRUE);
-    record_label_chunks(devs, dev);
+    record_label_chunks(dev);
 
     clear();
     while (labeling) {
@@ -883,7 +840,6 @@
 	refresh();
 	key = getch();
 	switch (toupper(key)) {
-	    int i;
 	    static char _msg[40];
 
 	case '\014':	/* ^L */
@@ -972,7 +928,7 @@
 
 		for (perc = 100; perc > 0; perc -= 5) {
 		    req = 0;	/* reset for each loop */
-		    if ((msg = try_auto_label(devs, dev, perc, &req)) == NULL)
+		    if ((msg = try_auto_label(dev, perc, &req)) == NULL)
 			break;
 		}
 		if (msg) {
@@ -1114,7 +1070,7 @@
 		tmp->private_free = safe_free;
 		if (variable_cmp(DISK_LABELLED, "written"))
 		    variable_set2(DISK_LABELLED, "yes", 0);
-		record_label_chunks(devs, dev);
+		record_label_chunks(dev);
 		clear_wins();
                 /* This is where we assign focus to new label so it shows. */
                 {
@@ -1151,7 +1107,7 @@
 	    Delete_Chunk2(label_chunk_info[here].c->disk, label_chunk_info[here].c, rflags);
 	    if (variable_cmp(DISK_LABELLED, "written"))
 		variable_set2(DISK_LABELLED, "yes", 0);
-	    record_label_chunks(devs, dev);
+	    record_label_chunks(dev);
 	    break;
 
 	case 'M':	/* mount */
@@ -1183,7 +1139,7 @@
 		}
 		if (variable_cmp(DISK_LABELLED, "written"))
 		    variable_set2(DISK_LABELLED, "yes", 0);
-		record_label_chunks(devs, dev);
+		record_label_chunks(dev);
 		clear_wins();
 		break;
 
@@ -1252,22 +1208,18 @@
 			   "it's too late to undo!");
 	    }
 	    else if (!msgNoYes("Are you SURE you want to Undo everything?")) {
+		Disk *d;
+
 		variable_unset(DISK_PARTITIONED);
 		variable_unset(DISK_LABELLED);
-		for (i = 0; devs[i]; i++) {
-		    Disk *d;
-
-		    if (!devs[i]->enabled)
-			continue;
-		    else if ((d = Open_Disk(devs[i]->name)) != NULL) {
-			Free_Disk(devs[i]->private);
-			devs[i]->private = d;
+		if ((d = Open_Disk(dev->name)) != NULL) {
+		    Free_Disk(dev->private);
+		    dev->private = d;
 #ifdef WITH_SLICES
-			diskPartition(devs[i]);
+		    diskPartition(dev);
 #endif
-		    }
 		}
-		record_label_chunks(devs, dev);
+		record_label_chunks(dev);
 	    }
 	    clear_wins();
 	    break;
@@ -1282,7 +1234,7 @@
 			  "installation.\n\n"
 			  "Are you absolutely sure you want to continue?")) {
 		variable_set2(DISK_LABELLED, "yes", 0);
-		diskLabelCommit(NULL);
+		diskLabelCommit(dev);
 	    }
 	    clear_wins();
 	    break;
@@ -1301,25 +1253,16 @@
 	    if (!msgNoYes("Are you sure you want to go into Wizard mode?\n\n"
 			  "This is an entirely undocumented feature which you are not\n"
 			  "expected to understand!")) {
-		int i;
-		Device **devs;
-
-		dialog_clear();
+		dlg_clear();
 		end_dialog();
 		DialogActive = FALSE;
-		devs = deviceFind(NULL, DEVICE_TYPE_DISK);
-		if (!devs) {
-		    msgConfirm("Can't find any disk devices!");
-		    break;
-		}
-		for (i = 0; devs[i] && ((Disk *)devs[i]->private); i++) {
-		    if (devs[i]->enabled)
-		    	slice_wizard(((Disk *)devs[i]->private));
+		if (dev->private) {
+		    slice_wizard(((Disk *)dev->private));
 		}
 		if (variable_cmp(DISK_LABELLED, "written"))
 		    variable_set2(DISK_LABELLED, "yes", 0);
 		DialogActive = TRUE;
-		record_label_chunks(devs, dev);
+		record_label_chunks(dev);
 		clear_wins();
 	    }
 	    else
@@ -1378,7 +1321,7 @@
  * and /home.  /home receives any extra left over disk space. 
  */
 static char *
-try_auto_label(Device **devs, Device *dev, int perc, int *req)
+try_auto_label(Device *dev, int perc, int *req)
 {
     daddr_t sz;
     Chunk *AutoHome, *AutoRoot, *AutoSwap;
@@ -1413,7 +1356,7 @@
 	AutoEfi->private_data = new_part(PART_EFI, "/efi", TRUE);
 	AutoEfi->private_free = safe_free;
 	AutoEfi->flags |= CHUNK_NEWFS;
-	record_label_chunks(devs, dev);
+	record_label_chunks(dev);
     }
 #endif
 
@@ -1431,7 +1374,7 @@
 	AutoRoot->private_data = new_part(PART_FILESYSTEM, "/", TRUE);
 	AutoRoot->private_free = safe_free;
 	AutoRoot->flags |= CHUNK_NEWFS;
-	record_label_chunks(devs, dev);
+	record_label_chunks(dev);
     }
     if (SwapChunk == NULL) {
 	sz = requested_part_size(VAR_SWAP_SIZE, 0, 0, perc);
@@ -1461,7 +1404,7 @@
 	}
 	AutoSwap->private_data = 0;
 	AutoSwap->private_free = safe_free;
-	record_label_chunks(devs, dev);
+	record_label_chunks(dev);
     }
     if (VarChunk == NULL) {
 	/* Work out how much extra space we want for a crash dump */
@@ -1492,7 +1435,7 @@
 	AutoVar->private_data = new_part(PART_FILESYSTEM, "/var", TRUE);
 	AutoVar->private_free = safe_free;
 	AutoVar->flags |= CHUNK_NEWFS;
-	record_label_chunks(devs, dev);
+	record_label_chunks(dev);
     }
     if (TmpChunk == NULL && !variable_get(VAR_NO_TMP)) {
 	sz = requested_part_size(VAR_TMP_SIZE, TMP_NOMINAL_SIZE, TMP_DEFAULT_SIZE, perc);
@@ -1509,7 +1452,7 @@
 	AutoTmp->private_data = new_part(PART_FILESYSTEM, "/tmp", TRUE);
 	AutoTmp->private_free = safe_free;
 	AutoTmp->flags |= CHUNK_NEWFS;
-	record_label_chunks(devs, dev);
+	record_label_chunks(dev);
     }
     if (UsrChunk == NULL && !variable_get(VAR_NO_USR)) {
 	sz = requested_part_size(VAR_USR_SIZE, USR_NOMINAL_SIZE, USR_DEFAULT_SIZE, perc);
@@ -1535,7 +1478,7 @@
 	    AutoUsr->private_data = new_part(PART_FILESYSTEM, "/usr", TRUE);
 	    AutoUsr->private_free = safe_free;
 	    AutoUsr->flags |= CHUNK_NEWFS;
-	    record_label_chunks(devs, dev);
+	    record_label_chunks(dev);
 	}
     }
 #if AUTO_HOME == 1
@@ -1562,7 +1505,7 @@
 	    AutoHome->private_data = new_part(PART_FILESYSTEM, "/home", TRUE);
 	    AutoHome->private_free = safe_free;
 	    AutoHome->flags |= CHUNK_NEWFS;
-	    record_label_chunks(devs, dev);
+	    record_label_chunks(dev);
 	}
     }
 #endif
@@ -1585,7 +1528,7 @@
 	    Delete_Chunk(AutoUsr->disk, AutoUsr);
 	if (AutoHome != NULL)
 	    Delete_Chunk(AutoHome->disk, AutoHome);
-	record_label_chunks(devs, dev);
+	record_label_chunks(dev);
     }
     return(msg);
 }
@@ -1616,7 +1559,7 @@
 	d = dev->private;
     else
 	d = devs[0]->private;
-    record_label_chunks(devs, dev);
+    record_label_chunks(dev);
     for (i = 0; label_chunk_info[i].c; i++) {
 	Chunk *c1 = label_chunk_info[i].c;
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.sbin/sade/main.c
--- a/head/usr.sbin/sade/main.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/usr.sbin/sade/main.c	Tue Dec 06 20:26:16 2011 +0200
@@ -1,5 +1,5 @@
 /*
- * $FreeBSD$
+ * $FreeBSD: head/usr.sbin/sade/main.c 227944 2011-11-24 18:37:16Z fjoe $
  *
  * Copyright (c) 1995
  *     Jordan Hubbard.  All rights reserved.
@@ -39,8 +39,8 @@
 int
 main(int argc, char **argv)
 {
-    int choice, scroll, curr, max, status;
-    
+    int status;
+
     /* Record name to be able to restart */
     StartName = argv[0];
 
@@ -77,7 +77,9 @@
 
     /* Try to preserve our scroll-back buffer */
     if (OnVTY) {
-	for (curr = 0; curr < 25; curr++)
+        int i;
+
+	for (i = 0; i < 25; i++)
 	    putchar('\n');
     }
     /* Move stderr aside */
@@ -105,10 +107,9 @@
     }
 
     /* Begin user dialog at outer menu */
-    dialog_clear();
+    dlg_clear();
     while (1) {
-	choice = scroll = curr = max = 0;
-	dmenuOpen(&MenuMain, &choice, &scroll, &curr, &max, FALSE);
+	dmenuOpen(&MenuMain);
 	if (getpid() != 1
 	    || !msgNoYes("Are you sure you wish to exit?")
 	    )
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.sbin/sade/menus.c
--- a/head/usr.sbin/sade/menus.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/usr.sbin/sade/menus.c	Tue Dec 06 20:26:16 2011 +0200
@@ -29,7 +29,7 @@
 
 #ifndef lint
 static const char rcsid[] =
-  "$FreeBSD$";
+  "$FreeBSD: head/usr.sbin/sade/menus.c 227944 2011-11-24 18:37:16Z fjoe $";
 #endif
 
 #include "sade.h"
@@ -42,18 +42,18 @@
  */
 
 DMenu MenuDiskDevices = {
-    DMENU_CHECKLIST_TYPE | DMENU_SELECTION_RETURNS,
+    DMENU_NORMAL_TYPE | DMENU_SELECTION_RETURNS,
     "Select Drive(s)",
-    "Please select the drive, or drives, on which you wish to perform\n"
-    "this operation.  If you are attempting to install a boot partition\n"
+    "Please select the drive on which you wish to perform this\n"
+    "operation.  If you are attempting to install a boot partition\n"
     "on a drive other than the first one or have multiple operating\n"
     "systems on your machine, you will have the option to install a boot\n"
     "manager later.  To select a drive, use the arrow keys to move to it\n"
-    "and press [SPACE] or [ENTER].  To de-select it, press it again.\n\n"
+    "and press [SPACE] or [ENTER].\n\n"
     "Use [TAB] to get to the buttons and leave this menu.",
     "Press F1 for important information regarding disk geometry!",
     "drives",
-    { { NULL, NULL, NULL, NULL, NULL, NULL, 0, 0, 0, 0 } },
+    { { NULL, NULL, NULL } },
 };
 
 DMenu MenuMain = {
@@ -62,12 +62,12 @@
     "This is a utility for partitioning and/or labelling your disks.",
     "DISKUTIL",
     "main",
-    { 
+    {
 #ifdef WITH_SLICES
-      { "1 Partition",		"Managing disk partitions",	NULL, diskPartitionEditor, NULL, NULL, 0, 0, 0, 0 },
+      { "1 Partition",		"Managing disk partitions",	diskPartitionEditor },
 #endif
-      { "2 Label",		"Label allocated disk partitions",	NULL, diskLabelEditor, NULL, NULL, 0, 0, 0, 0 },
-      { NULL, NULL, NULL, NULL, NULL, NULL, 0, 0, 0, 0 }
+      { "2 Label",		"Label allocated disk partitions",	diskLabelEditor },
+      { NULL, NULL, NULL }
     },
 };
 
@@ -75,22 +75,20 @@
 #ifdef PC98
 /* IPL type menu */
 DMenu MenuIPLType = {
-    DMENU_NORMAL_TYPE | DMENU_SELECTION_RETURNS,
+    DMENU_RADIO_TYPE | DMENU_SELECTION_RETURNS,
     "overwrite me",		/* will be disk specific label */
     "If you want a FreeBSD Boot Manager, select \"BootMgr\".  If you would\n"
     "prefer your Boot Manager to remain untouched then select \"None\".\n\n",
     "Press F1 to read about drive setup",
     "drives",
-    { { "BootMgr",	"Install the FreeBSD Boot Manager",
-	dmenuRadioCheck, dmenuSetValue, NULL, &BootMgr, 0, 0, 0, 0 },
-      { "None",		"Leave the IPL untouched",
-	dmenuRadioCheck, dmenuSetValue, NULL, &BootMgr, '(', '*', ')', 1 },
-      { NULL, NULL, NULL, NULL, NULL, NULL, 0, 0, 0, 0 } },
+    { { "BootMgr",	"Install the FreeBSD Boot Manager", NULL },
+      { "None",		"Leave the IPL untouched", NULL },
+      { NULL, NULL, NULL } },
 };
 #else
 /* MBR type menu */
 DMenu MenuMBRType = {
-    DMENU_NORMAL_TYPE | DMENU_SELECTION_RETURNS,
+    DMENU_RADIO_TYPE | DMENU_SELECTION_RETURNS,
     "overwrite me",		/* will be disk specific label */
     "FreeBSD comes with a boot manager that allows you to easily\n"
     "select between FreeBSD and any other operating systems on your machine\n"
@@ -99,18 +97,13 @@
     "to do so (limitations in the PC BIOS usually prevent this otherwise).\n"
     "If you have other operating systems installed and would like a choice when\n"
     "booting, choose \"BootMgr\". If you would prefer to keep your existing\n"
-    "boot manager, select \"None\".\n\n",
+    "boot manager, select \"None\".\n",
     "",
     "drives",
-    { { "Standard",	"Install a standard MBR (non-interactive boot manager)",
-	dmenuRadioCheck, dmenuSetValue, NULL, &BootMgr, '(', '*', ')', 1 },
-      { "BootMgr",	"Install the FreeBSD boot manager",
-	dmenuRadioCheck, dmenuSetValue, NULL, &BootMgr, '(', '*', ')', 0 },
-      { "None",		"Do not install a boot manager",
-	dmenuRadioCheck, dmenuSetValue, NULL, &BootMgr, '(', '*', ')', 2 },
-      { NULL, NULL, NULL, NULL, NULL, NULL, 0, 0, 0, 0 } }
+    { { "Standard",	"Install a standard MBR (non-interactive boot manager)", NULL },
+      { "BootMgr",	"Install the FreeBSD boot manager", NULL },
+      { "None",		"Do not install a boot manager", NULL },
+      { NULL, NULL, NULL } }
 };
 #endif /* PC98 */
 #endif /* __i386__ */
-
-
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.sbin/sade/misc.c
--- a/head/usr.sbin/sade/misc.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/usr.sbin/sade/misc.c	Tue Dec 06 20:26:16 2011 +0200
@@ -1,7 +1,7 @@
 /*
  * Miscellaneous support routines..
  *
- * $FreeBSD: head/usr.sbin/sade/misc.c 227903 2011-11-23 19:11:03Z fjoe $
+ * $FreeBSD: head/usr.sbin/sade/misc.c 228175 2011-12-01 09:01:51Z fjoe $
  *
  * Copyright (c) 1995
  *	Jordan Hubbard.  All rights reserved.
@@ -31,7 +31,6 @@
  *
  */
 
-#include "sade.h"
 #include <ctype.h>
 #include <unistd.h>
 #include <sys/stat.h>
@@ -47,6 +46,8 @@
 #include <sys/disklabel.h>
 #include <fs/msdosfs/msdosfsmount.h>
 
+#include "sade.h"
+
 /* Quick check to see if a file is readable */
 Boolean
 file_readable(char *fname)
@@ -217,3 +218,209 @@
     delwin(w);
 }
 
+static int
+xdialog_count_rows(const char *p)
+{
+	int rows = 0;
+
+	while ((p = strchr(p, '\n')) != NULL) {
+		p++;
+		if (*p == '\0')
+			break;
+		rows++;
+	}
+
+	return rows ? rows : 1;
+}
+
+static int
+xdialog_count_columns(const char *p)
+{
+	int len;
+	int max_len = 0;
+	const char *q;
+
+	for (; (q = strchr(p, '\n')) != NULL; p = q + 1) {
+		len = q - p;
+		max_len = MAX(max_len, len);
+	}
+
+	len = strlen(p);
+	max_len = MAX(max_len, len);
+	return max_len;
+}
+
+int
+xdialog_menu(const char *title, const char *cprompt, int height, int width,
+	     int menu_height, int item_no, dialogMenuItem *ditems)
+{
+	int i, result, choice = 0;
+	DIALOG_LISTITEM *listitems;
+	DIALOG_VARS save_vars;
+
+	dlg_save_vars(&save_vars);
+
+	/* initialize list items */
+	listitems = dlg_calloc(DIALOG_LISTITEM, item_no + 1);
+	assert_ptr(listitems, "xdialog_menu");
+	for (i = 0; i < item_no; i++) {
+		listitems[i].name = ditems[i].prompt;
+		listitems[i].text = ditems[i].title;
+	}
+
+	/* calculate height */
+	if (height < 0)
+		height = xdialog_count_rows(cprompt) + menu_height + 4 + 2;
+	if (height > LINES)
+		height = LINES;
+
+	/* calculate width */
+	if (width < 0) {
+		int tag_x = 0;
+
+		for (i = 0; i < item_no; i++) {
+			int j, l;
+
+			l = strlen(listitems[i].name);
+			for (j = 0; j < item_no; j++) {
+				int k = strlen(listitems[j].text);
+				tag_x = MAX(tag_x, l + k + 2);
+			}
+		}
+		width = MAX(xdialog_count_columns(cprompt), title != NULL ? xdialog_count_columns(title) : 0);
+		width = MAX(width, tag_x + 4) + 4;
+	}
+	width = MAX(width, 24);
+	if (width > COLS)
+		width = COLS;
+
+	/* show menu */
+	dialog_vars.default_item = listitems[choice].name;
+	result = dlg_menu(title, cprompt, height, width,
+	    menu_height, item_no, listitems, &choice, NULL);
+	switch (result) {
+	case DLG_EXIT_ESC:
+		result = -1;
+		break;
+	case DLG_EXIT_OK:
+		if (ditems[choice].fire != NULL) {
+			int status;
+			WINDOW *save;
+
+			save = savescr();
+			status = ditems[choice].fire(ditems + choice);
+			restorescr(save);
+		}
+		result = 0;
+		break;
+	case DLG_EXIT_CANCEL:
+	default:
+		result = 1;
+		break;
+	}
+
+	free(listitems);
+	dlg_restore_vars(&save_vars);
+	return result;
+}
+
+int
+xdialog_radiolist(const char *title, const char *cprompt, int height, int width,
+		  int menu_height, int item_no, dialogMenuItem *ditems)
+{
+	int i, result, choice = 0;
+	DIALOG_LISTITEM *listitems;
+	DIALOG_VARS save_vars;
+
+	dlg_save_vars(&save_vars);
+
+	/* initialize list items */
+	listitems = dlg_calloc(DIALOG_LISTITEM, item_no + 1);
+	assert_ptr(listitems, "xdialog_menu");
+	for (i = 0; i < item_no; i++) {
+		listitems[i].name = ditems[i].prompt;
+		listitems[i].text = ditems[i].title;
+		listitems[i].state = i == choice;
+	}
+
+	/* calculate height */
+	if (height < 0)
+		height = xdialog_count_rows(cprompt) + menu_height + 4 + 2;
+	if (height > LINES)
+		height = LINES;
+
+	/* calculate width */
+	if (width < 0) {
+		int check_x = 0;
+
+		for (i = 0; i < item_no; i++) {
+			int j, l;
+
+			l = strlen(listitems[i].name);
+			for (j = 0; j < item_no; j++) {
+				int k = strlen(listitems[j].text);
+				check_x = MAX(check_x, l + k + 6);
+			}
+		}
+		width = MAX(xdialog_count_columns(cprompt), title != NULL ? xdialog_count_columns(title) : 0);
+		width = MAX(width, check_x + 4) + 4;
+	}
+	width = MAX(width, 24);
+	if (width > COLS)
+		width = COLS;
+
+	/* show menu */
+	dialog_vars.default_item = listitems[choice].name;
+	result = dlg_checklist(title, cprompt, height, width,
+	    menu_height, item_no, listitems, NULL, FLAG_RADIO, &choice);
+	switch (result) {
+	case DLG_EXIT_ESC:
+		result = -1;
+		break;
+	case DLG_EXIT_OK:
+		if (ditems[choice].fire != NULL) {
+			int status;
+			WINDOW *save;
+
+			save = savescr();
+			status = ditems[choice].fire(ditems + choice);
+			restorescr(save);
+		}
+		result = 0;
+		break;
+	case DLG_EXIT_CANCEL:
+	default:
+		result = 1;
+		break;
+	}
+
+	/* save result */
+	if (result == 0)
+		dlg_add_result(listitems[choice].name);
+	free(listitems);
+	dlg_restore_vars(&save_vars);
+	return result;
+}
+
+int
+xdialog_msgbox(const char *title, const char *cprompt,
+	       int height, int width, int pauseopt)
+{
+	/* calculate height */
+	if (height < 0)
+		height = 2 + xdialog_count_rows(cprompt) + 2 + !!pauseopt;
+	if (height > LINES)
+		height = LINES;
+
+	/* calculate width */
+	if (width < 0) {
+		width = title != NULL ? xdialog_count_columns(title) : 0;
+		width = MAX(width, xdialog_count_columns(cprompt)) + 4;
+	}
+	if (pauseopt)
+		width = MAX(width, 10);
+	if (width > COLS)
+		width = COLS;
+
+	return dialog_msgbox(title, cprompt, height, width, pauseopt);
+}
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.sbin/sade/msg.c
--- a/head/usr.sbin/sade/msg.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/usr.sbin/sade/msg.c	Tue Dec 06 20:26:16 2011 +0200
@@ -1,5 +1,5 @@
 /*
- * $FreeBSD$
+ * $FreeBSD: head/usr.sbin/sade/msg.c 227944 2011-11-24 18:37:16Z fjoe $
  *
  * Copyright (c) 1995
  *	Jordan Hubbard.  All rights reserved.
@@ -184,13 +184,16 @@
     va_start(args, fmt);
     vsnprintf(errstr, FILENAME_MAX, fmt, args);
     va_end(args);
-    use_helpline(NULL);
-    use_helpfile(NULL);
+    dialog_vars.help_line = NULL;
+    dialog_vars.help_file = NULL;
     if (OnVTY) {
 	ioctl(0, VT_ACTIVATE, 1);
 	msgInfo(NULL);
     }
-    dialog_notify(errstr);
+    dialog_vars.help_line = "Press Enter or Space";
+    xdialog_msgbox("Message", errstr, -1, -1, 1);
+    dialog_vars.help_line = NULL;
+
     restorescr(w);
 }
 
@@ -205,11 +208,11 @@
     va_start(args, fmt);
     vsnprintf(errstr, FILENAME_MAX, fmt, args);
     va_end(args);
-    use_helpline(NULL);
-    use_helpfile(NULL);
+    dialog_vars.help_line = NULL;
+    dialog_vars.help_file = NULL;
     if (isDebug())
 	msgDebug("Notify: %s\n", errstr);
-    dialog_msgbox(NULL, errstr, -1, -1, 0);
+    xdialog_msgbox(NULL, errstr, -1, -1, 0);
 }
 
 /* Put up a message in a popup yes/no box and return 0 for YES, 1 for NO */
@@ -225,8 +228,8 @@
     va_start(args, fmt);
     vsnprintf(errstr, FILENAME_MAX, fmt, args);
     va_end(args);
-    use_helpline(NULL);
-    use_helpfile(NULL);
+    dialog_vars.help_line = NULL;
+    dialog_vars.help_file = NULL;
     if (OnVTY) {
 	ioctl(0, VT_ACTIVATE, 1);	/* Switch back */
 	msgInfo(NULL);
@@ -246,20 +249,24 @@
     char *errstr;
     int ret;
     WINDOW *w = savescr();
-    
+    DIALOG_VARS save_vars;
+
     errstr = (char *)alloca(FILENAME_MAX);
     va_start(args, fmt);
     vsnprintf(errstr, FILENAME_MAX, fmt, args);
     va_end(args);
-    use_helpline(NULL);
-    use_helpfile(NULL);
+    dialog_vars.help_line = NULL;
+    dialog_vars.help_file = NULL;
     if (OnVTY) {
 	ioctl(0, VT_ACTIVATE, 1);	/* Switch back */
 	msgInfo(NULL);
     }
     if (variable_get(VAR_NONINTERACTIVE))
 	return 1;	/* If non-interactive, return NO all the time */
-    ret = dialog_noyes("User Confirmation Requested", errstr, -1, -1);
+    dlg_save_vars(&save_vars);
+    dialog_vars.defaultno = TRUE;
+    ret = dialog_yesno("User Confirmation Requested", errstr, -1, -1);
+    dlg_restore_vars(&save_vars);
     restorescr(w);
     return ret;
 }
@@ -278,8 +285,8 @@
     va_start(args, fmt);
     vsnprintf(errstr, FILENAME_MAX, fmt, args);
     va_end(args);
-    use_helpline(NULL);
-    use_helpfile(NULL);
+    dialog_vars.help_line = NULL;
+    dialog_vars.help_file = NULL;
     if (buf)
 	SAFE_STRCPY(input_buffer, buf);
     else
@@ -288,10 +295,10 @@
 	ioctl(0, VT_ACTIVATE, 1);	/* Switch back */
 	msgInfo(NULL);
     }
-    rval = dialog_inputbox("Value Required", errstr, -1, -1, input_buffer);
+    rval = dialog_inputbox("Value Required", errstr, -1, -1, input_buffer, 0);
     restorescr(w);
     if (!rval)
-	return input_buffer;
+	return dialog_vars.input_result;
     else
 	return NULL;
 }
@@ -325,12 +332,12 @@
     va_start(args, fmt);
     vsnprintf(errstr, FILENAME_MAX, fmt, args);
     va_end(args);
-    use_helpline(NULL);
-    use_helpfile(NULL);
+    dialog_vars.help_line = NULL;
+    dialog_vars.help_file = NULL;
     msgDebug("Notify: %s\n", errstr);
-    dialog_clear_norefresh();
+    dlg_clear();
     sleep(2);
-    dialog_msgbox(NULL, errstr, -1, -1, 0);
+    xdialog_msgbox(NULL, errstr, -1, -1, 0);
     restorescr(w);
 }
 
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.sbin/sade/sade.h
--- a/head/usr.sbin/sade/sade.h	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/usr.sbin/sade/sade.h	Tue Dec 06 20:26:16 2011 +0200
@@ -25,7 +25,7 @@
  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  *
- * $FreeBSD: head/usr.sbin/sade/sade.h 227903 2011-11-23 19:11:03Z fjoe $
+ * $FreeBSD: head/usr.sbin/sade/sade.h 227944 2011-11-24 18:37:16Z fjoe $
  */
 
 #ifndef _SADE_H_INCLUDE
@@ -130,10 +130,25 @@
 typedef struct disk Disk;
 typedef struct chunk Chunk;
 
+/* special return codes for `fire' actions */
+#define DITEM_STATUS(flag)	((flag) & 0x0000FFFF)
+#define DITEM_SUCCESS		0
+#define DITEM_FAILURE		1
+
+/* flags - returned in upper 16 bits of return status */
+#define DITEM_LEAVE_MENU	(1 << 16)
+#define DITEM_RESTORE		(1 << 19)
+
+/* for use in describing more exotic behaviors */
+typedef struct _dmenu_item {
+    char *prompt;
+    char *title;
+    int (*fire)(struct _dmenu_item *self);
+} dialogMenuItem;
+
 /* Bitfields for menu options */
 #define DMENU_NORMAL_TYPE	0x1     /* Normal dialog menu           */
 #define DMENU_RADIO_TYPE	0x2     /* Radio dialog menu            */
-#define DMENU_CHECKLIST_TYPE	0x4     /* Multiple choice menu         */
 #define DMENU_SELECTION_RETURNS 0x8     /* Immediate return on item selection */
 
 typedef struct _dmenu {
@@ -184,7 +199,6 @@
     char *description;
     char *devname;
     DeviceType type;
-    Boolean enabled;
     Boolean (*init)(struct _device *dev);
     FILE * (*get)(struct _device *dev, char *file, Boolean probe);
     void (*shutdown)(struct _device *dev);
@@ -301,16 +315,8 @@
 extern void	command_shell_add(char *key, const char *fmt, ...) __printflike(2, 3);
 extern void	command_func_add(char *key, commandFunc func, void *data);
 
-/* config.c */
-extern void	configEnvironmentRC_conf(void);
-extern void	configRC_conf(void);
-extern int	configFstab(dialogMenuItem *self);
-extern int	configRC(dialogMenuItem *self);
-extern int	configWriteRC_conf(dialogMenuItem *self);
-
 /* devices.c */
-extern DMenu	*deviceCreateMenu(DMenu *menu, DeviceType type, int (*hook)(dialogMenuItem *d),
-				  int (*check)(dialogMenuItem *d));
+extern DMenu	*deviceCreateMenu(DMenu *menu, DeviceType type, int (*hook)(dialogMenuItem *d));
 extern void	deviceGetAll(void);
 extern void	deviceReset(void);
 extern void	deviceRescan(void);
@@ -318,7 +324,7 @@
 extern Device	**deviceFindDescr(char *name, char *desc, DeviceType class);
 extern int	deviceCount(Device **devs);
 extern Device	*new_device(char *name);
-extern Device	*deviceRegister(char *name, char *desc, char *devicename, DeviceType type, Boolean enabled,
+extern Device	*deviceRegister(char *name, char *desc, char *devicename, DeviceType type,
 				Boolean (*init)(Device *mediadev),
 				FILE * (*get)(Device *dev, char *file, Boolean probe),
 				void (*shutDown)(Device *mediadev),
@@ -332,8 +338,7 @@
 extern void	diskPartition(Device *dev);
 extern int	diskPartitionEditor(dialogMenuItem *self);
 #endif
-extern int	diskPartitionWrite(dialogMenuItem *self);
-extern int	diskGetSelectCount(Device ***devs);
+extern int	diskPartitionWrite(Device *dev);
 
 /* dispatch.c */
 extern int	dispatchCommand(char *command);
@@ -342,22 +347,8 @@
 extern int	dispatch_load_file(dialogMenuItem *self);
 
 /* dmenu.c */
-extern int	dmenuDisplayFile(dialogMenuItem *tmp);
-extern int	dmenuSubmenu(dialogMenuItem *tmp);
-extern int	dmenuSystemCommand(dialogMenuItem *tmp);
-extern int	dmenuSystemCommandBox(dialogMenuItem *tmp);
-extern int	dmenuExit(dialogMenuItem *tmp);
-extern int	dmenuISetVariable(dialogMenuItem *tmp);
-extern int	dmenuSetVariable(dialogMenuItem *tmp);
-extern int	dmenuSetVariables(dialogMenuItem *tmp);
-extern int	dmenuToggleVariable(dialogMenuItem *tmp);
-extern int	dmenuSetFlag(dialogMenuItem *tmp);
 extern int	dmenuSetValue(dialogMenuItem *tmp);
-extern Boolean	dmenuOpen(DMenu *menu, int *choice, int *bscroll, int *curr, int *max, Boolean buttons);
-extern Boolean	dmenuOpenSimple(DMenu *menu, Boolean buttons);
-extern int	dmenuVarCheck(dialogMenuItem *item);
-extern int	dmenuVarsCheck(dialogMenuItem *item);
-extern int	dmenuFlagCheck(dialogMenuItem *item);
+extern Boolean	dmenuOpen(DMenu *menu);
 extern int	dmenuRadioCheck(dialogMenuItem *item);
 
 /* dos.c */
@@ -373,7 +364,7 @@
 extern Boolean	checkLabels(Boolean whinge);
 extern int	installCommit(dialogMenuItem *self);
 extern int	installCustomCommit(dialogMenuItem *self);
-extern int	installFilesystems(dialogMenuItem *self);
+extern int	installFilesystems(Device *dev);
 extern int	installVarDefaults(dialogMenuItem *self);
 extern void	installEnvironment(void);
 extern Boolean	copySelf(void);
@@ -383,7 +374,7 @@
 
 /* label.c */
 extern int	diskLabelEditor(dialogMenuItem *self);
-extern int	diskLabelCommit(dialogMenuItem *self);
+extern int	diskLabelCommit(Device *dev);
 
 /* misc.c */
 extern Boolean	file_readable(char *fname);
@@ -399,6 +390,15 @@
 extern void	restorescr(WINDOW *w);
 extern char	*sstrncpy(char *dst, const char *src, int size);
 
+extern int	xdialog_menu(const char *title, const char *cprompt,
+			     int height, int width, int menu_height,
+			     int item_no, dialogMenuItem *ditems);
+extern int	xdialog_radiolist(const char *title, const char *cprompt,
+				  int height, int width, int menu_height,
+				  int item_no, dialogMenuItem *ditems);
+extern int	xdialog_msgbox(const char *title, const char *cprompt,
+			       int height, int width, int pauseopt);
+
 /* msg.c */
 extern Boolean	isDebug(void);
 extern void	msgInfo(const char *fmt, ...) __printf0like(1, 2);
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.sbin/sade/system.c
--- a/head/usr.sbin/sade/system.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/usr.sbin/sade/system.c	Tue Dec 06 20:26:16 2011 +0200
@@ -1,5 +1,5 @@
 /*
- * $FreeBSD$
+ * $FreeBSD: head/usr.sbin/sade/system.c 227944 2011-11-24 18:37:16Z fjoe $
  *
  * Jordan Hubbard
  *
@@ -11,7 +11,6 @@
  * Heck, get him completely drunk and send me pictures! :-)
  */
 
-#include "sade.h"
 #include <signal.h>
 #include <termios.h>
 #include <sys/param.h>
@@ -24,6 +23,7 @@
 #include <sys/sysctl.h>
 #include <ufs/ufs/ufsmount.h>
 
+#include "sade.h"
 
 /* Where we stick our temporary expanded doc file */
 #define	DOC_TMP_DIR	"/tmp/.doc"
@@ -56,8 +56,8 @@
 }
 
 static dialogMenuItem intrmenu[] = {
-    { "Restart", "Restart the program", NULL, intr_restart, NULL, NULL, 0, 0, 0, 0 },
-    { "Continue", "Continue without restarting", NULL, intr_continue, NULL, NULL, 0, 0, 0, 0 },
+    { "Restart", "Restart the program", intr_restart },
+    { "Continue", "Continue without restarting", intr_continue },
 };
 
 
@@ -66,15 +66,15 @@
 {
     WINDOW *save = savescr();
 
-    use_helpline(NULL);
-    use_helpfile(NULL);
+    dialog_vars.help_line = NULL;
+    dialog_vars.help_file = NULL;
     if (OnVTY) {
         ioctl(0, VT_ACTIVATE, 1);       /* Switch back */
         msgInfo(NULL);
     }
-    (void)dialog_menu("Installation interrupt",
+    (void)xdialog_menu("Installation interrupt",
 		     "Do you want to abort the installation?",
-		     -1, -1, 2, -2, intrmenu, NULL, NULL, NULL);
+		     -1, -1, 2, 2, intrmenu);
     restorescr(save);
 }
 
@@ -120,7 +120,7 @@
     }
 
     /* XXX - libdialog has particularly bad return value checking */
-    init_dialog();
+    init_dialog(stdin, stdout);
 
     /* If we haven't crashed I guess dialog is running ! */
     DialogActive = TRUE;
@@ -146,8 +146,7 @@
     struct termios foo;
     WINDOW *w = savescr();
 
-    dialog_clear();
-    dialog_update();
+    dlg_clear();
     end_dialog();
     DialogActive = FALSE;
     if (tcgetattr(0, &foo) != -1) {
@@ -173,8 +172,7 @@
 {
 
     oldW  = savescr();
-    dialog_clear();
-    dialog_update();
+    dlg_clear();
     end_dialog();
     DialogActive = FALSE;
 }
@@ -195,19 +193,18 @@
     char buf[FILENAME_MAX];
     int ret = 0;
     WINDOW *w = savescr();
-    
-		printf("zzz");
+
     fname = systemHelpFile(file, buf);
     if (!fname) {
 	snprintf(buf, FILENAME_MAX, "The %s file is not provided on this particular floppy image.", file);
-	use_helpfile(NULL);
-	use_helpline(NULL);
-	dialog_mesgbox("Sorry!", buf, -1, -1);
+	dialog_vars.help_line = NULL;
+	dialog_vars.help_file = NULL;
+	xdialog_msgbox("Sorry!", buf, -1, -1, 1);
 	ret = 1;
     }
     else {
-	use_helpfile(NULL);
-	use_helpline(NULL);
+	dialog_vars.help_line = NULL;
+	dialog_vars.help_file = NULL;
 	dialog_textbox(file, fname, LINES, COLS);
     }
     restorescr(w);
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.sbin/tzsetup/Makefile
--- a/head/usr.sbin/tzsetup/Makefile	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/usr.sbin/tzsetup/Makefile	Tue Dec 06 20:26:16 2011 +0200
@@ -1,13 +1,13 @@
-# $FreeBSD$
+# $FreeBSD: head/usr.sbin/tzsetup/Makefile 227934 2011-11-24 13:24:06Z fjoe $
 
 PROG=	tzsetup
 MAN=	tzsetup.8
 
-CFLAGS+= -I${.CURDIR}/../../gnu/lib/libodialog -I.
+CFLAGS+= -I${.CURDIR}/../../contrib/dialog -I.
 
 WARNS?=	3
 
-DPADD=	${LIBODIALOG} ${LIBNCURSES}
-LDADD=	-lodialog -lncurses
+DPADD=	${LIBDIALOG} ${LIBNCURSESW} ${LIBM}
+LDADD=	-ldialog -lncursesw -lm
 
 .include <bsd.prog.mk>
diff -r 167f7ed19c6d -r 4aee9df9e1ae head/usr.sbin/tzsetup/tzsetup.c
--- a/head/usr.sbin/tzsetup/tzsetup.c	Tue Dec 06 20:03:07 2011 +0200
+++ b/head/usr.sbin/tzsetup/tzsetup.c	Tue Dec 06 20:26:16 2011 +0200
@@ -33,9 +33,8 @@
  */
 
 #include <sys/cdefs.h>
-__FBSDID("$FreeBSD: head/usr.sbin/tzsetup/tzsetup.c 227011 2011-11-02 04:21:20Z dougb $");
+__FBSDID("$FreeBSD: head/usr.sbin/tzsetup/tzsetup.c 228176 2011-12-01 09:02:57Z fjoe $");
 
-#include <dialog.h>
 #include <err.h>
 #include <errno.h>
 #include <stdio.h>
@@ -49,6 +48,8 @@
 #include <sys/queue.h>
 #include <sys/stat.h>
 
+#include <dialog.h>
+
 #define	_PATH_ZONETAB		"/usr/share/zoneinfo/zone.tab"
 #define	_PATH_ISO3166		"/usr/share/misc/iso3166"
 #define	_PATH_ZONEINFO		"/usr/share/zoneinfo"
@@ -56,8 +57,130 @@
 #define	_PATH_DB		"/var/db/zoneinfo"
 #define	_PATH_WALL_CMOS_CLOCK	"/etc/wall_cmos_clock"
 
+/* special return codes for `fire' actions */
+#define DITEM_FAILURE           1
+
+/* flags - returned in upper 16 bits of return status */
+#define DITEM_LEAVE_MENU        (1 << 16)
+#define DITEM_RECREATE          (1 << 18)
+
+/* for use in describing more exotic behaviors */
+typedef struct dialogMenuItem {
+	char *prompt;
+	char *title;
+	int (*fire)(struct dialogMenuItem *self);
+	void *data;
+} dialogMenuItem;
+
+static int
+xdialog_count_rows(const char *p)
+{
+	int rows = 0;
+
+	while ((p = strchr(p, '\n')) != NULL) {
+		p++;
+		if (*p == '\0')
+			break;
+		rows++;
+	}
+
+	return rows ? rows : 1;
+}
+
+static int
+xdialog_count_columns(const char *p)
+{
+	int len;
+	int max_len = 0;
+	const char *q;
+
+	for (; (q = strchr(p, '\n')) != NULL; p = q + 1) {
+		len = q - p;
+		max_len = MAX(max_len, len);
+	}
+
+	len = strlen(p);
+	max_len = MAX(max_len, len);
+	return max_len;
+}
+
+static int
+xdialog_menu(const char *title, const char *cprompt, int height, int width,
+	     int menu_height, int item_no, dialogMenuItem *ditems)
+{
+	int i, result, choice = 0;
+	DIALOG_LISTITEM *listitems;
+	DIALOG_VARS save_vars;
+
+	dlg_save_vars(&save_vars);
+
+	/* initialize list items */
+	listitems = dlg_calloc(DIALOG_LISTITEM, item_no + 1);
+	assert_ptr(listitems, "xdialog_menu");
+	for (i = 0; i < item_no; i++) {
+		listitems[i].name = ditems[i].prompt;
+		listitems[i].text = ditems[i].title;
+	}
+
+	/* calculate height */
+	if (height < 0)
+		height = xdialog_count_rows(cprompt) + menu_height + 4 + 2;
+	if (height > LINES)
+		height = LINES;
+
+	/* calculate width */
+	if (width < 0) {
+		int tag_x = 0;
+
+		for (i = 0; i < item_no; i++) {
+			int j, l;
+
+			l = strlen(listitems[i].name);
+			for (j = 0; j < item_no; j++) {
+				int k = strlen(listitems[j].text);
+				tag_x = MAX(tag_x, l + k + 2);
+			}
+		}
+		width = MAX(xdialog_count_columns(cprompt), title != NULL ? xdialog_count_columns(title) : 0);
+		width = MAX(width, tag_x + 4) + 4;
+	}
+	width = MAX(width, 24);
+	if (width > COLS)
+		width = COLS;
+
+again:
+	dialog_vars.default_item = listitems[choice].name;
+	result = dlg_menu(title, cprompt, height, width,
+	    menu_height, item_no, listitems, &choice, NULL);
+	switch (result) {
+	case DLG_EXIT_ESC:
+		result = -1;
+		break;
+	case DLG_EXIT_OK:
+		if (ditems[choice].fire != NULL) {
+			int status;
+
+			status = ditems[choice].fire(ditems + choice);
+			if (status & DITEM_RECREATE) {
+				dlg_clear();
+				goto again;
+			}
+		}
+		result = 0;
+		break;
+	case DLG_EXIT_CANCEL:
+	default:
+		result = 1;
+		break;
+	}
+
+	free(listitems);
+	dlg_restore_vars(&save_vars);
+	return result;
+}
+
 static char	path_zonetab[MAXPATHLEN], path_iso3166[MAXPATHLEN],
-		path_zoneinfo[MAXPATHLEN], path_localtime[MAXPATHLEN], 
+		path_zoneinfo[MAXPATHLEN], path_localtime[MAXPATHLEN],
 		path_db[MAXPATHLEN], path_wall_cmos_clock[MAXPATHLEN];
 
 static int reallydoit = 1;
@@ -77,8 +200,6 @@
 struct continent {
 	dialogMenuItem *menu;
 	int		nitems;
-	int		ch;
-	int		sc;
 };
 
 static struct continent	africa, america, antarctica, arctic, asia, atlantic;
@@ -98,7 +219,7 @@
 	{ "Europe",	&europe },
 	{ "Indian",	&indian },
 	{ "Pacific",	&pacific },
-	{ "UTC", 	&utc }
+	{ "UTC",	&utc }
 };
 
 static struct continent_items {
@@ -134,7 +255,7 @@
 	int		rv;
 
 	if (strcmp(continent->title, "UTC") == 0)
-	        return set_zone_utc();	
+	        return set_zone_utc();
 
 	/* Short cut -- if there's only one country, don't post a menu. */
 	if (contp->nitems == 1)
@@ -152,8 +273,8 @@
 	}
 
 	menulen = contp->nitems < 16 ? contp->nitems : 16;
-	rv = dialog_menu(title, prompt, -1, -1, menulen, -contp->nitems,
-	    contp->menu, 0, &contp->ch, &contp->sc);
+	rv = xdialog_menu(title, prompt, -1, -1, menulen, contp->nitems,
+	    contp->menu);
 	if (rv == 0)
 		return (DITEM_LEAVE_MENU);
 	return (DITEM_RECREATE);
@@ -266,7 +387,7 @@
 	if (tlc[0] < 'A' || tlc[0] > 'Z' || tlc[1] < 'A' || tlc[1] > 'Z')
 		errx(1, "%s:%d: country code `%s' invalid", path_zonetab,
 		    lineno, tlc);
-	
+
 	cp = &countries[CODE2INT(tlc)];
 	if (cp->name == 0)
 		errx(1, "%s:%d: country code `%s' unknown", path_zonetab,
@@ -280,7 +401,7 @@
 		zp = malloc(sizeof(*zp));
 		if (zp == 0)
 			errx(1, "malloc(%zu)", sizeof(*zp));
-		
+
 		if (cp->nzones == 0)
 			TAILQ_INIT(&cp->zones);
 
@@ -451,9 +572,7 @@
 			memset(dmi, 0, sizeof(*dmi));
 			asprintf(&dmi->prompt, "%d", ++cp->continent->nitems);
 			dmi->title = cp->name;
-			dmi->checked = 0;
 			dmi->fire = set_zone_whole_country;
-			dmi->selected = 0;
 			dmi->data = cp;
 		} else {
 			cp->submenu = malloc(cp->nzones * sizeof(*dmi));
@@ -466,9 +585,7 @@
 				memset(dmi, 0, sizeof(*dmi));
 				asprintf(&dmi->prompt, "%d", ++cp->nzones);
 				dmi->title = zp->descr;
-				dmi->checked = 0;
 				dmi->fire = set_zone_multi;
-				dmi->selected = 0;
 				dmi->data = zp;
 
 				for (zp2 = TAILQ_FIRST(&cp->zones);
@@ -482,9 +599,7 @@
 				memset(dmi, 0, sizeof(*dmi));
 				asprintf(&dmi->prompt, "%d", ++cont->nitems);
 				dmi->title = cp->name;
-				dmi->checked = 0;
 				dmi->fire = set_zone_menu;
-				dmi->selected = 0;
 				dmi->data = cp;
 			}
 		}
@@ -503,8 +618,8 @@
 	snprintf(prompt, sizeof(prompt),
 	    "Select a zone which observes the same time as your locality.");
 	menulen = cp->nzones < 16 ? cp->nzones : 16;
-	rv = dialog_menu(title, prompt, -1, -1, menulen, -cp->nzones,
-	    cp->submenu, 0, 0, 0);
+	rv = xdialog_menu(title, prompt, -1, -1, menulen, cp->nzones,
+	    cp->submenu);
 	if (rv != 0)
 		return (DITEM_RECREATE);
 	return (DITEM_LEAVE_MENU);
@@ -515,7 +630,7 @@
 {
 	if (!confirm_zone(NULL))
 		return (DITEM_FAILURE | DITEM_RECREATE);
-		
+
 	return (install_zoneinfo_file(NULL));
 }
 
@@ -559,7 +674,7 @@
 				     "Could not delete %s: %s", path_localtime,
 				     strerror(errno));
 				if (usedialog)
-					dialog_mesgbox(title, prompt, 8, 72);
+					dialog_msgbox(title, prompt, 8, 72, 1);
 				else
 					fprintf(stderr, "%s\n", prompt);
 
@@ -571,7 +686,7 @@
 				     "Could not delete %s: %s", path_db,
 				     strerror(errno));
 				if (usedialog)
-					dialog_mesgbox(title, prompt, 8, 72);
+					dialog_msgbox(title, prompt, 8, 72, 1);
 				else
 					fprintf(stderr, "%s\n", prompt);
 
@@ -579,7 +694,7 @@
 			}
 			return (DITEM_LEAVE_MENU);
 		}
-		
+
 		if (copymode) {
 			fd1 = open(zoneinfo_file, O_RDONLY, 0);
 			if (fd1 < 0) {
@@ -588,7 +703,7 @@
 				    "Could not open %s: %s", zoneinfo_file,
 				    strerror(errno));
 				if (usedialog)
-					dialog_mesgbox(title, prompt, 8, 72);
+					dialog_msgbox(title, prompt, 8, 72, 1);
 				else
 					fprintf(stderr, "%s\n", prompt);
 				return (DITEM_FAILURE | DITEM_RECREATE);
@@ -603,7 +718,7 @@
 				    "Could not open %s: %s",
 				    path_localtime, strerror(errno));
 				if (usedialog)
-					dialog_mesgbox(title, prompt, 8, 72);
+					dialog_msgbox(title, prompt, 8, 72, 1);
 				else
 					fprintf(stderr, "%s\n", prompt);
 				return (DITEM_FAILURE | DITEM_RECREATE);
@@ -619,7 +734,7 @@
 				    "Error copying %s to %s %s", zoneinfo_file,
 				    path_localtime, strerror(errno));
 				if (usedialog)
-					dialog_mesgbox(title, prompt, 8, 72);
+					dialog_msgbox(title, prompt, 8, 72, 1);
 				else
 					fprintf(stderr, "%s\n", prompt);
 				/* Better to leave none than a corrupt one. */
@@ -635,7 +750,7 @@
 				    "Cannot access %s: %s", zoneinfo_file,
 				    strerror(errno));
 				if (usedialog)
-					dialog_mesgbox(title, prompt, 8, 72);
+					dialog_msgbox(title, prompt, 8, 72, 1);
 				else
 					fprintf(stderr, "%s\n", prompt);
 				return (DITEM_FAILURE | DITEM_RECREATE);
@@ -648,7 +763,7 @@
 				    path_localtime, zoneinfo_file,
 				    strerror(errno));
 				if (usedialog)
-					dialog_mesgbox(title, prompt, 8, 72);
+					dialog_msgbox(title, prompt, 8, 72, 1);
 				else
 					fprintf(stderr, "%s\n", prompt);
 				return (DITEM_FAILURE | DITEM_RECREATE);
@@ -667,7 +782,7 @@
 		    "Created symbolic link from %s to %s", zoneinfo_file,
 		    path_localtime);
 	if (usedialog)
-		dialog_mesgbox(title, prompt, 8, 72);
+		dialog_msgbox(title, prompt, 8, 72, 1);
 	else
 		fprintf(stderr, "%s\n", prompt);
 #endif
@@ -701,7 +816,7 @@
 	time_t		t = time(0);
 	struct tm	*tm;
 	int		rv;
-	
+
 	setenv("TZ", filename == NULL ? "" : filename, 1);
 	tzset();
 	tm = localtime(&t);
@@ -748,12 +863,6 @@
 	exit(1);
 }
 
-#if defined(__sparc64__)
-#define	DIALOG_UTC	dialog_yesno
-#else
-#define	DIALOG_UTC	dialog_noyes
-#endif
-
 int
 main(int argc, char **argv)
 {
@@ -858,15 +967,24 @@
 		/* FALLTHROUGH */
 	}
 
-	init_dialog();
+	init_dialog(stdin, stdout);
 	if (skiputc == 0) {
+		DIALOG_VARS save_vars;
+		int yesno;
+
 		snprintf(title, sizeof(title),
 		    "Select local or UTC (Greenwich Mean Time) clock");
 		snprintf(prompt, sizeof(prompt),
 		    "Is this machine's CMOS clock set to UTC?  "
 		    "If it is set to local time,\n"
 		    "or you don't know, please choose NO here!");
-		if (!DIALOG_UTC(title, prompt, 7, 72)) {
+		dlg_save_vars(&save_vars);
+#if !defined(__sparc64__)
+		dialog_vars.defaultno = TRUE;
+#endif
+		yesno = dialog_yesno(title, prompt, 7, 73);
+		dlg_restore_vars(&save_vars);
+		if (!yesno) {
 			if (reallydoit)
 				unlink(path_wall_cmos_clock);
 		} else {
@@ -882,7 +1000,7 @@
 				close(fd);
 			}
 		}
-		dialog_clear_norefresh();
+		dlg_clear();
 	}
 	if (optind == argc - 1) {
 		snprintf(title, sizeof(title), "Default timezone provided");
@@ -890,18 +1008,18 @@
 		    "\nUse the default `%s' zone?", argv[optind]);
 		if (!dialog_yesno(title, prompt, 7, 72)) {
 			rv = install_zoneinfo_file(argv[optind]);
-			dialog_clear();
+			dlg_clear();
 			end_dialog();
 			exit(rv & ~DITEM_LEAVE_MENU);
 		}
-		dialog_clear_norefresh();
+		dlg_clear();
 	}
 	snprintf(title, sizeof(title), "Time Zone Selector");
 	snprintf(prompt, sizeof(prompt), "Select a region");
-	dialog_menu(title, prompt, -1, -1, NCONTINENTS, -NCONTINENTS,
-	    continents, 0, NULL, NULL);
+	xdialog_menu(title, prompt, -1, -1, NCONTINENTS, NCONTINENTS,
+	    continents);
 
-	dialog_clear();
+	dlg_clear();
 	end_dialog();
 	return (0);
 }


More information about the Zrouter-src-freebsd mailing list