summary refs log tree commit diff
path: root/pkgs/os-specific
diff options
context:
space:
mode:
Diffstat (limited to 'pkgs/os-specific')
-rw-r--r--pkgs/os-specific/darwin/cctools-port/default.nix64
-rw-r--r--pkgs/os-specific/darwin/cctools-port/ld-ignore-rpath-link.patch16
-rw-r--r--pkgs/os-specific/darwin/cctools-port/ld-rpath-nonfinal.patch31
-rw-r--r--pkgs/os-specific/darwin/htop/default.nix21
-rw-r--r--pkgs/os-specific/darwin/maloader/default.nix36
-rw-r--r--pkgs/os-specific/darwin/native-x11-and-opengl/default.nix6
-rw-r--r--pkgs/os-specific/darwin/opencflite/default.nix21
-rw-r--r--pkgs/os-specific/darwin/otool/default.nix2
-rw-r--r--pkgs/os-specific/darwin/xcode/default.nix52
-rw-r--r--pkgs/os-specific/darwin/xcode/gcc-fix-enum-attributes.patch13
-rw-r--r--pkgs/os-specific/gnu/default.nix2
-rw-r--r--pkgs/os-specific/gnu/hurd/default.nix2
-rw-r--r--pkgs/os-specific/gnu/libpthread/default.nix2
-rw-r--r--pkgs/os-specific/gnu/mach/default.nix2
-rw-r--r--pkgs/os-specific/gnu/mig/default.nix2
-rw-r--r--pkgs/os-specific/gnu/smbfs/default.nix2
-rw-r--r--pkgs/os-specific/gnu/unionfs/default.nix2
-rw-r--r--pkgs/os-specific/linux/acpi-call/default.nix14
-rw-r--r--pkgs/os-specific/linux/acpi/default.nix10
-rw-r--r--pkgs/os-specific/linux/acpid/default.nix6
-rw-r--r--pkgs/os-specific/linux/acpitool/default.nix2
-rw-r--r--pkgs/os-specific/linux/afuse/default.nix3
-rw-r--r--pkgs/os-specific/linux/alienfx/default.nix39
-rw-r--r--pkgs/os-specific/linux/alienfx/unistd.patch12
-rw-r--r--pkgs/os-specific/linux/alsa-lib/default.nix33
-rw-r--r--pkgs/os-specific/linux/alsa-lib/mips-atomic.patch39
-rw-r--r--pkgs/os-specific/linux/alsa-oss/default.nix13
-rw-r--r--pkgs/os-specific/linux/alsa-plugins/default.nix21
-rw-r--r--pkgs/os-specific/linux/alsa-utils/default.nix19
-rw-r--r--pkgs/os-specific/linux/apparmor/default.nix8
-rw-r--r--pkgs/os-specific/linux/atheros/0.9.4.nix28
-rw-r--r--pkgs/os-specific/linux/ati-drivers/builder.sh5
-rw-r--r--pkgs/os-specific/linux/ati-drivers/default.nix38
-rw-r--r--pkgs/os-specific/linux/ati-drivers/gentoo-patches.patch330
-rw-r--r--pkgs/os-specific/linux/ati-drivers/patch-samples.patch26
-rw-r--r--pkgs/os-specific/linux/atop/default.nix3
-rw-r--r--pkgs/os-specific/linux/audit/default.nix28
-rw-r--r--pkgs/os-specific/linux/aufs-util/2.nix41
-rw-r--r--pkgs/os-specific/linux/aufs-util/3.nix40
-rw-r--r--pkgs/os-specific/linux/aufs/2.nix43
-rw-r--r--pkgs/os-specific/linux/aufs/3.nix44
-rw-r--r--pkgs/os-specific/linux/autofs/autofs-v5.nix10
-rw-r--r--pkgs/os-specific/linux/autofs/create-patches-v5.sh4
-rw-r--r--pkgs/os-specific/linux/autofs/patches-v5.nix31
-rw-r--r--pkgs/os-specific/linux/batman-adv/batctl.nix6
-rw-r--r--pkgs/os-specific/linux/batman-adv/default.nix12
-rw-r--r--pkgs/os-specific/linux/bbswitch/default.nix18
-rw-r--r--pkgs/os-specific/linux/blcr/default.nix14
-rw-r--r--pkgs/os-specific/linux/bluez/bluez5.nix11
-rw-r--r--pkgs/os-specific/linux/broadcom-sta-v6/default.nix49
-rw-r--r--pkgs/os-specific/linux/broadcom-sta-v6/license.patch13
-rw-r--r--pkgs/os-specific/linux/broadcom-sta/cfg80211_ibss_joined-channel-parameter.patch17
-rw-r--r--pkgs/os-specific/linux/broadcom-sta/default.nix56
-rw-r--r--pkgs/os-specific/linux/broadcom-sta/license.patch9
-rw-r--r--pkgs/os-specific/linux/broadcom-sta/linux-2.6.39.patch11
-rw-r--r--pkgs/os-specific/linux/broadcom-sta/linux-3.2.patch13
-rw-r--r--pkgs/os-specific/linux/broadcom-sta/linux-3.4.patch12
-rw-r--r--pkgs/os-specific/linux/broadcom-sta/linux-recent.patch (renamed from pkgs/os-specific/linux/broadcom-sta-v6/linux-recent.patch)0
-rw-r--r--pkgs/os-specific/linux/broadcom-sta/makefile.patch16
-rw-r--r--pkgs/os-specific/linux/busybox/default.nix15
-rw-r--r--pkgs/os-specific/linux/can-utils/default.nix24
-rw-r--r--pkgs/os-specific/linux/checkpolicy/default.nix9
-rw-r--r--pkgs/os-specific/linux/checksec/0001-attempt-to-modprobe-config-before-checking-kernel.patch27
-rw-r--r--pkgs/os-specific/linux/checksec/default.nix42
-rw-r--r--pkgs/os-specific/linux/cifs-utils/default.nix6
-rw-r--r--pkgs/os-specific/linux/cifs-utils/find-systemd-ask-password-via-path.patch22
-rw-r--r--pkgs/os-specific/linux/conky/default.nix64
-rw-r--r--pkgs/os-specific/linux/conky/stdbool.patch12
-rw-r--r--pkgs/os-specific/linux/consoletools/default.nix11
-rw-r--r--pkgs/os-specific/linux/conspy/default.nix8
-rw-r--r--pkgs/os-specific/linux/cpufrequtils/default.nix11
-rw-r--r--pkgs/os-specific/linux/cpufrequtils/remove-pot-creation-date.patch24
-rw-r--r--pkgs/os-specific/linux/cpupower/default.nix42
-rw-r--r--pkgs/os-specific/linux/criu/default.nix38
-rw-r--r--pkgs/os-specific/linux/cryptodev/default.nix14
-rw-r--r--pkgs/os-specific/linux/cryptsetup/default.nix6
-rw-r--r--pkgs/os-specific/linux/disk-indicator/default.nix36
-rw-r--r--pkgs/os-specific/linux/dmidecode/default.nix7
-rw-r--r--pkgs/os-specific/linux/drbd/default.nix4
-rw-r--r--pkgs/os-specific/linux/dstat/default.nix2
-rw-r--r--pkgs/os-specific/linux/e1000e/default.nix14
-rw-r--r--pkgs/os-specific/linux/exmap/default.nix56
-rw-r--r--pkgs/os-specific/linux/ffado/default.nix1
-rw-r--r--pkgs/os-specific/linux/firejail/default.nix37
-rw-r--r--pkgs/os-specific/linux/firejail/default.upstream3
-rw-r--r--pkgs/os-specific/linux/firmware/b43-firmware-cutter/default.nix5
-rw-r--r--pkgs/os-specific/linux/firmware/b43-firmware/5.1.138.nix1
-rw-r--r--pkgs/os-specific/linux/firmware/firmware-linux-nonfree/default.nix37
-rw-r--r--pkgs/os-specific/linux/frandom/default.nix17
-rw-r--r--pkgs/os-specific/linux/fuse/default.nix8
-rw-r--r--pkgs/os-specific/linux/gogoclient/default.nix2
-rw-r--r--pkgs/os-specific/linux/google-authenticator/default.nix10
-rw-r--r--pkgs/os-specific/linux/gradm/default.nix52
-rw-r--r--pkgs/os-specific/linux/guvcview/default.nix39
-rw-r--r--pkgs/os-specific/linux/hdparm/default.nix4
-rw-r--r--pkgs/os-specific/linux/hibernate/default.nix8
-rw-r--r--pkgs/os-specific/linux/hostapd/default.nix5
-rw-r--r--pkgs/os-specific/linux/htop/default.nix8
-rw-r--r--pkgs/os-specific/linux/hwdata/builder.sh5
-rw-r--r--pkgs/os-specific/linux/hwdata/default.nix19
-rw-r--r--pkgs/os-specific/linux/i7z/default.nix5
-rw-r--r--pkgs/os-specific/linux/i810switch/default.nix2
-rw-r--r--pkgs/os-specific/linux/ifenslave/default.nix26
-rw-r--r--pkgs/os-specific/linux/iomelt/default.nix25
-rw-r--r--pkgs/os-specific/linux/iotop/default.nix6
-rw-r--r--pkgs/os-specific/linux/iproute/default.nix12
-rw-r--r--pkgs/os-specific/linux/iproute/no-werror.patch12
-rw-r--r--pkgs/os-specific/linux/ipsec-tools/default.nix7
-rw-r--r--pkgs/os-specific/linux/iptables/default.nix19
-rw-r--r--pkgs/os-specific/linux/iscsitarget/default.nix27
-rw-r--r--pkgs/os-specific/linux/iw/default.nix4
-rw-r--r--pkgs/os-specific/linux/iwlwifi/default.nix40
-rw-r--r--pkgs/os-specific/linux/jujuutils/default.nix2
-rw-r--r--pkgs/os-specific/linux/kernel-headers/3.14.nix (renamed from pkgs/os-specific/linux/kernel-headers/2.6.28.nix)38
-rw-r--r--pkgs/os-specific/linux/kernel-headers/3.7.nix6
-rw-r--r--pkgs/os-specific/linux/kernel-headers/default.nix25
-rw-r--r--pkgs/os-specific/linux/kernel/apparmor-patches/3.2/0001-AppArmor-compatibility-patch-for-v5-network-controll.patch553
-rw-r--r--pkgs/os-specific/linux/kernel/apparmor-patches/3.2/0002-AppArmor-compatibility-patch-for-v5-interface.patch391
-rw-r--r--pkgs/os-specific/linux/kernel/apparmor-patches/3.2/0003-AppArmor-Allow-dfa-backward-compatibility-with-broke.patch69
-rw-r--r--pkgs/os-specific/linux/kernel/apparmor-patches/3.4/0001-UBUNTU-SAUCE-AppArmor-Add-profile-introspection-file.patch264
-rw-r--r--pkgs/os-specific/linux/kernel/apparmor-patches/3.4/0002-UBUNTU-SAUCE-AppArmor-basic-networking-rules.patch603
-rw-r--r--pkgs/os-specific/linux/kernel/apparmor-patches/3.4/0003-UBUNTU-SAUCE-apparmor-Add-the-ability-to-mediate-mou.patch957
-rw-r--r--pkgs/os-specific/linux/kernel/builder.sh149
-rw-r--r--pkgs/os-specific/linux/kernel/common-config.nix119
-rw-r--r--pkgs/os-specific/linux/kernel/generate-config.pl5
-rw-r--r--pkgs/os-specific/linux/kernel/generic.nix157
-rw-r--r--pkgs/os-specific/linux/kernel/grsec-path.patch17
-rw-r--r--pkgs/os-specific/linux/kernel/linux-3.0.nix12
-rw-r--r--pkgs/os-specific/linux/kernel/linux-3.10.nix5
-rw-r--r--pkgs/os-specific/linux/kernel/linux-3.12.nix7
-rw-r--r--pkgs/os-specific/linux/kernel/linux-3.14.nix (renamed from pkgs/os-specific/linux/kernel/linux-3.11.nix)7
-rw-r--r--pkgs/os-specific/linux/kernel/linux-3.15.nix17
-rw-r--r--pkgs/os-specific/linux/kernel/linux-3.16.nix (renamed from pkgs/os-specific/linux/kernel/linux-3.9.nix)7
-rw-r--r--pkgs/os-specific/linux/kernel/linux-3.2.nix23
-rw-r--r--pkgs/os-specific/linux/kernel/linux-3.4.nix16
-rw-r--r--pkgs/os-specific/linux/kernel/linux-rpi-3.6.nix2
-rw-r--r--pkgs/os-specific/linux/kernel/linux-testing.nix23
-rw-r--r--pkgs/os-specific/linux/kernel/manual-config.nix332
-rw-r--r--pkgs/os-specific/linux/kernel/patches.nix124
-rw-r--r--pkgs/os-specific/linux/kernel/perf.diff18
-rw-r--r--pkgs/os-specific/linux/kernel/perf.nix11
-rw-r--r--pkgs/os-specific/linux/kernel/sec_perm-2.6.24.patch16
-rw-r--r--pkgs/os-specific/linux/keyutils/default.nix29
-rw-r--r--pkgs/os-specific/linux/klibc/default.nix78
-rw-r--r--pkgs/os-specific/linux/klibc/no-reinstall-kernel-headers.patch11
-rw-r--r--pkgs/os-specific/linux/kmod-blacklist-ubuntu/default.nix32
-rw-r--r--pkgs/os-specific/linux/kmod/default.nix4
-rw-r--r--pkgs/os-specific/linux/kmod/module-dir.patch46
-rw-r--r--pkgs/os-specific/linux/kmscon/default.nix50
-rw-r--r--pkgs/os-specific/linux/ktap/default.nix32
-rw-r--r--pkgs/os-specific/linux/latencytop/default.nix2
-rw-r--r--pkgs/os-specific/linux/ldm/default.nix42
-rw-r--r--pkgs/os-specific/linux/libaio/default.nix9
-rw-r--r--pkgs/os-specific/linux/libatasmart/default.nix6
-rw-r--r--pkgs/os-specific/linux/libcap-ng/default.nix2
-rw-r--r--pkgs/os-specific/linux/libnl/3.2.19.nix20
-rw-r--r--pkgs/os-specific/linux/libnl/default.nix4
-rw-r--r--pkgs/os-specific/linux/libselinux/default.nix26
-rw-r--r--pkgs/os-specific/linux/libsemanage/default.nix8
-rw-r--r--pkgs/os-specific/linux/libsepol/default.nix16
-rw-r--r--pkgs/os-specific/linux/libvolume_id/default.nix6
-rw-r--r--pkgs/os-specific/linux/lm-sensors/default.nix4
-rw-r--r--pkgs/os-specific/linux/lockdep/default.nix29
-rw-r--r--pkgs/os-specific/linux/lsiutil/default.nix2
-rw-r--r--pkgs/os-specific/linux/lsscsi/default.nix6
-rw-r--r--pkgs/os-specific/linux/lttng-modules/default.nix14
-rw-r--r--pkgs/os-specific/linux/lvm2/default.nix6
-rw-r--r--pkgs/os-specific/linux/lxc/default.nix10
-rw-r--r--pkgs/os-specific/linux/mcelog/default.nix4
-rw-r--r--pkgs/os-specific/linux/mdadm/default.nix9
-rw-r--r--pkgs/os-specific/linux/mdadm/udev.patch20
-rw-r--r--pkgs/os-specific/linux/microcode/converter.nix2
-rw-r--r--pkgs/os-specific/linux/microcode/intel.nix6
-rw-r--r--pkgs/os-specific/linux/musl/default.nix24
-rw-r--r--pkgs/os-specific/linux/ndiswrapper/default.nix18
-rw-r--r--pkgs/os-specific/linux/ndiswrapper/no-sbin.patch12
-rw-r--r--pkgs/os-specific/linux/ndiswrapper/prefix.patch66
-rw-r--r--pkgs/os-specific/linux/net-tools/default.nix2
-rw-r--r--pkgs/os-specific/linux/netatop/default.nix14
-rw-r--r--pkgs/os-specific/linux/nfs-utils/default.nix2
-rwxr-xr-xpkgs/os-specific/linux/nvidia-x11/builder-legacy.sh7
-rwxr-xr-xpkgs/os-specific/linux/nvidia-x11/builder-legacy304.sh7
-rwxr-xr-xpkgs/os-specific/linux/nvidia-x11/builder.sh77
-rw-r--r--pkgs/os-specific/linux/nvidia-x11/default.nix37
-rw-r--r--pkgs/os-specific/linux/nvidia-x11/legacy173.nix14
-rw-r--r--pkgs/os-specific/linux/nvidia-x11/legacy304.nix14
-rw-r--r--pkgs/os-specific/linux/nvidia-x11/legacy96.nix44
-rw-r--r--pkgs/os-specific/linux/nvidia-x11/nvidia-drivers-linux-3.11-incremental.patch25
-rw-r--r--pkgs/os-specific/linux/nvidia-x11/version-test.patch19
-rw-r--r--pkgs/os-specific/linux/nvidiabl/default.nix25
-rw-r--r--pkgs/os-specific/linux/open-iscsi/default.nix16
-rw-r--r--pkgs/os-specific/linux/otpw/default.nix4
-rw-r--r--pkgs/os-specific/linux/pam/CVE-2014-2583.patch49
-rw-r--r--pkgs/os-specific/linux/pam/default.nix8
-rw-r--r--pkgs/os-specific/linux/pam_krb5/default.nix1
-rw-r--r--pkgs/os-specific/linux/pam_usb/default.nix2
-rw-r--r--pkgs/os-specific/linux/pax-utils/default.nix24
-rw-r--r--pkgs/os-specific/linux/paxctl/default.nix28
-rw-r--r--pkgs/os-specific/linux/pcmciautils/default.nix2
-rw-r--r--pkgs/os-specific/linux/plymouth/default.nix51
-rw-r--r--pkgs/os-specific/linux/pm-utils/default.nix2
-rw-r--r--pkgs/os-specific/linux/pmount/default.nix8
-rw-r--r--pkgs/os-specific/linux/pmtools/default.nix2
-rw-r--r--pkgs/os-specific/linux/policycoreutils/default.nix14
-rw-r--r--pkgs/os-specific/linux/pommed/default.nix3
-rw-r--r--pkgs/os-specific/linux/powertop/default.nix8
-rw-r--r--pkgs/os-specific/linux/procps-ng/default.nix6
-rw-r--r--pkgs/os-specific/linux/procps/watch.nix29
-rw-r--r--pkgs/os-specific/linux/psmisc/0001-Typo-in-fuser-makes-M-on-all-the-time.patch44
-rw-r--r--pkgs/os-specific/linux/psmisc/default.nix7
-rw-r--r--pkgs/os-specific/linux/psmouse-alps/default.nix12
-rw-r--r--pkgs/os-specific/linux/radeontools/default.nix4
-rw-r--r--pkgs/os-specific/linux/reptyr/default.nix12
-rw-r--r--pkgs/os-specific/linux/rfkill/default.nix8
-rwxr-xr-xpkgs/os-specific/linux/rfkill/rfkill-hook.sh6
-rw-r--r--pkgs/os-specific/linux/rfkill/udev.nix4
-rw-r--r--pkgs/os-specific/linux/rtkit/default.nix12
-rw-r--r--pkgs/os-specific/linux/sdparm/default.nix6
-rw-r--r--pkgs/os-specific/linux/sepolgen/default.nix4
-rw-r--r--pkgs/os-specific/linux/setools/default.nix33
-rw-r--r--pkgs/os-specific/linux/setools/ftbfs-invalid-operands-of-types.patch15
-rw-r--r--pkgs/os-specific/linux/shadow/default.nix13
-rw-r--r--pkgs/os-specific/linux/spl/const.patch13
-rw-r--r--pkgs/os-specific/linux/spl/default.nix22
-rw-r--r--pkgs/os-specific/linux/spl/git.nix46
-rw-r--r--pkgs/os-specific/linux/sysdig/default.nix43
-rw-r--r--pkgs/os-specific/linux/sysdig/default.upstream8
-rw-r--r--pkgs/os-specific/linux/syslinux/default.nix32
-rw-r--r--pkgs/os-specific/linux/sysstat/default.nix2
-rw-r--r--pkgs/os-specific/linux/systemd/default.nix57
-rw-r--r--pkgs/os-specific/linux/systemd/fixes.patch3217
-rw-r--r--pkgs/os-specific/linux/systemd/libc-bug-accept4-arm.patch81
-rw-r--r--pkgs/os-specific/linux/tp_smapi/default.nix12
-rw-r--r--pkgs/os-specific/linux/tunctl/default.nix2
-rw-r--r--pkgs/os-specific/linux/uclibc/default.nix2
-rw-r--r--pkgs/os-specific/linux/udisks/1-default.nix2
-rw-r--r--pkgs/os-specific/linux/udisks/2-default.nix6
-rw-r--r--pkgs/os-specific/linux/udisks/cve-2014-0004.patch82
-rw-r--r--pkgs/os-specific/linux/upower/0.99.nix51
-rw-r--r--pkgs/os-specific/linux/upower/default.nix43
-rw-r--r--pkgs/os-specific/linux/usermount/default.nix28
-rw-r--r--pkgs/os-specific/linux/util-linux/default.nix12
-rw-r--r--pkgs/os-specific/linux/v4l-utils/default.nix4
-rw-r--r--pkgs/os-specific/linux/v4l2loopback/default.nix32
-rw-r--r--pkgs/os-specific/linux/v86d/default.nix6
-rw-r--r--pkgs/os-specific/linux/wis-go7007/default.nix17
-rw-r--r--pkgs/os-specific/linux/wpa_supplicant/default.nix16
-rw-r--r--pkgs/os-specific/linux/wpa_supplicant/gui.nix2
-rw-r--r--pkgs/os-specific/linux/wvdial/default.nix2
-rw-r--r--pkgs/os-specific/linux/x86info/default.nix2
-rw-r--r--pkgs/os-specific/linux/xf86-input-mtrack/default.nix5
-rw-r--r--pkgs/os-specific/linux/xf86-input-multitouch/default.nix5
-rw-r--r--pkgs/os-specific/linux/xf86-input-wacom/default.nix4
-rw-r--r--pkgs/os-specific/linux/xf86-video-nouveau/default.nix37
-rw-r--r--pkgs/os-specific/linux/zfs/default.nix25
-rw-r--r--pkgs/os-specific/linux/zfs/git.nix54
-rw-r--r--pkgs/os-specific/windows/cygwin-setup/default.nix46
-rw-r--r--pkgs/os-specific/windows/jom/default.nix2
-rw-r--r--pkgs/os-specific/windows/mingw-w64/default.nix28
-rw-r--r--pkgs/os-specific/windows/pthread-w32/default.nix2
260 files changed, 8729 insertions, 3038 deletions
diff --git a/pkgs/os-specific/darwin/cctools-port/default.nix b/pkgs/os-specific/darwin/cctools-port/default.nix
new file mode 100644
index 00000000000..cdc259c1e2a
--- /dev/null
+++ b/pkgs/os-specific/darwin/cctools-port/default.nix
@@ -0,0 +1,64 @@
+{ stdenv, cross, fetchurl, autoconf, automake, libtool
+, libcxx, llvm, clang, openssl, libuuid
+, maloader, makeWrapper, xctoolchain
+}:
+
+stdenv.mkDerivation rec {
+  name = "cctools-port-${version}";
+  version = "845";
+
+  src = fetchurl {
+    url = "https://github.com/tpoechtrager/cctools-port/archive/"
+        + "cctools-${version}-ld64-136-1.tar.gz";
+    sha256 = "06pg6h1g8avgx4j6cfykdpggf490li796gzhhyqn27jsagli307i";
+  };
+
+  buildInputs = [
+    autoconf automake libtool libcxx llvm clang openssl libuuid makeWrapper
+  ];
+
+  patches = [ ./ld-rpath-nonfinal.patch ./ld-ignore-rpath-link.patch ];
+
+  enableParallelBuilding = true;
+
+  postPatch = ''
+    patchShebangs tools
+    sed -i -e 's/which/type -P/' tools/*.sh
+    sed -i -e 's|clang++|& -I${libcxx}/include/c++/v1|' cctools/autogen.sh
+
+    # Workaround for https://www.sourceware.org/bugzilla/show_bug.cgi?id=11157
+    cat > cctools/include/unistd.h <<EOF
+    #ifdef __block
+    #  undef __block
+    #  include_next "unistd.h"
+    #  define __block __attribute__((__blocks__(byref)))
+    #else
+    #  include_next "unistd.h"
+    #endif
+    EOF
+  '';
+
+  preConfigure = ''
+    cd cctools
+    sh autogen.sh
+  '';
+
+  configureFlags = [
+    "CXXFLAGS=-I${libcxx}/include/c++/v1"
+    "--target=${cross.config}"
+  ];
+
+  postInstall = ''
+    for tool in dyldinfo dwarfdump dsymutil; do
+      makeWrapper "${maloader}/bin/ld-mac" "$out/bin/${cross.config}-$tool" \
+        --add-flags "${xctoolchain}/bin/$tool"
+      ln -s "$out/bin/${cross.config}-$tool" "$out/bin/$tool"
+    done
+  '';
+
+  meta = {
+    homepage = "http://www.opensource.apple.com/source/cctools/";
+    description = "Mac OS X Compiler Tools (cross-platform port)";
+    license = stdenv.lib.licenses.apsl20;
+  };
+}
diff --git a/pkgs/os-specific/darwin/cctools-port/ld-ignore-rpath-link.patch b/pkgs/os-specific/darwin/cctools-port/ld-ignore-rpath-link.patch
new file mode 100644
index 00000000000..fc87f69ac32
--- /dev/null
+++ b/pkgs/os-specific/darwin/cctools-port/ld-ignore-rpath-link.patch
@@ -0,0 +1,16 @@
+diff --git a/cctools/ld64/src/ld/Options.cpp b/cctools/ld64/src/ld/Options.cpp
+index 2565518..9250016 100644
+--- a/cctools/ld64/src/ld/Options.cpp
++++ b/cctools/ld64/src/ld/Options.cpp
+@@ -2522,6 +2522,11 @@ void Options::parse(int argc, const char* argv[])
+ 					throw "missing argument to -rpath";
+ 				fRPaths.push_back(path);
+ 			}
++			else if ( strcmp(arg, "-rpath-link") == 0 ) {
++				const char* path = argv[++i];
++				if ( path == NULL )
++					throw "missing argument to -rpath-link";
++			}
+ 			else if ( strcmp(arg, "-read_only_stubs") == 0 ) {
+ 				fReadOnlyx86Stubs = true;
+ 			}
diff --git a/pkgs/os-specific/darwin/cctools-port/ld-rpath-nonfinal.patch b/pkgs/os-specific/darwin/cctools-port/ld-rpath-nonfinal.patch
new file mode 100644
index 00000000000..265d0d30477
--- /dev/null
+++ b/pkgs/os-specific/darwin/cctools-port/ld-rpath-nonfinal.patch
@@ -0,0 +1,31 @@
+diff --git a/cctools/ld64/src/ld/Options.cpp b/cctools/ld64/src/ld/Options.cpp
+index 9250016..91d54ec 100644
+--- a/cctools/ld64/src/ld/Options.cpp
++++ b/cctools/ld64/src/ld/Options.cpp
+@@ -4175,23 +4175,9 @@ void Options::checkIllegalOptionCombinations()
+ 		throw "-r and -dead_strip cannot be used together";
+ 
+ 	// can't use -rpath unless targeting 10.5 or later
+-	if ( fRPaths.size() > 0 ) {
+-		if ( !minOS(ld::mac10_5, ld::iOS_2_0) )
+-			throw "-rpath can only be used when targeting Mac OS X 10.5 or later";
+-		switch ( fOutputKind ) {
+-			case Options::kDynamicExecutable:
+-			case Options::kDynamicLibrary:
+-			case Options::kDynamicBundle:
+-				break;
+-			case Options::kStaticExecutable:
+-			case Options::kObjectFile:
+-			case Options::kDyld:
+-			case Options::kPreload:
+-			case Options::kKextBundle:
+-				throw "-rpath can only be used when creating a dynamic final linked image";
+-		}
+-	}
+-	
++	if ( fRPaths.size() > 0 && !minOS(ld::mac10_5, ld::iOS_2_0) )
++		throw "-rpath can only be used when targeting Mac OS X 10.5 or later";
++
+ 	if ( fPositionIndependentExecutable ) {
+ 		switch ( fOutputKind ) {
+ 			case Options::kDynamicExecutable:
diff --git a/pkgs/os-specific/darwin/htop/default.nix b/pkgs/os-specific/darwin/htop/default.nix
new file mode 100644
index 00000000000..65e8b09db34
--- /dev/null
+++ b/pkgs/os-specific/darwin/htop/default.nix
@@ -0,0 +1,21 @@
+{ fetchurl, stdenv, ncurses, autoconf, automake }:
+
+stdenv.mkDerivation rec {
+  name = "htop-0.8.2.2";
+
+  src = fetchurl {
+    url = "https://github.com/max-horvath/htop-osx/archive/0.8.2.2.tar.gz";
+    sha256 = "0qxibadn2lfqn10a5jmkv8r5ljfs0vaaa4j6psd7ppxa2w6bx5li";
+  };
+
+  buildInputs = [ autoconf automake ncurses ];
+
+  preConfigure = "./autogen.sh";
+
+  meta = {
+    description = "An interactive process viewer for Mac OS X";
+    homepage = "https://github.com/max-horvath/htop-osx";
+    platforms = stdenv.lib.platforms.darwin;
+    maintainers = with stdenv.lib.maintainers; [ joelteon ];
+  };
+}
diff --git a/pkgs/os-specific/darwin/maloader/default.nix b/pkgs/os-specific/darwin/maloader/default.nix
new file mode 100644
index 00000000000..f5bfe890735
--- /dev/null
+++ b/pkgs/os-specific/darwin/maloader/default.nix
@@ -0,0 +1,36 @@
+{ stdenv, fetchgit, opencflite, clang, libcxx }:
+
+stdenv.mkDerivation {
+  name = "maloader-0git";
+
+  src = fetchgit {
+    url = "git://github.com/shinh/maloader.git";
+    rev = "5f220393e0b7b9ad0cf1aba0e89df2b42a1f0442";
+    sha256 = "07j9b7n0grrbxxyn2h8pnk6pa8b370wq5z5zwbds8dlhi7q37rhn";
+  };
+
+  postPatch = ''
+    sed -i \
+      -e '/if.*loadLibMac.*mypath/s|mypath|"'"$out/lib/"'"|' \
+      -e 's|libCoreFoundation\.so|${opencflite}/lib/&|' \
+      ld-mac.cc
+  '';
+
+  NIX_CFLAGS_COMPILE = "-I${libcxx}/include/c++/v1";
+  buildInputs = [ clang libcxx ];
+  buildFlags = [ "USE_LIBCXX=1" "release" ];
+
+  installPhase = ''
+    install -vD libmac.so "$out/lib/libmac.so"
+
+    for bin in extract macho2elf ld-mac; do
+      install -vD "$bin" "$out/bin/$bin"
+    done
+  '';
+
+  meta = {
+    description = "Mach-O loader for Linux";
+    homepage = "https://github.com/shinh/maloader";
+    license = stdenv.lib.licenses.bsd2;
+  };
+}
diff --git a/pkgs/os-specific/darwin/native-x11-and-opengl/default.nix b/pkgs/os-specific/darwin/native-x11-and-opengl/default.nix
index cee03741dce..3844912f6ba 100644
--- a/pkgs/os-specific/darwin/native-x11-and-opengl/default.nix
+++ b/pkgs/os-specific/darwin/native-x11-and-opengl/default.nix
@@ -7,6 +7,10 @@ stdenv.mkDerivation rec {
 
   builder = writeScript "${name}-builder.sh" ''
     /bin/mkdir -p $out
-    /bin/ln -sv /usr/X11/{bin,lib,include,share} $out/
+    /bin/mkdir $out/lib
+    /bin/ln -sv /usr/X11/lib/{*.dylib,X11,xorg} $out/lib
+    /bin/mkdir $out/lib/pkgconfig
+    /bin/ln -sv /usr/X11/lib/pkgconfig/{x*.pc,gl*.pc} $out/lib/pkgconfig
+    /bin/ln -sv /usr/X11/{bin,include,share} $out/
   '';
 }
diff --git a/pkgs/os-specific/darwin/opencflite/default.nix b/pkgs/os-specific/darwin/opencflite/default.nix
new file mode 100644
index 00000000000..a2408bfc5c8
--- /dev/null
+++ b/pkgs/os-specific/darwin/opencflite/default.nix
@@ -0,0 +1,21 @@
+{ stdenv, fetchurl, icu, libuuid, tzdata }:
+
+stdenv.mkDerivation rec {
+  name = "opencflite-${version}";
+  version = "476.19.0";
+
+  src = fetchurl {
+    url = "mirror://sourceforge/opencflite/${name}.tar.gz";
+    sha256 = "0jgmzs0ycl930hmzcvx0ykryik56704yw62w394q1q3xw5kkjn9v";
+  };
+
+  configureFlags = [ "--with-uuid=${libuuid}" ];
+  buildInputs = [ icu tzdata.lib ];
+  enableParallelBuilding = true;
+
+  meta = {
+    description = "Cross platform port of the OS X CoreFoundation";
+    homepage = "http://sourceforge.net/projects/opencflite/";
+    license = stdenv.lib.licenses.apsl20;
+  };
+}
diff --git a/pkgs/os-specific/darwin/otool/default.nix b/pkgs/os-specific/darwin/otool/default.nix
index 671e51542d0..e0793664a9c 100644
--- a/pkgs/os-specific/darwin/otool/default.nix
+++ b/pkgs/os-specific/darwin/otool/default.nix
@@ -24,7 +24,7 @@ stdenv.mkDerivation {
   meta = with stdenv.lib; {
     description = "Object file displaying tool";
     homepage    = https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man1/otool.1.html;
-    license     = with licenses; [ apsl20 gpl2Plus ];
+    # TODO license     = with licenses; [ apsl20 gpl2Plus ];
     maintainers = with maintainers; [ lovek323 ];
     platforms   = platforms.darwin;
 
diff --git a/pkgs/os-specific/darwin/xcode/default.nix b/pkgs/os-specific/darwin/xcode/default.nix
new file mode 100644
index 00000000000..2a48590154e
--- /dev/null
+++ b/pkgs/os-specific/darwin/xcode/default.nix
@@ -0,0 +1,52 @@
+{ stdenv, requireFile, xpwn }:
+
+with stdenv.lib;
+
+let
+  osxVersion = "10.9";
+in stdenv.mkDerivation rec {
+  name = "xcode-${version}";
+  version = "5.1";
+
+  src = requireFile {
+    name = "xcode_${version}.dmg";
+    url = meta.homepage;
+    sha256 = "70bb550cc14eca80b9825f4ae9bfbf7f076bb75777311be428bc30a7eb7a6f7e";
+  };
+
+  phases = [ "unpackPhase" "patchPhase" "installPhase" "fixupPhase" ];
+  outputs = [ "out" "toolchain" ];
+
+
+  unpackCmd = let
+    basePath = "Xcode.app/Contents/Developer/Platforms/MacOSX.platform";
+    sdkPath = "${basePath}/Developer/SDKs";
+  in ''
+    ${xpwn}/bin/dmg extract "$curSrc" main.hfs > /dev/null
+    ${xpwn}/bin/hfsplus main.hfs extractall "${sdkPath}" > /dev/null
+  '';
+
+  setSourceRoot = "sourceRoot=MacOSX${osxVersion}.sdk";
+
+  patches = optional (osxVersion == "10.9") ./gcc-fix-enum-attributes.patch;
+
+  installPhase = ''
+    mkdir -p "$out/share/sysroot"
+    cp -a * "$out/share/sysroot/"
+    ln -s "$out/share/sysroot/usr/lib" "$out/lib"
+    ln -s "$out/share/sysroot/usr/include" "$out/include"
+
+    mkdir -p "$toolchain"
+    pushd "$toolchain"
+    ${xpwn}/bin/hfsplus "$(dirs +1)/../main.hfs" extractall \
+      Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr \
+      > /dev/null
+    popd
+  '';
+
+  meta = {
+    homepage = "https://developer.apple.com/downloads/";
+    description = "Apple's XCode SDK";
+    license = stdenv.lib.licenses.unfree;
+  };
+}
diff --git a/pkgs/os-specific/darwin/xcode/gcc-fix-enum-attributes.patch b/pkgs/os-specific/darwin/xcode/gcc-fix-enum-attributes.patch
new file mode 100644
index 00000000000..1e1895c2894
--- /dev/null
+++ b/pkgs/os-specific/darwin/xcode/gcc-fix-enum-attributes.patch
@@ -0,0 +1,13 @@
+diff --git a/System/Library/Frameworks/Foundation.framework/Headers/NSUserNotification.h b/System/Library/Frameworks/Foundation.framework/Headers/NSUserNotification.h
+index fa0c290..7da7e0c 100644
+--- a/System/Library/Frameworks/Foundation.framework/Headers/NSUserNotification.h
++++ b/System/Library/Frameworks/Foundation.framework/Headers/NSUserNotification.h
+@@ -13,7 +13,7 @@ typedef NS_ENUM(NSInteger, NSUserNotificationActivationType) {
+     NSUserNotificationActivationTypeNone = 0,
+     NSUserNotificationActivationTypeContentsClicked = 1,
+     NSUserNotificationActivationTypeActionButtonClicked = 2,
+-    NSUserNotificationActivationTypeReplied NS_AVAILABLE(10_9, NA) = 3
++    NSUserNotificationActivationTypeReplied = 3
+ } NS_ENUM_AVAILABLE(10_8, NA);
+ 
+ NS_CLASS_AVAILABLE(10_8, NA)
diff --git a/pkgs/os-specific/gnu/default.nix b/pkgs/os-specific/gnu/default.nix
index 27b1cdd3e8a..94bfec0a18e 100644
--- a/pkgs/os-specific/gnu/default.nix
+++ b/pkgs/os-specific/gnu/default.nix
@@ -82,7 +82,7 @@ let
     mig = callPackage ./mig {
       # Build natively, but force use of a 32-bit environment because we're
       # targeting `i586-pc-gnu'.
-      stdenv = (forceSystem "i686-linux").stdenv;
+      stdenv = (forceSystem "i686-linux" "i386").stdenv;
     };
 
     # XXX: Use this one for its `.crossDrv'.  Using the one above from
diff --git a/pkgs/os-specific/gnu/hurd/default.nix b/pkgs/os-specific/gnu/hurd/default.nix
index 0c9059a3008..4bdb6e132fb 100644
--- a/pkgs/os-specific/gnu/hurd/default.nix
+++ b/pkgs/os-specific/gnu/hurd/default.nix
@@ -65,7 +65,7 @@ stdenv.mkDerivation ({
          kernels (such as Linux).
       '';
 
-    license = "GPLv2+";
+    license = stdenv.lib.licenses.gpl2Plus;
 
     homepage = http://www.gnu.org/software/hurd/;
 
diff --git a/pkgs/os-specific/gnu/libpthread/default.nix b/pkgs/os-specific/gnu/libpthread/default.nix
index 3eaa6336ec2..4b16652ba05 100644
--- a/pkgs/os-specific/gnu/libpthread/default.nix
+++ b/pkgs/os-specific/gnu/libpthread/default.nix
@@ -31,7 +31,7 @@ stdenv.mkDerivation ({
   meta = {
     description = "GNU Hurd's libpthread";
 
-    license = "LGPLv2+";
+    license = stdenv.lib.licenses.lgpl2Plus;
 
     maintainers = [ stdenv.lib.maintainers.ludo ];
   };
diff --git a/pkgs/os-specific/gnu/mach/default.nix b/pkgs/os-specific/gnu/mach/default.nix
index 54c6429955b..6d2d20687bc 100644
--- a/pkgs/os-specific/gnu/mach/default.nix
+++ b/pkgs/os-specific/gnu/mach/default.nix
@@ -41,7 +41,7 @@ stdenv.mkDerivation ({
          were added using glue code, i.e., a Linux emulation layer in Mach.
       '';
 
-    license = "GPLv2+";
+    license = stdenv.lib.licenses.gpl2Plus;
 
     homepage = http://www.gnu.org/software/hurd/microkernel/mach/gnumach.html;
 
diff --git a/pkgs/os-specific/gnu/mig/default.nix b/pkgs/os-specific/gnu/mig/default.nix
index 9ee188b0c8c..34426b45d55 100644
--- a/pkgs/os-specific/gnu/mig/default.nix
+++ b/pkgs/os-specific/gnu/mig/default.nix
@@ -42,7 +42,7 @@ stdenv.mkDerivation {
          Mach-based inter-process communication.
       '';
 
-    license = "GPLv2+";
+    license = stdenv.lib.licenses.gpl2Plus;
 
     homepage = http://www.gnu.org/software/hurd/microkernel/mach/mig/gnu_mig.html;
 
diff --git a/pkgs/os-specific/gnu/smbfs/default.nix b/pkgs/os-specific/gnu/smbfs/default.nix
index 4897c0c0af8..6f3d719d816 100644
--- a/pkgs/os-specific/gnu/smbfs/default.nix
+++ b/pkgs/os-specific/gnu/smbfs/default.nix
@@ -37,7 +37,7 @@ stdenv.mkDerivation rec {
 
     homepage = http://www.nongnu.org/hurdextras/;
 
-    license = "GPLv3+";
+    license = stdenv.lib.licenses.gpl3Plus;
 
     maintainers = [ stdenv.lib.maintainers.ludo ];
   };
diff --git a/pkgs/os-specific/gnu/unionfs/default.nix b/pkgs/os-specific/gnu/unionfs/default.nix
index 946e4c0c109..5e2f428130c 100644
--- a/pkgs/os-specific/gnu/unionfs/default.nix
+++ b/pkgs/os-specific/gnu/unionfs/default.nix
@@ -36,7 +36,7 @@ stdenv.mkDerivation rec {
 
     homepage = http://www.gnu.org/software/hurd/hurd/translator/unionfs.html;
 
-    license = "GPLv2+";
+    license = stdenv.lib.licenses.gpl2Plus;
 
     maintainers = [ stdenv.lib.maintainers.ludo ];
   };
diff --git a/pkgs/os-specific/linux/acpi-call/default.nix b/pkgs/os-specific/linux/acpi-call/default.nix
index 9fd8168948d..63c55341b14 100644
--- a/pkgs/os-specific/linux/acpi-call/default.nix
+++ b/pkgs/os-specific/linux/acpi-call/default.nix
@@ -1,23 +1,23 @@
-{ stdenv, fetchgit, kernelDev }:
+{ stdenv, fetchgit, kernel }:
 
 stdenv.mkDerivation {
-  name = "acpi-call-${kernelDev.version}";
+  name = "acpi-call-${kernel.version}";
 
   src = fetchgit {
     url = "git://github.com/mkottman/acpi_call.git";
-    rev = "46dd97e115ddc7219c88b0818c4d5b235162fe6e";
-    sha256 = "1bi0azd7xxhrivjhnmxllj2sfj12br56mxii20mnqdpqwyz0rhni";
+    rev = "ac67445bc75ec4fcf46ceb195fb84d74ad350d51";
+    sha256 = "0jl19irz9x9pxab2qp4z8c3jijv2m30zhmnzi6ygbrisqqlg4c75";
   };
   
   preBuild = ''
     sed -e 's/break/true/' -i examples/turn_off_gpu.sh
     sed -e 's@/bin/bash@.bin/sh@' -i examples/turn_off_gpu.sh
-    sed -e "s@/lib/modules/\$(.*)@${kernelDev}/lib/modules/${kernelDev.modDirVersion}@" -i Makefile
+    sed -e "s@/lib/modules/\$(.*)@${kernel.dev}/lib/modules/${kernel.modDirVersion}@" -i Makefile
   '';
  
   installPhase = ''
-    mkdir -p $out/lib/modules/${kernelDev.modDirVersion}/misc
-    cp acpi_call.ko $out/lib/modules/${kernelDev.modDirVersion}/misc
+    mkdir -p $out/lib/modules/${kernel.modDirVersion}/misc
+    cp acpi_call.ko $out/lib/modules/${kernel.modDirVersion}/misc
     mkdir -p $out/bin
     cp examples/turn_off_gpu.sh $out/bin/test_discrete_video_off.sh
     chmod a+x $out/bin/test_discrete_video_off.sh
diff --git a/pkgs/os-specific/linux/acpi/default.nix b/pkgs/os-specific/linux/acpi/default.nix
index d694a9e5ed2..0fc79922515 100644
--- a/pkgs/os-specific/linux/acpi/default.nix
+++ b/pkgs/os-specific/linux/acpi/default.nix
@@ -2,14 +2,14 @@
 
 stdenv.mkDerivation rec {
   name = "acpi-${version}";
-  version = "1.6";
+  version = "1.7";
 
   src = fetchurl {
     url = "mirror://sourceforge/acpiclient/${version}/${name}.tar.gz";
-    sha256 = "0cawznhkzb51yxa599d1xkw05nklmjrrmd79vmjkkzf4002d4qgd";
+    sha256 = "01ahldvf0gc29dmbd5zi4rrnrw2i1ajnf30sx2vyaski3jv099fp";
   };
 
-  meta = {
+  meta = with stdenv.lib; {
     description = "Show battery status and other ACPI information";
     longDescription = ''
       Linux ACPI client is a small command-line
@@ -18,6 +18,8 @@ stdenv.mkDerivation rec {
       battery and thermal information.
     '';
     homepage = http://sourceforge.net/projects/acpiclient/;
-    license = "GPLv2+";
+    license = stdenv.lib.licenses.gpl2Plus;
+    platforms = platforms.linux;
+    maintainers = maintainers.mornfall;
   };
 }
diff --git a/pkgs/os-specific/linux/acpid/default.nix b/pkgs/os-specific/linux/acpid/default.nix
index 7f3440d8f59..c9d45835cfd 100644
--- a/pkgs/os-specific/linux/acpid/default.nix
+++ b/pkgs/os-specific/linux/acpid/default.nix
@@ -1,11 +1,11 @@
 {stdenv, fetchurl}:
 
 stdenv.mkDerivation rec {
-  name = "acpid-2.0.17";
+  name = "acpid-2.0.22";
 
   src = fetchurl {
-    url = "http://tedfelix.com/linux/${name}.tar.xz";
-    sha256 = "0gksl6z3sb6yyk7bdmldxsrncvprd3rny0i8ggl4m95nvv3x5drn";
+    url = "mirror://sourceforge/acpid2/${name}.tar.xz";
+    sha256 = "0cdbcy5xjdcyp2x6hzgpv6a9vg9bbxmypmfvv1qzgj43897la49x";
   };
 
   preBuild = ''
diff --git a/pkgs/os-specific/linux/acpitool/default.nix b/pkgs/os-specific/linux/acpitool/default.nix
index c7f96206eab..6fc3bbe7c08 100644
--- a/pkgs/os-specific/linux/acpitool/default.nix
+++ b/pkgs/os-specific/linux/acpitool/default.nix
@@ -11,7 +11,7 @@ stdenv.mkDerivation rec {
   meta = {
     description = "A small, convenient command-line ACPI client with a lot of features";
     homepage = http://freeunix.dyndns.org:8000/site2/acpitool.shtml;
-    license = "GPLv2+";
+    license = stdenv.lib.licenses.gpl2Plus;
     maintainers = [ stdenv.lib.maintainers.guibert ];
   };
 }
diff --git a/pkgs/os-specific/linux/afuse/default.nix b/pkgs/os-specific/linux/afuse/default.nix
index 06af0c9228a..70c8f36105c 100644
--- a/pkgs/os-specific/linux/afuse/default.nix
+++ b/pkgs/os-specific/linux/afuse/default.nix
@@ -13,9 +13,8 @@ stdenv.mkDerivation {
   meta = { 
     description = "Automounter in userspace";
     homepage = http://sourceforge.net/projects/afuse;
-    license = "GPL-v2";
+    license = stdenv.lib.licenses.gpl2;
     maintainers = [ stdenv.lib.maintainers.marcweber ];
     platforms = stdenv.lib.platforms.linux;
   };
 }
-
diff --git a/pkgs/os-specific/linux/alienfx/default.nix b/pkgs/os-specific/linux/alienfx/default.nix
new file mode 100644
index 00000000000..93d77819e57
--- /dev/null
+++ b/pkgs/os-specific/linux/alienfx/default.nix
@@ -0,0 +1,39 @@
+{ stdenv, libusb1, fetchgit}:
+
+
+let
+  rev = "85ee5eeaca59a1c92659c3f49b148b0447d78f16";
+in
+
+stdenv.mkDerivation {
+  name = "alienfx-1.0.0";
+  src = fetchgit {
+    inherit rev;
+    url = https://github.com/tibz/alienfx.git;
+
+    sha256 = "47501a3b4e08d39edee4cd829ae24259a7e740b9798db76b846fa872989f8fb1";
+  };
+
+  prePatch = ''
+    substituteInPlace Makefile --replace /usr/ $out/
+    substituteInPlace Makefile --replace "install -o root -g root" "install"
+  '';
+ 
+  patches = [./unistd.patch];
+  buildInputs = [ libusb1 ];
+  makeFlags = "build";
+  preInstall = ''
+    mkdir -p $out/bin
+    mkdir -p $out/man/man1
+  '';
+  installTargets = "install";
+  postInstall = ''cp alienfx.1 $out/man/man1'';
+  
+  meta = {
+    description = "Controls AlienFX lighting";
+    homepage = "https://github.com/tibz/alienfx";
+    maintainers = [stdenv.lib.maintainers.tomberek];
+    platforms = stdenv.lib.platforms.linux;
+  };
+}
+
diff --git a/pkgs/os-specific/linux/alienfx/unistd.patch b/pkgs/os-specific/linux/alienfx/unistd.patch
new file mode 100644
index 00000000000..546a27892f0
--- /dev/null
+++ b/pkgs/os-specific/linux/alienfx/unistd.patch
@@ -0,0 +1,12 @@
+diff --git a/alienfx.cpp b/alienfx.cpp
+index 5981039..aea8992 100644
+--- a/alienfx.cpp
++++ b/alienfx.cpp
+@@ -13,6 +13,7 @@
+ #include <string.h>
+ #include <iostream>
+ #include <libusb-1.0/libusb.h>
++#include <unistd.h>
+ 
+ using namespace std;
+ 
diff --git a/pkgs/os-specific/linux/alsa-lib/default.nix b/pkgs/os-specific/linux/alsa-lib/default.nix
index 26d32594fba..f46e54448b9 100644
--- a/pkgs/os-specific/linux/alsa-lib/default.nix
+++ b/pkgs/os-specific/linux/alsa-lib/default.nix
@@ -1,17 +1,24 @@
 {stdenv, fetchurl}:
 
 stdenv.mkDerivation rec {
-  name = "alsa-lib-1.0.26";
+  name = "alsa-lib-1.0.28";
 
   src = fetchurl {
     urls = [
      "ftp://ftp.alsa-project.org/pub/lib/${name}.tar.bz2"
      "http://alsa.cybermirror.org/lib/${name}.tar.bz2"
     ];
-    sha256 = "0zbfkwqn7ixa71lsna9llq6i2gic540h8r8r0rjdphrwc1hq37wc";
+    sha256 = "0vaafg5q1q1mqcsgin5v7xlmngl3cnbmg5a9xxw0xcz1vn2ln1rw";
   };
 
-  configureFlags = "--disable-xmlto";
+  patches = [
+    /* allow specifying alternatives alsa plugin locations using
+       export ALSA_PLUGIN_DIRS=$(nix-build -A alsaPlugins)/lib/alsa-lib
+       This patch should be improved:
+       See http://thread.gmane.org/gmane.linux.distributions.nixos/3435
+    */
+    ./alsa-plugin-dirs.patch
+  ];
 
   # Fix pcm.h file in order to prevent some compilation bugs
   # 2: see http://stackoverflow.com/questions/3103400/how-to-overcome-u-int8-t-vs-uint8-t-issue-efficiently
@@ -29,7 +36,8 @@ stdenv.mkDerivation rec {
     '';
   };
 
-  meta = {
+  meta = with stdenv.lib; {
+    homepage = http://www.alsa-project.org/;
     description = "ALSA, the Advanced Linux Sound Architecture libraries";
 
     longDescription = ''
@@ -37,20 +45,7 @@ stdenv.mkDerivation rec {
       MIDI functionality to the Linux-based operating system.
     '';
 
-    homepage = http://www.alsa-project.org/;
+    license = licenses.gpl3Plus;
+    platforms = platforms.linux;
   };
-
-  patches = [
-    /* allow specifying alternatives alsa plugin locations using
-       export ALSA_PLUGIN_DIRS=$(nix-build -A alsaPlugins)/lib/alsa-lib
-       This patch should be improved:
-       See http://thread.gmane.org/gmane.linux.distributions.nixos/3435
-    */
-    ./alsa-plugin-dirs.patch
-
-    /* patch provided by larsc on irc.
-       it may be a compiler problem on mips; without this, alsa does not build
-       on mips, because lacks some symbols atomic_add/atomic_sub  */
-    ./mips-atomic.patch
-  ];
 }
diff --git a/pkgs/os-specific/linux/alsa-lib/mips-atomic.patch b/pkgs/os-specific/linux/alsa-lib/mips-atomic.patch
deleted file mode 100644
index 3af7c5d4deb..00000000000
--- a/pkgs/os-specific/linux/alsa-lib/mips-atomic.patch
+++ /dev/null
@@ -1,39 +0,0 @@
-diff --git a/include/iatomic.h b/include/iatomic.h
-index e92dbfd..364bc5c 100644
---- a/include/iatomic.h
-+++ b/include/iatomic.h
-@@ -720,7 +720,7 @@ typedef struct { volatile int counter; } atomic_t;
-  * Atomically adds @i to @v.  Note that the guaranteed useful range
-  * of an atomic_t is only 24 bits.
-  */
--extern __inline__ void atomic_add(int i, atomic_t * v)
-+static __inline__ void atomic_add(int i, atomic_t * v)
- {
- 	unsigned long temp;
- 
-@@ -744,7 +744,7 @@ extern __inline__ void atomic_add(int i, atomic_t * v)
-  * Atomically subtracts @i from @v.  Note that the guaranteed
-  * useful range of an atomic_t is only 24 bits.
-  */
--extern __inline__ void atomic_sub(int i, atomic_t * v)
-+static __inline__ void atomic_sub(int i, atomic_t * v)
- {
- 	unsigned long temp;
- 
-@@ -763,7 +763,7 @@ extern __inline__ void atomic_sub(int i, atomic_t * v)
- /*
-  * Same as above, but return the result value
-  */
--extern __inline__ int atomic_add_return(int i, atomic_t * v)
-+static __inline__ int atomic_add_return(int i, atomic_t * v)
- {
- 	unsigned long temp, result;
- 
-@@ -784,7 +784,7 @@ extern __inline__ int atomic_add_return(int i, atomic_t * v)
- 	return result;
- }
- 
--extern __inline__ int atomic_sub_return(int i, atomic_t * v)
-+static __inline__ int atomic_sub_return(int i, atomic_t * v)
- {
- 	unsigned long temp, result;
diff --git a/pkgs/os-specific/linux/alsa-oss/default.nix b/pkgs/os-specific/linux/alsa-oss/default.nix
index 98bf4374b4f..0d02daebe1d 100644
--- a/pkgs/os-specific/linux/alsa-oss/default.nix
+++ b/pkgs/os-specific/linux/alsa-oss/default.nix
@@ -1,12 +1,14 @@
 {stdenv, fetchurl, alsaLib, gettext, ncurses, libsamplerate}:
 
 stdenv.mkDerivation rec {
-  name = "alsa-oss-1.0.25";
+  name = "alsa-oss-1.0.28";
 
   src = fetchurl {
-    url = "ftp://ftp.alsa-project.org/pub/oss-lib/${name}.tar.bz2";
-    # url = "http://alsa.cybermirror.org/oss-lib/${name}.tar.bz2";
-    sha256 = "ed823b8e42599951d896c1709615d4cf7cb1cb3a7c55c75ccee82e24ccaf28e3";
+    urls = [
+      "ftp://ftp.alsa-project.org/pub/oss-lib/${name}.tar.bz2"
+      "http://alsa.cybermirror.org/oss-lib/${name}.tar.bz2"
+    ];
+    sha256 = "1mbabiywxjjlvdh257j3a0v4vvy69mwwnvc3xlq7pg50i2m2rris";
   };
 
   buildInputs = [ alsaLib ncurses libsamplerate ];
@@ -21,6 +23,7 @@ stdenv.mkDerivation rec {
     '';
 
   meta = {
+    homepage = http://www.alsa-project.org/;
     description = "ALSA, the Advanced Linux Sound Architecture alsa-oss emulation";
 
     longDescription = ''
@@ -28,6 +31,6 @@ stdenv.mkDerivation rec {
       MIDI functionality to the Linux-based operating system.
     '';
 
-    homepage = http://www.alsa-project.org/;
+    platforms = stdenv.lib.platforms.linux;
   };
 }
diff --git a/pkgs/os-specific/linux/alsa-plugins/default.nix b/pkgs/os-specific/linux/alsa-plugins/default.nix
index fb17b47b506..0bb96c343df 100644
--- a/pkgs/os-specific/linux/alsa-plugins/default.nix
+++ b/pkgs/os-specific/linux/alsa-plugins/default.nix
@@ -1,26 +1,27 @@
-{ stdenv, fetchurl, lib, pkgconfig, alsaLib, pulseaudio ? null, jackaudio ? null }:
+{ stdenv, fetchurl, lib, pkgconfig, alsaLib, libogg, pulseaudio ? null, jack2 ? null }:
 
 stdenv.mkDerivation rec {
-  name = "alsa-plugins-1.0.26";
+  name = "alsa-plugins-1.0.28";
 
   src = fetchurl {
     urls = [
       "ftp://ftp.alsa-project.org/pub/plugins/${name}.tar.bz2"
       "http://alsa.cybermirror.org/plugins/${name}.tar.bz2"
     ];
-    sha256 = "07wz3kl6isabk15ddpzz820pqlgvw6q0m7knnbgv9780s8s52l83";
+    sha256 = "081is33afhykb4ysll8s6gh0d6nm1cglslj9ck0disbyl3qqlvs2";
   };
 
+  # ToDo: a52, etc.?
   buildInputs =
-    [ pkgconfig alsaLib ]
-    ++ stdenv.lib.optional (pulseaudio != null) pulseaudio
-    ++ stdenv.lib.optional (jackaudio != null) jackaudio;
+    [ pkgconfig alsaLib libogg ]
+    ++ lib.optional (pulseaudio != null) pulseaudio
+    ++ lib.optional (jack2 != null) jack2;
 
-  meta = { 
+  meta = with lib; {
     description = "Various plugins for ALSA";
     homepage = http://alsa-project.org/;
-    license = "GPL2.1";
-    maintainers = [lib.maintainers.marcweber];
-    platforms = lib.platforms.linux;
+    license = licenses.lgpl21;
+    maintainers = [maintainers.marcweber];
+    platforms = platforms.linux;
   };
 }
diff --git a/pkgs/os-specific/linux/alsa-utils/default.nix b/pkgs/os-specific/linux/alsa-utils/default.nix
index c121b227eee..7ab4a919786 100644
--- a/pkgs/os-specific/linux/alsa-utils/default.nix
+++ b/pkgs/os-specific/linux/alsa-utils/default.nix
@@ -1,12 +1,14 @@
 {stdenv, fetchurl, alsaLib, gettext, ncurses, libsamplerate}:
 
 stdenv.mkDerivation rec {
-  name = "alsa-utils-1.0.26";
+  name = "alsa-utils-1.0.28";
 
   src = fetchurl {
-    # url = "ftp://ftp.alsa-project.org/pub/utils/${name}.tar.bz2";
-    url = "http://alsa.cybermirror.org/utils/${name}.tar.bz2";
-    sha256 = "1rw1n3w8syqky9i7kwy5xd2rzfdbihxas32vwfxpb177lqx2lpzq";
+    urls = [
+      "ftp://ftp.alsa-project.org/pub/utils/${name}.tar.bz2"
+      "http://alsa.cybermirror.org/utils/${name}.tar.bz2"
+    ];
+    sha256 = "1k1ach1jv0bf71klj9sqaijnw9wjrjad0g5in6bpfnhjn24lrzzk";
   };
 
   buildInputs = [ alsaLib ncurses libsamplerate ];
@@ -16,13 +18,8 @@ stdenv.mkDerivation rec {
 
   installFlags = "ASOUND_STATE_DIR=$(TMPDIR)/dummy";
 
-  preConfigure =
-    ''
-      # Ensure that ‘90-alsa-restore.rules.in’ gets rebuilt.
-      rm alsactl/90-alsa-restore.rules
-    '';
-
   meta = {
+    homepage = http://www.alsa-project.org/;
     description = "ALSA, the Advanced Linux Sound Architecture utils";
 
     longDescription = ''
@@ -30,6 +27,6 @@ stdenv.mkDerivation rec {
       MIDI functionality to the Linux-based operating system.
     '';
 
-    homepage = http://www.alsa-project.org/;
+    platforms = stdenv.lib.platforms.linux;
   };
 }
diff --git a/pkgs/os-specific/linux/apparmor/default.nix b/pkgs/os-specific/linux/apparmor/default.nix
index 858be431a91..8048419a93b 100644
--- a/pkgs/os-specific/linux/apparmor/default.nix
+++ b/pkgs/os-specific/linux/apparmor/default.nix
@@ -5,11 +5,11 @@
 stdenv.mkDerivation rec {
 
   name = "apparmor-${version}";
-  version = "2.8.1";
+  version = "2.8.3";
 
   src = fetchurl {
     url = "http://launchpad.net/apparmor/2.8/${version}/+download/${name}.tar.gz";
-    sha256 = "1r0a5k14jbiik28m5gql0f3dbxl252jya7i120rrsbzqqnvw6nw7";
+    sha256 = "0zjwhkq9wh76m59zmrzfp68sjy4fnz4h23r7asxyaw6inrzwmhl4";
   };
 
   buildInputs = [
@@ -48,7 +48,7 @@ stdenv.mkDerivation rec {
     make
     make check
     make install
-    ensureDir $out/lib/perl5/site_perl/
+    mkdir -p $out/lib/perl5/site_perl/
     cp swig/perl/LibAppArmor.pm $out/lib/perl5/site_perl/
     cp swig/perl/LibAppArmor.bs $out/lib/perl5/site_perl/
     # this is automatically copied elsewhere....
@@ -87,7 +87,7 @@ stdenv.mkDerivation rec {
     homepage = http://apparmor.net/;
     description = "Linux application security system";
     license = licenses.gpl2;
-    maintainers = [ maintainers.phreedom ];
+    maintainers = [ maintainers.phreedom maintainers.thoughtpolice ];
     platforms = platforms.linux;
   };
 }
diff --git a/pkgs/os-specific/linux/atheros/0.9.4.nix b/pkgs/os-specific/linux/atheros/0.9.4.nix
deleted file mode 100644
index 341bdc3f1bb..00000000000
--- a/pkgs/os-specific/linux/atheros/0.9.4.nix
+++ /dev/null
@@ -1,28 +0,0 @@
-{ stdenv, fetchurl, builderDefs, kernelDev }:
-	let localDefs = builderDefs.passthru.function {
-		src = /* put a fetchurl here */
-		fetchurl {
-		  url = http://downloads.sourceforge.net/madwifi/madwifi-0.9.4.tar.gz;
-		  sha256 = "06jd5b8rfw7rmiva6jgmrb7n26g5plcg9marbnnmg68gbcqbr3xh";
-		};
-
-		buildInputs = [];
-		configureFlags = [];
-		makeFlags = [''KERNELPATH=${kernelDev}/lib/modules/*/build'' ''DESTDIR=$out''];
-	};
-	in with localDefs;
-let 
-postInstall = fullDepEntry (''
-	ln -s $out/usr/local/bin $out/bin
-'') [minInit doMakeInstall];
-in
-stdenv.mkDerivation rec {
-	name = "atheros-0.9.4-${kernelDev.version}";
-	builder = writeScript (name + "-builder")
-		(textClosure localDefs [doMakeInstall 
-			postInstall doForceShare doPropagate]);
-	meta = {
-		description = "Atheros WiFi driver";
-		inherit src;
-	};
-}
diff --git a/pkgs/os-specific/linux/ati-drivers/builder.sh b/pkgs/os-specific/linux/ati-drivers/builder.sh
index 2a20aa29fcc..d1ca1b35452 100644
--- a/pkgs/os-specific/linux/ati-drivers/builder.sh
+++ b/pkgs/os-specific/linux/ati-drivers/builder.sh
@@ -8,7 +8,7 @@ die(){ echo $@; exit 1; }
 
 # custom unpack:
 unzip $src
-run_file=$(echo amd-driver-installer-*)
+run_file=$(echo amd-catalyst-*)
 sh $run_file --extract .
 
 eval "$patchPhase"
@@ -181,6 +181,8 @@ GCC_MAJOR="`gcc --version | grep -o -e ") ." | head -1 | cut -d " " -f 2`"
   # make xorg use the ati version
   ln -s $out/lib/xorg/modules/extensions/{fglrx/fglrx-libglx.so,libglx.so}
 
+  # libstdc++ and gcc are needed by some libs
+  patchelf --set-rpath $gcc/$lib_arch $out/lib/libatiadlxx.so
 }
 
 { # build samples
@@ -190,6 +192,7 @@ GCC_MAJOR="`gcc --version | grep -o -e ") ." | head -1 | cut -d " " -f 2`"
   cd samples
   tar xfz ../common/usr/src/ati/fglrx_sample_source.tgz
 
+  eval "$patchPhaseSamples"
 
   ( # build and install fgl_glxgears
     cd fgl_glxgears; 
diff --git a/pkgs/os-specific/linux/ati-drivers/default.nix b/pkgs/os-specific/linux/ati-drivers/default.nix
index 326de9ed81a..0aa67dba237 100644
--- a/pkgs/os-specific/linux/ati-drivers/default.nix
+++ b/pkgs/os-specific/linux/ati-drivers/default.nix
@@ -1,4 +1,4 @@
-{ stdenv, fetchurl, kernelDev, xlibs, which, imake
+{ stdenv, fetchurl, kernel, xlibs, which, imake
 , mesa # for fgl_glxgears
 , libXxf86vm, xf86vidmodeproto # for fglrx_gamma
 , xorg, makeWrapper, glibc, patchelf
@@ -13,39 +13,45 @@
 # See http://thread.gmane.org/gmane.linux.distributions.nixos/4145 for a
 # workaround (TODO)
 
-# The gentoo ebuild contains much more magic..
+# The gentoo ebuild contains much more magic and is usually a great resource to
+# find patches :)
 
 # http://wiki.cchtml.com/index.php/Main_Page
 
 # There is one issue left:
 # /usr/lib/dri/fglrx_dri.so must point to /run/opengl-driver/lib/fglrx_dri.so
 
+# You eventually have to blacklist radeon module (?)
+
 assert stdenv.system == "x86_64-linux";
 
-stdenv.mkDerivation rec {
-  name = "ati-drivers-${version}-${kernel.version}";
-  version = "13.4";
+stdenv.mkDerivation {
+  name = "ati-drivers-13.12-${kernel.version}";
 
   builder = ./builder.sh;
 
   inherit libXxf86vm xf86vidmodeproto;
+  gcc = stdenv.gcc.gcc;
 
   src = fetchurl {
-    url = http://www2.ati.com/drivers/linux/amd-driver-installer-catalyst-13-4-linux-x86.x86_64.zip;
-    sha256 = "1914ikdich0kg047bqh89ai5z4dyryj5mlw5i46n90fsfiaxa532";
+    url = http://www2.ati.com/drivers/linux/amd-catalyst-13.12-linux-x86.x86_64.zip;
+    sha256 = "1c3fn328340by4qn99dgfj8c2q34fxdb2alcak0vnyc6bw7l5sms";
+    curlOpts = "--referer http://support.amd.com/en-us/download/desktop?os=Linux%20x86_64";
   };
 
-  patchPhase = "patch -p0 < ${./gentoo-patches.patch}";
+  # most patches are taken from gentoo
+  patchPhase = "patch -p1 < ${./gentoo-patches.patch}";
+  patchPhaseSamples = "patch -p2 < ${./patch-samples.patch}";
 
   buildInputs =
-    [ xlibs.libXext xlibs.libX11
+    [ xlibs.libXext xlibs.libX11 xlibs.libXinerama
       xlibs.libXrandr which imake makeWrapper
       patchelf
       unzip
       mesa
     ];
 
-  kernel = kernelDev;
+  kernel = kernel.dev;
 
   inherit glibc /* glibc only used for setting interpreter */;
 
@@ -54,21 +60,23 @@ stdenv.mkDerivation rec {
       "${xorg.libXrender}/lib"
       "${xorg.libXext}/lib"
       "${xorg.libX11}/lib"
+      "${xorg.libXinerama}/lib"
     ];
 
   # without this some applications like blender don't start, but they start
   # with nvidia. This causes them to be symlinked to $out/lib so that they
   # appear in /run/opengl-driver/lib which get's added to LD_LIBRARY_PATH
- extraDRIlibs = [ xorg.libXext ];
+  extraDRIlibs = [ xorg.libXext ];
 
   inherit mesa; # only required to build examples
 
-  meta = {
+  meta = with stdenv.lib; {
     description = "ATI drivers";
     homepage = http://support.amd.com/us/gpudownload/Pages/index.aspx;
-    license = "unfree";
-    maintainers = [stdenv.lib.maintainers.marcweber];
-    #platforms = [ "x86_64-linux" ];
+    license = licenses.unfree;
+    maintainers = with maintainers; [marcweber offline];
+    platforms = [ "x86_64-linux" ];
+    hydraPlatforms = [];
   };
 
   # moved assertions here because the name is evaluated when the NixOS manual is generated
diff --git a/pkgs/os-specific/linux/ati-drivers/gentoo-patches.patch b/pkgs/os-specific/linux/ati-drivers/gentoo-patches.patch
index ce4871c0658..392c2a8c29e 100644
--- a/pkgs/os-specific/linux/ati-drivers/gentoo-patches.patch
+++ b/pkgs/os-specific/linux/ati-drivers/gentoo-patches.patch
@@ -1,293 +1,51 @@
-diff -Nur common/lib/modules/fglrx/build_mod/drmP.h common-r1/lib/modules/fglrx/build_mod/drmP.h
---- common/lib/modules/fglrx/build_mod/drmP.h	2013-05-15 09:26:23.555752577 +0300
-+++ common-r1/lib/modules/fglrx/build_mod/drmP.h	2013-05-16 10:39:17.496212055 +0300
-@@ -901,10 +901,6 @@
- int                   DRM(stub_unregister)(int minor);
+diff --git a/common/lib/modules/fglrx/build_mod/firegl_public.c b/common/lib/modules/fglrx/build_mod/firegl_public.c
+index d3ad3ce..9362b58 100755
+--- a/common/lib/modules/fglrx/build_mod/firegl_public.c
++++ b/common/lib/modules/fglrx/build_mod/firegl_public.c
+@@ -34,6 +34,11 @@
+ #include <linux/autoconf.h>
+ #endif
  
- 				/* Proc support (drm_proc.h) */
--extern struct proc_dir_entry *DRM(proc_init)(drm_device_t *dev,
--					     int minor,
--					     struct proc_dir_entry *root,
--					     struct proc_dir_entry **dev_root);
- extern int            DRM(proc_cleanup)(int minor,
- 					struct proc_dir_entry *root,
- 					struct proc_dir_entry *dev_root);
-diff -Nur common/lib/modules/fglrx/build_mod/drm_proc.h common-r1/lib/modules/fglrx/build_mod/drm_proc.h
---- common/lib/modules/fglrx/build_mod/drm_proc.h	2013-05-15 09:26:23.555752577 +0300
-+++ common-r1/lib/modules/fglrx/build_mod/drm_proc.h	2013-05-19 02:16:16.584406160 +0300
-@@ -75,61 +75,6 @@
- #define DRM_PROC_ENTRIES (sizeof(DRM(proc_list))/sizeof(DRM(proc_list)[0]))
- 
- /**
-- * Initialize the DRI proc filesystem for a device.
-- *
-- * \param dev DRM device.
-- * \param minor device minor number.
-- * \param root DRI proc dir entry.
-- * \param dev_root resulting DRI device proc dir entry.
-- * \return root entry pointer on success, or NULL on failure.
-- * 
-- * Create the DRI proc root entry "/proc/ati", the device proc root entry
-- * "/proc/ati/%minor%/", and each entry in proc_list as
-- * "/proc/ati/%minor%/%name%".
-- */
--struct proc_dir_entry *DRM(proc_init)(drm_device_t *dev, int minor,
--				      struct proc_dir_entry *root,
--				      struct proc_dir_entry **dev_root)
--{
--	struct proc_dir_entry *ent;
--	int		      i, j;
--	char                  name[64];
--
--	if (!minor) root = create_proc_entry("dri", S_IFDIR, NULL);
--	if (!root) {
--		DRM_ERROR("Cannot create /proc/ati\n");
--		return NULL;
--	}
--
--	sprintf(name, "%d", minor);
--	*dev_root = create_proc_entry(name, S_IFDIR, root);
--	if (!*dev_root) {
--		DRM_ERROR("Cannot create /proc/ati/%s\n", name);
--		return NULL;
--	}
--
--	for (i = 0; i < DRM_PROC_ENTRIES; i++) {
--		ent = create_proc_entry(DRM(proc_list)[i].name,
--					S_IFREG|S_IRUGO, *dev_root);
--		if (!ent) {
--			DRM_ERROR("Cannot create /proc/ati/%s/%s\n",
--				  name, DRM(proc_list)[i].name);
--			for (j = 0; j < i; j++)
--				remove_proc_entry(DRM(proc_list)[i].name,
--						  *dev_root);
--			remove_proc_entry(name, root);
--			if (!minor) remove_proc_entry("dri", NULL);
--			return NULL;
--		}
--		ent->read_proc = DRM(proc_list)[i].f;
--		ent->data      = dev;
--	}
--
--	return root;
--}
--
--
--/**
-  * Cleanup the proc filesystem resources.
-  *
-  * \param minor device minor number.
-diff -Nur common/lib/modules/fglrx/build_mod/firegl_public.c common-r1/lib/modules/fglrx/build_mod/firegl_public.c
---- common/lib/modules/fglrx/build_mod/firegl_public.c	2013-05-15 09:26:23.545752925 +0300
-+++ common-r1/lib/modules/fglrx/build_mod/firegl_public.c	2013-05-19 03:07:10.236552522 +0300
-@@ -583,6 +583,202 @@
-     { "NULL",           NULL,                       NULL} // Terminate List!!!
- };
- 
-+
-+#if LINUX_VERSION_CODE >= KERNEL_VERSION(3,10,0)
-+typedef int (read_proc_t)(char *page, char **start, off_t off, int count, int *eof, void *data);
-+typedef int (write_proc_t)(struct file *file, const char __user *buffer, unsigned long count, void *data);
-+#else
-+#define PDE_DATA(inode) (PDE((inode))->data)
++#if LINUX_VERSION_CODE >= KERNEL_VERSION(3,5,0)
++#include <linux/uidgid.h>
 +#endif
 +
-+#if LINUX_VERSION_CODE >= KERNEL_VERSION(3,10,0)
-+typedef struct {
-+	read_proc_t *read_func;
-+	write_proc_t *write_func;
-+	void *data;
-+} gentoo_proc_wrapper_t;
-+
-+#define GENTOO_PROC_WRAPPER_OVERFLOW_MAGIC 939750305
-+
-+static ssize_t gentoo_proc_wrapper_read (struct file *myfile, char __user *buffer, size_t count, loff_t *offset) {
-+	int is_eof=0, retval;
-+	char *start, *usebuffer=NULL;
-+	gentoo_proc_wrapper_t* wrapper_data=(gentoo_proc_wrapper_t*)(myfile->private_data);
-+	if (PAGE_SIZE<*offset) {
-+		printk(KERN_ERR "Trying to read beyond 4k on proc\n");
-+		return -EIO;
-+	}
-+	//printk(KERN_NOTICE " call with: dev %p, func %p\n", wrapper_data->data, wrapper_data->read_func);
-+	
-+	usebuffer=kmalloc(2*PAGE_SIZE, GFP_KERNEL);
-+	if (!usebuffer)
-+		return -ENOMEM;
-+	((u32*)usebuffer)[1024]=GENTOO_PROC_WRAPPER_OVERFLOW_MAGIC;
-+
-+	retval=wrapper_data->read_func(usebuffer, &start, *offset, count, &is_eof, wrapper_data->data);
-+
-+	BUG_ON(GENTOO_PROC_WRAPPER_OVERFLOW_MAGIC != ((u32*)usebuffer)[1024]);
-+
-+	if (0 > retval)
-+	{
-+		printk(KERN_ERR "Proc read failed with %d", retval);
-+		goto out;
-+	}
-+
-+	if (copy_to_user(buffer, start, retval)) {
-+		printk(KERN_NOTICE "copy to user failed in amd drivers proc code\n");
-+		retval=-EFAULT;
-+		goto out;
-+	}
-+	*offset+=retval;
-+	
-+out:
-+	if (usebuffer)
-+		kfree(usebuffer);
-+	return retval;
-+}
-+static ssize_t gentoo_proc_wrapper_write (struct file *myfile, const char __user *buffer, size_t count, loff_t *offset) {
-+	gentoo_proc_wrapper_t* wrapper_data=(gentoo_proc_wrapper_t*)(myfile->private_data);
-+	int retval=0;
-+	void *usebuffer=NULL;
-+
-+	BUG_ON(*offset);
-+	if (!wrapper_data->write_func)
-+		return -EPERM;
-+	
-+	usebuffer=kmalloc(count, GFP_KERNEL);
-+	if (!usebuffer)
-+		return -ENOMEM;
-+	if (copy_from_user(usebuffer, buffer, count)) {
-+		printk(KERN_NOTICE "copy from user failed in amd drivers proc code\n");
-+		retval=-EFAULT;
-+		goto out;
-+	}
-+	
-+	retval=wrapper_data->write_func(myfile, buffer, count, wrapper_data->data);
-+	*offset+=retval;
-+out:
-+	if (usebuffer)
-+		kfree(usebuffer);
-+	return retval;
-+}
-+static int gentoo_proc_wrapper_open(struct inode *myinode, struct file *myfile) {
-+	myfile->private_data=PDE_DATA(myinode);
-+	return generic_file_open(myinode, myfile);
-+}
-+struct file_operations gentoo_proc_fops = {
-+	.read=gentoo_proc_wrapper_read,
-+	.write=gentoo_proc_wrapper_write,
-+	.open=gentoo_proc_wrapper_open,
-+};
-+	
-+static void *gentoo_proc_wrapper_data(read_proc_t *reader, write_proc_t *writer, void *mydata) {
-+	gentoo_proc_wrapper_t *retval=kmalloc(sizeof(gentoo_proc_wrapper_t), GFP_KERNEL);
-+	if (!retval)
-+		return retval;
-+	retval->read_func=reader;
-+	retval->write_func=writer;
-+	retval->data=mydata;
-+	return retval;
-+}
-+
-+static struct proc_dir_entry *firegl_proc_init( device_t *dev,
-+                                                int minor,
-+                                                struct proc_dir_entry *root,
-+                                                struct proc_dir_entry **dev_root,
-+                                                kcl_proc_list_t *proc_list ) // proc_list must be terminated!
-+{
-+    struct proc_dir_entry *ent;
-+    char    name[64];
-+    kcl_proc_list_t *list = proc_list;
-+	void *tempdata;
-+    KCL_DEBUG1(FN_FIREGL_PROC, "minor %d, proc_list 0x%08lx\n", minor, (unsigned long)proc_list);
-+    if (!minor)
-+    {
-+        root = proc_mkdir("ati", NULL);
-+    }
-+
-+    if (!root)
-+    {
-+        KCL_DEBUG_ERROR("Cannot create /proc/ati\n");
-+        return NULL;
-+    }
-+
-+    if (minor == 0)
-+    {
-+        // Global major debice number entry
-+		tempdata=gentoo_proc_wrapper_data((read_proc_t*)firegl_major_proc_read, NULL, NULL);
-+		if (!tempdata)
-+			return NULL;
-+        ent = proc_create_data("major", S_IFREG|S_IRUGO, root, &gentoo_proc_fops, tempdata);
-+        if (!ent)
-+        {
-+            remove_proc_entry("ati", NULL);
-+            KCL_DEBUG_ERROR("Cannot create /proc/ati/major\n");
-+            return NULL;
-+        }
-+    }
-+
-+    sprintf(name, "%d", minor);
-+    *dev_root = proc_mkdir(name, root);
-+    if (!*dev_root) {
-+        remove_proc_entry("major", root);
-+        remove_proc_entry("ati", NULL);
-+        KCL_DEBUG_ERROR("Cannot create /proc/ati/%s\n", name);
-+        return NULL;
-+    }
-+
-+    while (list->f || list->fops)
-+    {
-+		struct file_operations *my_fops = &gentoo_proc_fops;
-+        if (list->fops)
-+        {
-+            my_fops = (struct file_operations*)list->fops;
-+			tempdata=(dev->pubdev.signature == FGL_DEVICE_SIGNATURE)? firegl_find_device(minor) : (dev);
-+        }
-+		else {
-+			BUG_ON(!list->f);
-+			tempdata=gentoo_proc_wrapper_data((read_proc_t*)list->f, NULL, (dev->pubdev.signature == FGL_DEVICE_SIGNATURE)? firegl_find_device(minor) : (dev) );
-+			if (!tempdata)
-+				return NULL;
-+		}
-+		//printk(KERN_NOTICE "name %s, dev %p, func %p, data %p\n", list->name, (dev->pubdev.signature == FGL_DEVICE_SIGNATURE)? firegl_find_device(minor) : (dev), list->f, tempdata);
-+        ent = proc_create_data(list->name, S_IFREG|S_IRUGO, *dev_root, my_fops, tempdata);
-+
-+        if (!ent)
-+        {
-+            KCL_DEBUG_ERROR("Cannot create /proc/ati/%s/%s\n", name, list->name);
-+            while (proc_list != list)
-+            {
-+                remove_proc_entry(proc_list->name, *dev_root);
-+                proc_list++;
-+            }
-+            remove_proc_entry(name, root);
-+            if (!minor)
-+            {
-+                remove_proc_entry("major", root);
-+                remove_proc_entry("ati", NULL);
-+            }
-+            return NULL;
-+        }
-+
-+        list++;
-+    }
 +
-+    if (minor == 0)
-+    {
-+        // Global debug entry, only create it once
-+		tempdata=gentoo_proc_wrapper_data((read_proc_t*)firegl_debug_proc_read_wrap, (write_proc_t*)firegl_debug_proc_write_wrap, dev);
-+		if (!tempdata)
-+			return NULL;
-+        ent=proc_create_data("debug", S_IFREG|S_IRUGO, root, &gentoo_proc_fops, tempdata);
-+		if (!ent)
-+			return NULL;
+ #if !defined(CONFIG_X86) 
+ #if !defined(CONFIG_X86_PC) 
+ #if !defined(CONFIG_X86_XEN) 
+@@ -1543,9 +1548,17 @@ KCL_TYPE_Pid ATI_API_CALL KCL_GetTgid(void)
+ KCL_TYPE_Uid ATI_API_CALL KCL_GetEffectiveUid(void)
+ {
+ #ifdef current_euid
++# if LINUX_VERSION_CODE >= KERNEL_VERSION(3,5,0)
++    return __kuid_val(current_euid());
++# else
+     return current_euid();
++# endif
+ #else
++# if LINUX_VERSION_CODE >= KERNEL_VERSION(3,5,0)
++    return __kuid_val(current->euid);
++# else
+     return current->euid;
++# endif
+ #endif
+ }
+ 
+
+diff -urN a/common/lib/modules/fglrx/build_mod/kcl_acpi.c common/lib/modules/fglrx/build_mod/kcl_acpi.c
+--- a/common/lib/modules/fglrx/build_mod/kcl_acpi.c	2013-12-27 13:32:34.734832283 +0100
++++ b/common/lib/modules/fglrx/build_mod/kcl_acpi.c	2013-12-27 13:33:31.849831765 +0100
+@@ -1002,7 +1002,11 @@
+ #endif
+     {
+         return KCL_ACPI_ERROR;
+-    }    
 +    }
-+
-+    return root;
-+}
++#if LINUX_VERSION_CODE >= KERNEL_VERSION(3,9,1)
++    ((acpi_tbl_table_handler)handler)(hdr);
 +#else
- static struct proc_dir_entry *firegl_proc_init( device_t *dev,
-                                                 int minor,
-                                                 struct proc_dir_entry *root,
-@@ -677,6 +873,7 @@
- 
-     return root;
- }
+     ((acpi_table_handler)handler)(hdr);
 +#endif
- 
- static int firegl_proc_cleanup( int minor,
-                                 struct proc_dir_entry *root,
+     return KCL_ACPI_OK;
+ }
diff --git a/pkgs/os-specific/linux/ati-drivers/patch-samples.patch b/pkgs/os-specific/linux/ati-drivers/patch-samples.patch
new file mode 100644
index 00000000000..8bd24b1d022
--- /dev/null
+++ b/pkgs/os-specific/linux/ati-drivers/patch-samples.patch
@@ -0,0 +1,26 @@
+diff --git a/samples/fgl_glxgears/fgl_glxgears.c b/samples/fgl_glxgears/fgl_glxgears.c
+index 6c8e313..2b8d035 100644
+--- a/samples/fgl_glxgears/fgl_glxgears.c
++++ b/samples/fgl_glxgears/fgl_glxgears.c
+@@ -1096,8 +1096,6 @@ static void event_loop(void)
+                   view_rotx -= 5.0;
+                }
+                else {
+-                  r = XLookupString(&event.xkey, buffer, sizeof(buffer),
+-                                    NULL, NULL);
+                   if (buffer[0] == 27) {
+                      /* escape */
+                      return;
+
+
+diff -Nur a/samples/fgl_glxgears/fgl_glxgears.c b/samples/fgl_glxgears/fgl_glxgears.c
+--- a/samples/fgl_glxgears/fgl_glxgears.c	2012-08-29 09:59:03.000000000 +0300
++++ b/samples/fgl_glxgears/fgl_glxgears.c	2013-09-07 09:26:11.034723135 +0300
+@@ -78,7 +78,6 @@
+ #endif // _WIN32
+ 
+ #define INT_PTR ptrdiff_t
+-#include <GL/glATI.h>
+ 
+ #ifdef _WIN32
+ #include <GL/wglATI.h>
diff --git a/pkgs/os-specific/linux/atop/default.nix b/pkgs/os-specific/linux/atop/default.nix
index 39ba5dc3973..fd4b6df9552 100644
--- a/pkgs/os-specific/linux/atop/default.nix
+++ b/pkgs/os-specific/linux/atop/default.nix
@@ -35,5 +35,8 @@ stdenv.mkDerivation rec {
     longDescription = ''
       Atop is an ASCII full-screen performance monitor that is capable of reporting the activity of all processes (even if processes have finished during the interval), daily logging of system and process activity for long-term analysis, highlighting overloaded system resources by using colors, etc. At regular intervals, it shows system-level activity related to the CPU, memory, swap, disks and network layers, and for every active process it shows the CPU utilization, memory growth, disk utilization, priority, username, state, and exit code.
     '';
+    inherit version;
+    downloadPage = http://atoptool.nl/downloadatop.php;
+    updateWalker = true;
   };
 }
diff --git a/pkgs/os-specific/linux/audit/default.nix b/pkgs/os-specific/linux/audit/default.nix
new file mode 100644
index 00000000000..9de84e228c4
--- /dev/null
+++ b/pkgs/os-specific/linux/audit/default.nix
@@ -0,0 +1,28 @@
+{ stdenv, fetchurl, openldap
+, enablePython ? false, python ? null
+}:
+
+assert enablePython -> python != null;
+
+stdenv.mkDerivation rec {
+  name = "audit-2.3.2";
+
+  src = fetchurl {
+    url = "http://people.redhat.com/sgrubb/audit/${name}.tar.gz";
+    sha256 = "0a8x10wz0xfj0iq1wgjl6hdhxvq58cb3906vc687i21876sy0wl8";
+  };
+
+  buildInputs = [ openldap ]
+            ++ stdenv.lib.optional enablePython python;
+
+  configureFlags = ''
+    ${if enablePython then "--with-python" else "--without-python"}
+  '';
+
+  meta = {
+    description = "Audit Library";
+    homepage = "http://people.redhat.com/sgrubb/audit/";
+    license = stdenv.lib.licenses.gpl2;
+    platforms = stdenv.lib.platforms.linux;
+  };
+}
diff --git a/pkgs/os-specific/linux/aufs-util/2.nix b/pkgs/os-specific/linux/aufs-util/2.nix
deleted file mode 100644
index e4968b92048..00000000000
--- a/pkgs/os-specific/linux/aufs-util/2.nix
+++ /dev/null
@@ -1,41 +0,0 @@
-{ stdenv, fetchurl, kernelDev, aufs }:
-
-assert aufs != null;
-
-let version = "20100506"; in
-
-stdenv.mkDerivation {
-  name = "aufs2-util-${version}-${kernelDev.version}";
-
-  src = fetchurl {
-    url = "http://tarballs.nixos.org/aufs2-util-git-${version}.tar.bz2";
-    sha256 = "0ly0c3p8fjxqbk8k5rmm1a91wg8wcrvhi1lv4aawalkkk8rqbnwk";
-  };
-
-  buildInputs = [ aufs ];
-
-  makeFlags =
-    [ "KDIR=${kernelDev}/lib/modules/${kernelDev.version}/build"
-      "Install=install"
-      "DESTDIR=$(out)"
-    ];
-
-  postInstall =
-    ''
-      mv $out/usr/* $out
-      rmdir $out/usr
-
-      cp aufs.shlib $out/lib/
-
-      substituteInPlace $out/bin/aubrsync \
-        --replace /sbin/mount $out/sbin/mount \
-        --replace /usr/lib/aufs.shlib $out/lib/aufs.shlib
-    '';
-
-  meta = {
-    description = "Utilities for AUFS2";
-    homepage = http://aufs.sourceforge.net/;
-    maintainers = [ stdenv.lib.maintainers.eelco ];
-    platforms = stdenv.lib.platforms.linux;
-  };
-}
diff --git a/pkgs/os-specific/linux/aufs-util/3.nix b/pkgs/os-specific/linux/aufs-util/3.nix
deleted file mode 100644
index 9997c2743a5..00000000000
--- a/pkgs/os-specific/linux/aufs-util/3.nix
+++ /dev/null
@@ -1,40 +0,0 @@
-{ stdenv, fetchgit, kernelDev, aufs }:
-
-assert aufs != null;
-
-stdenv.mkDerivation {
-  name = "aufs3-util-${aufs.patch.version}-${kernelDev.version}";
-
-  src = fetchgit {
-    url = git://aufs.git.sourceforge.net/gitroot/aufs/aufs-util.git;
-    rev = aufs.patch.utilRev;
-    sha256 = aufs.patch.utilHash;
-  };
-
-  buildInputs = [ aufs ];
-
-  makeFlags =
-    [ "KDIR=${kernelDev}/lib/modules/${kernelDev.modDirVersion}/build"
-      "Install=install"
-      "DESTDIR=$(out)"
-    ];
-
-  postInstall =
-    ''
-      mv $out/usr/* $out
-      rmdir $out/usr
-
-      cp aufs.shlib $out/lib/
-
-      substituteInPlace $out/bin/aubrsync \
-        --replace /sbin/mount $out/sbin/mount \
-        --replace /usr/lib/aufs.shlib $out/lib/aufs.shlib
-    '';
-
-  meta = {
-    description = "Utilities for AUFS3";
-    homepage = http://aufs.sourceforge.net/;
-    maintainers = [ stdenv.lib.maintainers.eelco  ];
-    platforms = stdenv.lib.platforms.linux;
-  };
-}
diff --git a/pkgs/os-specific/linux/aufs/2.nix b/pkgs/os-specific/linux/aufs/2.nix
deleted file mode 100644
index a4a40823f7a..00000000000
--- a/pkgs/os-specific/linux/aufs/2.nix
+++ /dev/null
@@ -1,43 +0,0 @@
-{ stdenv, fetchurl, kernelDev, perl, fetchgit }:
-
-assert kernelDev.features ? aufsBase;
-
-let version = "20100522"; in
-
-stdenv.mkDerivation {
-  name = "aufs2-${version}-${kernelDev.version}";
-
-  src = 
-  if (builtins.lessThan (builtins.compareVersions kernelDev.version "2.6.35") 0) then
-    fetchurl {
-      url = "http://tarballs.nixos.org/aufs2-standalone-git-${version}.tar.bz2";
-      sha256 = "1g4mw4qx2xzpygdwjiw36bkhfz1hi7wxx7w79n2h0lr5grzzdnd6";
-    }
-  else
-    fetchgit {
-      url = "http://git.c3sl.ufpr.br/pub/scm/aufs/aufs2-standalone.git";
-      rev = "d950eef373ff1e0448ad3945b734da6ab050571d";
-      sha256 = "816145b0341bd7862df50c058144cf6ebc25c05d2976f781ff0fe10d4559b853";
-    };
-
-  buildInputs = [ perl ];
-
-  makeFlags = "KDIR=${kernelDev}/lib/modules/${kernelDev.version}/build";
-
-  installPhase =
-    ''
-      mkdir -p $out/lib/modules/${kernelDev.version}/misc
-      cp aufs.ko $out/lib/modules/${kernelDev.version}/misc
-
-      # Install the headers because aufs2-util requires them.
-      cp -prvd include $out/
-    '';
-
-  meta = {
-    description = "Another Unionfs implementation for Linux (second generation)";
-    homepage = http://aufs.sourceforge.net/;
-    maintainers = [ stdenv.lib.maintainers.eelco
-                    stdenv.lib.maintainers.raskin ];
-    platforms = stdenv.lib.platforms.linux;
-  };
-}
diff --git a/pkgs/os-specific/linux/aufs/3.nix b/pkgs/os-specific/linux/aufs/3.nix
deleted file mode 100644
index 2f566d3abff..00000000000
--- a/pkgs/os-specific/linux/aufs/3.nix
+++ /dev/null
@@ -1,44 +0,0 @@
-{ stdenv, kernelDev, perl }:
-
-let
-
-  aufsPredicate = x:
-    if x ? features then
-      (if x.features ? aufs3 then x.features.aufs3 else false)
-    else false;
-  featureAbort = abort "This kernel does not have aufs 3 support";
-  patch = stdenv.lib.findFirst aufsPredicate featureAbort kernelDev.kernelPatches;
-
-in
-
-stdenv.mkDerivation {
-  name = "aufs3-${patch.version}-${kernelDev.version}";
-
-  src = patch.patch.src;
-
-  buildInputs = [ perl ];
-
-  makeFlags = "KDIR=${kernelDev}/lib/modules/${kernelDev.modDirVersion}/build";
-
-  NIX_CFLAGS_COMPILE="-I${kernelDev}/lib/modules/${kernelDev.modDirVersion}/build/include/generated";
-
-  installPhase =
-    ''
-      mkdir -p $out/lib/modules/${kernelDev.modDirVersion}/misc
-      cp -v aufs.ko $out/lib/modules/${kernelDev.modDirVersion}/misc
-
-      # Install the headers because aufs3-util requires them.
-      mkdir -p $out/include/linux
-      cp -v usr/include/linux/aufs_type.h $out/include/linux
-    '';
-
-  passthru = { inherit patch; };
-
-  meta = {
-    description = "Another Unionfs implementation for Linux (third generation)";
-    homepage = http://aufs.sourceforge.net/;
-    maintainers = [ stdenv.lib.maintainers.eelco
-                    stdenv.lib.maintainers.raskin ];
-    platforms = stdenv.lib.platforms.linux;
-  };
-}
diff --git a/pkgs/os-specific/linux/autofs/autofs-v5.nix b/pkgs/os-specific/linux/autofs/autofs-v5.nix
index 731b383e711..5c5c2f026af 100644
--- a/pkgs/os-specific/linux/autofs/autofs-v5.nix
+++ b/pkgs/os-specific/linux/autofs/autofs-v5.nix
@@ -4,17 +4,17 @@ let
   baseURL = mirror://kernel/linux/daemons/autofs/v5;
 in
 stdenv.mkDerivation {
-  name = "autofs-5.0.5";
+  name = "autofs-5.0.8";
 
   src = fetchurl {
-    url = "${baseURL}/autofs-5.0.5.tar.bz2";
-    sha256 = "00k0k3jkbr29gn1wnzqjyc9iqq5bwjyip1isc79wf51wph0kxiv8";
+    url = "${baseURL}/autofs-5.0.8.tar.bz2";
+    sha256 = "0zczihrqdamj43401v2pczf7zi94f8qk20gc6l92nxmpak3443if";
   };
 
   patches = import ./patches-v5.nix fetchurl;
 
   preConfigure = ''
-    configureFlags="--with-path=$PATH"
+    configureFlags="--disable-move-mount --with-path=$PATH"
     export MOUNT=/var/run/current-system/sw/bin/mount
     export UMOUNT=/var/run/current-system/sw/bin/umount
     export MODPROBE=/var/run/current-system/sw/sbin/modprobe
@@ -36,7 +36,7 @@ stdenv.mkDerivation {
   meta = { 
     description="Kernel based automounter";
     homepage="http://www.linux-consulting.com/Amd_AutoFS/autofs.html";
-    license = "GPLv2";
+    license = stdenv.lib.licenses.gpl2;
     executables = [ "automount" ];
   };
 }
diff --git a/pkgs/os-specific/linux/autofs/create-patches-v5.sh b/pkgs/os-specific/linux/autofs/create-patches-v5.sh
index 781c59a324a..1fe6b503288 100644
--- a/pkgs/os-specific/linux/autofs/create-patches-v5.sh
+++ b/pkgs/os-specific/linux/autofs/create-patches-v5.sh
@@ -1,10 +1,10 @@
 #!/bin/sh
 #
 # Use this script with the upstream sorted list of patches
-# curl ftp://ftp.kernel.org/pub/linux/daemons/autofs/v5/patch_order-5.0.5 |
+# curl ftp://ftp.kernel.org/pub/linux/daemons/autofs/v5/patches-5.0.{x+1}/patch_order-5.0.x | 
 #   grep -v '^#' | sh create-patches-v5.sh
 
-BASEURL=mirror://kernel/linux/daemons/autofs/v5;
+BASEURL=mirror://kernel/linux/daemons/autofs/v5/patches-5.0.9;
 
 echo '# File created automatically' > patches-v5.nix
 echo 'fetchurl :' >> patches-v5.nix
diff --git a/pkgs/os-specific/linux/autofs/patches-v5.nix b/pkgs/os-specific/linux/autofs/patches-v5.nix
index 0598102fb2a..a577beefbe7 100644
--- a/pkgs/os-specific/linux/autofs/patches-v5.nix
+++ b/pkgs/os-specific/linux/autofs/patches-v5.nix
@@ -1,32 +1,7 @@
 # File created automatically
 fetchurl :
 [
-(fetchurl { url = mirror://kernel/linux/daemons/autofs/v5/autofs-5.0.5-fix-included-map-read-fail-handling.patch; sha256 = "1a8yhy898zp8hn6ihnz8scannjx74am6ys6dkahds4ga3zjg0k27"; })
-(fetchurl { url = mirror://kernel/linux/daemons/autofs/v5/autofs-5.0.5-refactor-ldap-sasl-bind.patch; sha256 = "0c4izyvg4mrn0h4g18vk7d10zyb6b1sh40bjrm0xc6ga7n7z89x1"; })
-(fetchurl { url = mirror://kernel/linux/daemons/autofs/v5/autofs-5.0.4-add-mount-wait-parameter.patch; sha256 = "1a8wd8lyx4bh9v6yw0360vbzjwvr1w838k2g3xrg374z6fmj4n3f"; })
-(fetchurl { url = mirror://kernel/linux/daemons/autofs/v5/autofs-5.0.5-special-case-cifs-escapes.patch; sha256 = "0cb4kaipdmqlx11nw1l9c6ccssl01q5zg3f9zaarhv6ha91jag63"; })
-(fetchurl { url = mirror://kernel/linux/daemons/autofs/v5/autofs-5.0.5-fix-libxml2-workaround-configure.patch; sha256 = "1fb5ksyqc7706j48hwjarsk83047np360kln6lll8plmrg2539rc"; })
-(fetchurl { url = mirror://kernel/linux/daemons/autofs/v5/autofs-5.0.5-more-code-analysis-corrections.patch; sha256 = "1lhx6iblmi4b8jx5sd94jlj8pwkhfy9f7dxnx45af0c251rcqxi9"; })
-(fetchurl { url = mirror://kernel/linux/daemons/autofs/v5/autofs-5.0.5-fix-backwards-ifndef-INET6.patch; sha256 = "0k2cbr2651w6hf720qm68l66d3jr5y6yp80igr7ym60q68pxkwfk"; })
-(fetchurl { url = mirror://kernel/linux/daemons/autofs/v5/autofs-5.0.5-fix-stale-init-for-file-map-instance.patch; sha256 = "1h128fj8bgwg8ym0066dl9qp5yfv8jrjnrhsdsmfx2qdq2shyj42"; })
-(fetchurl { url = mirror://kernel/linux/daemons/autofs/v5/autofs-5.0.5-fix-ext4-fsck-at-mount.patch; sha256 = "1w92iykwnpvz6sbn98nmc9qa8wwar2qidqln3f14wfic9jrs2x6n"; })
-(fetchurl { url = mirror://kernel/linux/daemons/autofs/v5/autofs-5.0.5-dont-use-master_lex_destroy-to-clear-parse-buffer.patch; sha256 = "1rq2xqj3jqibbknnssd3ji0ymdw8jq7fv2a4s15m63rd8q3b2mci"; })
-(fetchurl { url = mirror://kernel/linux/daemons/autofs/v5/autofs-5.0.5-make-documentation-for-set-log-priority-clearer.patch; sha256 = "0ly5zkhsx49b98vzrq863ksj9f8024vrzivlhwa45p47kzza9p9b"; })
-(fetchurl { url = mirror://kernel/linux/daemons/autofs/v5/autofs-5.0.5-fix-timeout-in-connect_nb.patch; sha256 = "1fhy7rmvk14ikxnavlznx8qya0y5gm73y8gs1v1piwmig0g3y8hf"; })
-(fetchurl { url = mirror://kernel/linux/daemons/autofs/v5/autofs-5.0.5-fix-pidof-init-script-usage.patch; sha256 = "1rqpdjn99wqr8j591qsn231chwi3s25jma3raqmpsip3vz75rfy8"; })
-(fetchurl { url = mirror://kernel/linux/daemons/autofs/v5/autofs-5.0.5-check-for-path-mount-location-in-generic-module.patch; sha256 = "17lccz000ajclm29v7cv6i2dxs7lgb0p6dg9xdp84h58h6x94n0l"; })
-(fetchurl { url = mirror://kernel/linux/daemons/autofs/v5/autofs-5.0.5-dont-fail-mount-on-access-fail.patch; sha256 = "0sssai921nkin77gi6n62qsxp97f49xa7cwb51dwy8216qcn5fkr"; })
-(fetchurl { url = mirror://kernel/linux/daemons/autofs/v5/autofs-5.0.5-fix-rpc-large-export-list.patch; sha256 = "1k4574pkmnp55jkqg83f3pyw3vqf0pv8fyhwb6ndrzfmgrmbcqar"; })
-(fetchurl { url = mirror://kernel/linux/daemons/autofs/v5/autofs-5.0.5-fix-memory-leak-on-reload.patch; sha256 = "15qc61akl0gvs33anz6vif2cb4g1v47s9n6v9j0sdw4sw45292gv"; })
-(fetchurl { url = mirror://kernel/linux/daemons/autofs/v5/autofs-5.0.5-update-kernel-patches-2.6.18-and-2.6.19.patch; sha256 = "0rlb3k2bq5f18jrwa7xnfq3rxngqv9i07xcpyfq8yv3lj6qrb5qc"; })
-(fetchurl { url = mirror://kernel/linux/daemons/autofs/v5/autofs-5.0.5-dont-connect-at-ldap-lookup-module-init.patch; sha256 = "0dvfvim2riasa3dcf4ifkjg9bssaq8am4asrxfl9gkxqa3lp0drh"; })
-(fetchurl { url = mirror://kernel/linux/daemons/autofs/v5/autofs-5.0.5-fix-random-selection-option.patch; sha256 = "0ignn2m4syk491awkrzjj07vyfmlj4fyigk8fd3larn06vpcy0kx"; })
-(fetchurl { url = mirror://kernel/linux/daemons/autofs/v5/autofs-5.0.5-fix-disable-timeout.patch; sha256 = "0d66pm2kmc9pz6k0shsd1gx0m8jhf71ik6wa7nzdijwpzzmbdagc"; })
-(fetchurl { url = mirror://kernel/linux/daemons/autofs/v5/autofs-5.0.5-fix-strdup-return-value-check.patch; sha256 = "0k0xqs1k12nxiaidf3j2w8iywycpbx14bmxc00ra0nc2i3shd6cz"; })
-(fetchurl { url = mirror://kernel/linux/daemons/autofs/v5/autofs-5.0.5-fix-reconnect-get-base-dn.patch; sha256 = "1yn5fcb1xqzycmnbv6l7ghjy34vlacbnr5yz37sfgz7w81qr7xgk"; })
-(fetchurl { url = mirror://kernel/linux/daemons/autofs/v5/autofs-5.0.5-add-sasl-mutex-callbacks.patch; sha256 = "18kkznkg2p5f0gq4hncis37j75pg72h7la9q71xpl0ci875j35r8"; })
-(fetchurl { url = mirror://kernel/linux/daemons/autofs/v5/autofs-5.0.5-fix-get-qdn-fail.patch; sha256 = "0sd6k7fcwvql1p3vhhfjiw4rbrqyr36fvjv37dyap7p6sahn84n9"; })
-(fetchurl { url = mirror://kernel/linux/daemons/autofs/v5/autofs-5.0.5-fix-ampersand-escape-in-auto-smb.patch; sha256 = "1imsxa4rdbkdy8lx7sibm6g91f05lidhfzwf2k4fbkiz9232872r"; })
-(fetchurl { url = mirror://kernel/linux/daemons/autofs/v5/autofs-5.0.5-add-locality-as-valid-ldap-master-map-attribute.patch; sha256 = "1r3azgm8y5i42p9hmp4mn88wz0ks6fyrjb80nj3npv6x3qy8cryv"; })
-(fetchurl { url = mirror://kernel/linux/daemons/autofs/v5/autofs-5.0.5-add-locality-as-valid-ldap-master-map-attribute-fix.patch; sha256 = "026gbbffadl4ly5n5z73mzf2ga14m9ya09agbxrpsf24f4h65cw4"; })
+(fetchurl { url = mirror://kernel/linux/daemons/autofs/v5/patches-5.0.9/autofs-5.0.8-fix-undefined-authtype_requires_creds-err-if-ldap-en.patch; sha256 = "11v1a32rx57ylp8scswpk41jl9n4kfx55nvdlzhvfs4rhws18rpx"; })
+(fetchurl { url = mirror://kernel/linux/daemons/autofs/v5/patches-5.0.9/autofs-5.0.8-fix-master-map-type-check.patch; sha256 = "1nkq0y6j7dc6214af3q9bxvy7pv9kak0q9chijxcj6zkhfzwrjy3"; })
+(fetchurl { url = mirror://kernel/linux/daemons/autofs/v5/patches-5.0.9/autofs-5.0.8-fix-task-manager-not-getting-signaled.patch; sha256 = "17h06wk4x0rqiky6pm9dglbc5ycxxrd3438a9snnlysl4zzgrqhx"; })
 ]
diff --git a/pkgs/os-specific/linux/batman-adv/batctl.nix b/pkgs/os-specific/linux/batman-adv/batctl.nix
index 2ff9d214bbb..6e57e7651c4 100644
--- a/pkgs/os-specific/linux/batman-adv/batctl.nix
+++ b/pkgs/os-specific/linux/batman-adv/batctl.nix
@@ -1,14 +1,14 @@
 {stdenv, fetchurl}:
 
 let
-  ver = "2013.2.0";
+  ver = "2013.4.0";
 in
 stdenv.mkDerivation rec {
   name = "batctl-${ver}";
 
   src = fetchurl {
     url = "http://downloads.open-mesh.org/batman/releases/batman-adv-${ver}/${name}.tar.gz";
-    sha1 = "0ba6520c813c9dd2e59e6205e8ea2e60a0c85f52";
+    sha256 = "0k6b695h38m92a8wn5gvb3z746m3fm0ygv58yyn163adcsvf7sjd";
   };
 
   preBuild = ''
@@ -18,7 +18,7 @@ stdenv.mkDerivation rec {
   meta = {
     homepage = http://www.open-mesh.org/projects/batman-adv/wiki/Wiki;
     description = "B.A.T.M.A.N. routing protocol in a linux kernel module for layer 2, control tool";
-    license = "GPLv2";
+    license = stdenv.lib.licenses.gpl2;
     maintainers = with stdenv.lib.maintainers; [viric];
     platforms = with stdenv.lib.platforms; linux;
   };
diff --git a/pkgs/os-specific/linux/batman-adv/default.nix b/pkgs/os-specific/linux/batman-adv/default.nix
index e4b4d1104b0..fee955bcca2 100644
--- a/pkgs/os-specific/linux/batman-adv/default.nix
+++ b/pkgs/os-specific/linux/batman-adv/default.nix
@@ -1,17 +1,17 @@
-{ stdenv, fetchurl, kernelDev }:
+{ stdenv, fetchurl, kernel }:
 
-let base = "batman-adv-2013.2.0"; in
+let base = "batman-adv-2013.4.0"; in
 
 stdenv.mkDerivation rec {
-  name = "${base}-${kernelDev.version}";
+  name = "${base}-${kernel.version}";
 
   src = fetchurl {
     url = "http://downloads.open-mesh.org/batman/releases/${base}/${base}.tar.gz";
-    sha1 = "7d2aff2ad118cbc5452de43f7e9da8374521ec0e";
+    sha1 = "870a85df5410b3b5623be69e75297e642c91a7d4";
   };
 
   preBuild = ''
-    makeFlags="KERNELPATH=${kernelDev}/lib/modules/${kernelDev.modDirVersion}/build"
+    makeFlags="KERNELPATH=${kernel.dev}/lib/modules/${kernel.modDirVersion}/build"
     sed -i -e "s,INSTALL_MOD_DIR=,INSTALL_MOD_PATH=$out INSTALL_MOD_DIR=," \
       -e /depmod/d Makefile
   '';
@@ -19,7 +19,7 @@ stdenv.mkDerivation rec {
   meta = {
     homepage = http://www.open-mesh.org/projects/batman-adv/wiki/Wiki;
     description = "B.A.T.M.A.N. routing protocol in a linux kernel module for layer 2";
-    license = "GPLv2";
+    license = stdenv.lib.licenses.gpl2;
     maintainers = with stdenv.lib.maintainers; [viric];
     platforms = with stdenv.lib.platforms; linux;
   };
diff --git a/pkgs/os-specific/linux/bbswitch/default.nix b/pkgs/os-specific/linux/bbswitch/default.nix
index 675fe7695af..6c7d6d5330e 100644
--- a/pkgs/os-specific/linux/bbswitch/default.nix
+++ b/pkgs/os-specific/linux/bbswitch/default.nix
@@ -1,9 +1,9 @@
-{ stdenv, fetchurl, kernelDev }:
+{ stdenv, fetchurl, kernel }:
 
 let
   baseName = "bbswitch";
-  version = "0.7";
-  name = "${baseName}-${version}-${kernelDev.version}";
+  version = "0.8";
+  name = "${baseName}-${version}-${kernel.version}";
 
 in
 
@@ -12,20 +12,20 @@ stdenv.mkDerivation {
 
   src = fetchurl {
     url = "https://github.com/Bumblebee-Project/${baseName}/archive/v${version}.tar.gz";
-    sha256 = "0na6gfnvmp5fjbm430ms342hmrsbr6cf78n6hldqb8js2ry3f8dw";
+    sha256 = "0xql1nv8dafnrcg54f3jsi3ny3cd2ca9iv73pxpgxd2gfczvvjkn";
   };
 
   preBuild = ''
     substituteInPlace Makefile \
-      --replace "\$(shell uname -r)" "${kernelDev.modDirVersion}" \
-      --replace "/lib/modules" "${kernelDev}/lib/modules"
+      --replace "\$(shell uname -r)" "${kernel.modDirVersion}" \
+      --replace "/lib/modules" "${kernel.dev}/lib/modules"
   '';
 
   installPhase = ''
-    ensureDir $out/lib/modules/${kernelDev.modDirVersion}/misc
-    cp bbswitch.ko $out/lib/modules/${kernelDev.modDirVersion}/misc
+    mkdir -p $out/lib/modules/${kernel.modDirVersion}/misc
+    cp bbswitch.ko $out/lib/modules/${kernel.modDirVersion}/misc
 
-    ensureDir $out/bin
+    mkdir -p $out/bin
     tee $out/bin/discrete_vga_poweroff << EOF
     #!/bin/sh
 
diff --git a/pkgs/os-specific/linux/blcr/default.nix b/pkgs/os-specific/linux/blcr/default.nix
index d0d81abb244..43673c899b4 100644
--- a/pkgs/os-specific/linux/blcr/default.nix
+++ b/pkgs/os-specific/linux/blcr/default.nix
@@ -1,13 +1,13 @@
-{ stdenv, fetchurl, kernelDev, perl, makeWrapper }:
+{ stdenv, fetchurl, kernel, perl, makeWrapper }:
 
 # BLCR 0.8.4 works for kernel version up to 2.6.38 (including 2.6.38.x)
 # BLCR 0.8.5 should works for kernel version up to 3.7.1
 
 assert stdenv.isLinux;
-assert builtins.compareVersions "3.7.2" kernelDev.version == 1;
+assert builtins.compareVersions "3.7.2" kernel.version == 1;
 
 stdenv.mkDerivation {
-  name = "blcr_${kernelDev.version}-0.8.5";
+  name = "blcr_${kernel.version}-0.8.5";
 
   src = fetchurl {
     url = http://crd.lbl.gov/assets/Uploads/FTG/Projects/CheckpointRestart/downloads/blcr-0.8.5.tar.gz;
@@ -18,9 +18,9 @@ stdenv.mkDerivation {
 
   preConfigure = ''
     configureFlagsArray=(
-      --with-linux=${kernelDev}/lib/modules/${kernelDev.modDirVersion}/build
-      --with-kmod-dir=$out/lib/modules/${kernelDev.modDirVersion}
-      --with-system-map=${kernelDev}/System.map
+      --with-linux=${kernel.dev}/lib/modules/${kernel.modDirVersion}/build
+      --with-kmod-dir=$out/lib/modules/${kernel.modDirVersion}
+      --with-system-map=${kernel}/System.map
     )
   '';
 
@@ -34,7 +34,7 @@ stdenv.mkDerivation {
   meta = {
     description = "Berkeley Lab Checkpoint/Restart for Linux (BLCR)";
     homepage = https://ftg.lbl.gov/projects/CheckpointRestart/;
-    license = "GPL2";
+    license = stdenv.lib.licenses.gpl2;
     platforms = stdenv.lib.platforms.linux;
     maintainers = with stdenv.lib.maintainers; [
       z77z
diff --git a/pkgs/os-specific/linux/bluez/bluez5.nix b/pkgs/os-specific/linux/bluez/bluez5.nix
index 6bc0759c1a2..2a87611a680 100644
--- a/pkgs/os-specific/linux/bluez/bluez5.nix
+++ b/pkgs/os-specific/linux/bluez/bluez5.nix
@@ -1,22 +1,22 @@
-{ stdenv, fetchurl, pkgconfig, dbus, glib, libusb, alsaLib, python,
+{ stdenv, fetchurl, pkgconfig, dbus, glib, alsaLib, python,
   pythonPackages, pythonDBus, readline, libsndfile, udev, libical,
   systemd }:
 
 assert stdenv.isLinux;
 
 stdenv.mkDerivation rec {
-  name = "bluez-5.8";
+  name = "bluez-5.22";
    
   src = fetchurl {
     url = "mirror://kernel/linux/bluetooth/${name}.tar.xz";
-    sha256 = "1l33lq1lpg7hy26138ir5dj4gl3mql2qxpj20rjnnwyckc3jk700";
+    sha256 = "10h8p89jnhxhjw4x53j4r53i999qjaz82l5591q6q48qb98ndf78";
   };
 
   pythonPath = with pythonPackages;
-    [ pythonDBus pygobject3 recursivePthLoader ];
+    [ pythonDBus pygobject pygobject3 recursivePthLoader ];
 
   buildInputs =
-    [ pkgconfig dbus.libs glib libusb alsaLib python pythonPackages.wrapPython
+    [ pkgconfig dbus.libs glib alsaLib python pythonPackages.wrapPython
       readline libsndfile udev libical
       # Disables GStreamer; not clear what it gains us other than a
       # zillion extra dependencies.
@@ -71,6 +71,7 @@ stdenv.mkDerivation rec {
 
   meta = with stdenv.lib; {
     homepage = http://www.bluez.org/;
+    repositories.git = https://git.kernel.org/pub/scm/bluetooth/bluez.git;
     description = "Bluetooth support for Linux";
     platforms = platforms.linux;
   };
diff --git a/pkgs/os-specific/linux/broadcom-sta-v6/default.nix b/pkgs/os-specific/linux/broadcom-sta-v6/default.nix
deleted file mode 100644
index db4337c0ff2..00000000000
--- a/pkgs/os-specific/linux/broadcom-sta-v6/default.nix
+++ /dev/null
@@ -1,49 +0,0 @@
-{ stdenv, fetchurl, kernelDev }:
-let
-  version = "6_30_223_141";
-in
-stdenv.mkDerivation {
-  name = "broadcom-sta-${version}-${kernelDev.version}";
-
-  src = if stdenv.system == "i686-linux" then (
-    fetchurl {
-      url = "http://www.broadcom.com/docs/linux_sta/hybrid-v35-nodebug-pcoem-${version}.tar.gz";
-      sha256 = "19wra62dpm0x0byksh871yxr128b4v13kzkzqv56igjfpzv36z6m";
-    } ) else (
-    fetchurl {
-      url = "http://www.broadcom.com/docs/linux_sta/hybrid-v35_64-nodebug-pcoem-${version}.tar.gz";
-      sha256 = "0jlvch7d3khmmg5kp80x4ka33hidj8yykqjcqq6j56z2g6wb4dsz";
-    }
-  );
-
-  buildInputs = [ kernelDev ];
-  patches = [
-    ./linux-recent.patch
-    ./license.patch
-  ];
-
-  makeFlags = "KBASE=${kernelDev}/lib/modules/${kernelDev.modDirVersion}";
-
-  unpackPhase = ''
-      sourceRoot=broadcom-sta
-      mkdir "$sourceRoot"
-      tar xvf "$src" -C "$sourceRoot"
-  '';
-
-  installPhase =
-    ''
-      binDir="$out/lib/modules/${kernelDev.modDirVersion}/kernel/net/wireless/"
-      docDir="$out/share/doc/broadcom-sta/"
-      mkdir -p "$binDir" "$docDir"
-      cp wl.ko "$binDir"
-      cp lib/LICENSE.txt "$docDir"
-    '';
-
-  meta = {
-    description = "Kernel module driver for some Broadcom's wireless cards";
-    homepage = http://www.broadcom.com/support/802.11/linux_sta.php;
-    license = "unfree-redistributable";
-    maintainers = with stdenv.lib.maintainers; [ phreedom vcunat ];
-    platforms = stdenv.lib.platforms.linux;
-  };
-}
diff --git a/pkgs/os-specific/linux/broadcom-sta-v6/license.patch b/pkgs/os-specific/linux/broadcom-sta-v6/license.patch
deleted file mode 100644
index aebb4636519..00000000000
--- a/pkgs/os-specific/linux/broadcom-sta-v6/license.patch
+++ /dev/null
@@ -1,13 +0,0 @@
-diff -Naur hybrid-portsrc-x86_32-v5_10_91_9.orig/src/wl/sys/wl_linux.c hybrid-portsrc-x86_32-v5_10_91_9/src/wl/sys/wl_linux.c
---- hybrid-portsrc-x86_32-v5_10_91_9.orig/src/wl/sys/wl_linux.c	2009-04-23 02:48:59.000000000 +0900
-+++ hybrid-portsrc-x86_32-v5_10_91_9/src/wl/sys/wl_linux.c	2009-05-08 00:48:20.000000000 +0900
-@@ -171,6 +171,8 @@
- static void wl_free_if(wl_info_t *wl, wl_if_t *wlif);
- static void wl_get_driver_info(struct net_device *dev, struct ethtool_drvinfo *info);
- 
-+MODULE_LICENSE("MIXED/Proprietary");
-+
- #if defined(WL_CONFIG_RFKILL)
- #include <linux/rfkill.h>
- static int wl_init_rfkill(wl_info_t *wl);
-
diff --git a/pkgs/os-specific/linux/broadcom-sta/cfg80211_ibss_joined-channel-parameter.patch b/pkgs/os-specific/linux/broadcom-sta/cfg80211_ibss_joined-channel-parameter.patch
new file mode 100644
index 00000000000..5596c0ebcf2
--- /dev/null
+++ b/pkgs/os-specific/linux/broadcom-sta/cfg80211_ibss_joined-channel-parameter.patch
@@ -0,0 +1,17 @@
+Add channel parameter to cfg80211_ibss_joined call
+
+--- a/src/wl/sys/wl_cfg80211_hybrid.c
++++ b/src/wl/sys/wl_cfg80211_hybrid.c
+@@ -1841,7 +1841,12 @@ wl_notify_connect_status(struct wl_cfg80211_priv *wl, struct net_device *ndev,
+ 			wl_get_assoc_ies(wl);
+ 			memcpy(&wl->bssid, &e->addr, ETHER_ADDR_LEN);
+ 			wl_update_bss_info(wl);
++#if LINUX_VERSION_CODE < KERNEL_VERSION(3, 15, 0)
+ 			cfg80211_ibss_joined(ndev, (u8 *)&wl->bssid, GFP_KERNEL);
++#else
++			cfg80211_ibss_joined(ndev, (u8 *)&wl->bssid,
++			                     &wl->conf->channel, GFP_KERNEL);
++#endif
+ 			set_bit(WL_STATUS_CONNECTED, &wl->status);
+ 			wl->profile->active = true;
+ 		}
diff --git a/pkgs/os-specific/linux/broadcom-sta/default.nix b/pkgs/os-specific/linux/broadcom-sta/default.nix
index 816a099e243..1ed13c2e450 100644
--- a/pkgs/os-specific/linux/broadcom-sta/default.nix
+++ b/pkgs/os-specific/linux/broadcom-sta/default.nix
@@ -1,38 +1,38 @@
-{ stdenv, fetchurl, kernelDev }:
-
-let version = "5_100_82_112";
-    bits = if stdenv.system == "i686-linux" then "32" else
-      assert stdenv.system == "x86_64-linux"; "64";
+{ stdenv, fetchurl, kernel }:
+let
+  version = "6_30_223_141";
 in
-
 stdenv.mkDerivation {
-  name = "broadcom-sta-${version}-${kernelDev.version}";
-
-  src = fetchurl {
-    url = "http://www.broadcom.com/docs/linux_sta/hybrid-portsrc_x86_${bits}-v${version}.tar.gz";
-    sha256 = if bits == "32"
-      then "1rvhw9ngw0djxyyjx5m01c0js89zs3xiwmra03al6f9q7cbf7d45"
-      else "1qsarnry10f5m8a73wbr9cg2ifs00sqg6x0ay59l72vl9hb2zlww";
-  };
-
-  buildInputs = [ kernelDev ];
-  patches =
-    [ ./makefile.patch ./linux-2.6.39.patch ./linux-3.2.patch
-      ./linux-3.4.patch ./license.patch
-    ];
-
-  makeFlags = "KDIR=${kernelDev}/lib/modules/${kernelDev.modDirVersion}/build";
-
-  unpackPhase =
-    ''
+  name = "broadcom-sta-${version}-${kernel.version}";
+
+  src = if stdenv.system == "i686-linux" then (
+    fetchurl {
+      url = "http://www.broadcom.com/docs/linux_sta/hybrid-v35-nodebug-pcoem-${version}.tar.gz";
+      sha256 = "19wra62dpm0x0byksh871yxr128b4v13kzkzqv56igjfpzv36z6m";
+    } ) else (
+    fetchurl {
+      url = "http://www.broadcom.com/docs/linux_sta/hybrid-v35_64-nodebug-pcoem-${version}.tar.gz";
+      sha256 = "0jlvch7d3khmmg5kp80x4ka33hidj8yykqjcqq6j56z2g6wb4dsz";
+    }
+  );
+
+  patches = [
+    ./linux-recent.patch
+    ./license.patch
+    ./cfg80211_ibss_joined-channel-parameter.patch
+  ];
+
+  makeFlags = "KBASE=${kernel.dev}/lib/modules/${kernel.modDirVersion}";
+
+  unpackPhase = ''
       sourceRoot=broadcom-sta
       mkdir "$sourceRoot"
       tar xvf "$src" -C "$sourceRoot"
-    '';
+  '';
 
   installPhase =
     ''
-      binDir="$out/lib/modules/${kernelDev.modDirVersion}/kernel/net/wireless/"
+      binDir="$out/lib/modules/${kernel.modDirVersion}/kernel/net/wireless/"
       docDir="$out/share/doc/broadcom-sta/"
       mkdir -p "$binDir" "$docDir"
       cp wl.ko "$binDir"
@@ -43,7 +43,7 @@ stdenv.mkDerivation {
     description = "Kernel module driver for some Broadcom's wireless cards";
     homepage = http://www.broadcom.com/support/802.11/linux_sta.php;
     license = "unfree-redistributable";
-    maintainers = [ stdenv.lib.maintainers.vcunat ];
+    maintainers = with stdenv.lib.maintainers; [ phreedom vcunat ];
     platforms = stdenv.lib.platforms.linux;
   };
 }
diff --git a/pkgs/os-specific/linux/broadcom-sta/license.patch b/pkgs/os-specific/linux/broadcom-sta/license.patch
index b320d977e8b..aebb4636519 100644
--- a/pkgs/os-specific/linux/broadcom-sta/license.patch
+++ b/pkgs/os-specific/linux/broadcom-sta/license.patch
@@ -1,12 +1,13 @@
 diff -Naur hybrid-portsrc-x86_32-v5_10_91_9.orig/src/wl/sys/wl_linux.c hybrid-portsrc-x86_32-v5_10_91_9/src/wl/sys/wl_linux.c
 --- hybrid-portsrc-x86_32-v5_10_91_9.orig/src/wl/sys/wl_linux.c	2009-04-23 02:48:59.000000000 +0900
 +++ hybrid-portsrc-x86_32-v5_10_91_9/src/wl/sys/wl_linux.c	2009-05-08 00:48:20.000000000 +0900
-@@ -163,6 +163,8 @@
+@@ -171,6 +171,8 @@
  static void wl_free_if(wl_info_t *wl, wl_if_t *wlif);
  static void wl_get_driver_info(struct net_device *dev, struct ethtool_drvinfo *info);
  
 +MODULE_LICENSE("MIXED/Proprietary");
 +
- static struct pci_device_id wl_id_table[] = {
- 	{ PCI_VENDOR_ID_BROADCOM, 0x4311, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0 }, 
- 	{ PCI_VENDOR_ID_BROADCOM, 0x4312, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0 }, 
+ #if defined(WL_CONFIG_RFKILL)
+ #include <linux/rfkill.h>
+ static int wl_init_rfkill(wl_info_t *wl);
+
diff --git a/pkgs/os-specific/linux/broadcom-sta/linux-2.6.39.patch b/pkgs/os-specific/linux/broadcom-sta/linux-2.6.39.patch
deleted file mode 100644
index ca07c918c36..00000000000
--- a/pkgs/os-specific/linux/broadcom-sta/linux-2.6.39.patch
+++ /dev/null
@@ -1,11 +0,0 @@
---- old/src/wl/sys/wl_cfg80211.c
-+++ new/src/wl/sys/wl_cfg80211.c
-@@ -1811,7 +1811,7 @@
- 	notif_bss_info->frame_len = offsetof(struct ieee80211_mgmt, u.beacon.variable) +
- 	                            wl_get_ielen(wl);
- 	freq = ieee80211_channel_to_frequency(notif_bss_info->channel 
--#if LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 39)
-+#if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 39)
- 		,(notif_bss_info->channel <= CH_MAX_2G_CHANNEL) ? IEEE80211_BAND_2GHZ : IEEE80211_BAND_5GHZ
- #endif
- 	);
diff --git a/pkgs/os-specific/linux/broadcom-sta/linux-3.2.patch b/pkgs/os-specific/linux/broadcom-sta/linux-3.2.patch
deleted file mode 100644
index b491537cb86..00000000000
--- a/pkgs/os-specific/linux/broadcom-sta/linux-3.2.patch
+++ /dev/null
@@ -1,13 +0,0 @@
-diff -Naur broadcom-sta-5.100.82.112.orig/src/wl/sys/wl_linux.c broadcom-sta-5.100.82.112/src/wl/sys/wl_linux.c
---- broadcom-sta-5.100.82.112.orig/src/wl/sys/wl_linux.c	2011-10-23 01:56:55.000000000 +0900
-+++ broadcom-sta-5.100.82.112/src/wl/sys/wl_linux.c	2011-11-22 00:56:07.021520421 +0900
-@@ -385,7 +385,9 @@
- #endif
- 	.ndo_get_stats = wl_get_stats,
- 	.ndo_set_mac_address = wl_set_mac_address,
-+#if LINUX_VERSION_CODE < KERNEL_VERSION(3, 2, 0)
- 	.ndo_set_multicast_list = wl_set_multicast_list,
-+#endif
- 	.ndo_do_ioctl = wl_ioctl
- };
- 
diff --git a/pkgs/os-specific/linux/broadcom-sta/linux-3.4.patch b/pkgs/os-specific/linux/broadcom-sta/linux-3.4.patch
deleted file mode 100644
index 854131c641b..00000000000
--- a/pkgs/os-specific/linux/broadcom-sta/linux-3.4.patch
+++ /dev/null
@@ -1,12 +0,0 @@
---- broadcom-sta.orig/src/wl/sys/wl_linux.c
-+++ broadcom-sta.new/src/wl/sys/wl_linux.c
-@@ -40,7 +40,9 @@
- #include <linux/pci_ids.h>
- #define WLC_MAXBSSCFG          1
- 
-+#if LINUX_VERSION_CODE < KERNEL_VERSION(3, 4, 0)
- #include <asm/system.h>
-+#endif
- #include <asm/io.h>
- #include <asm/irq.h>
- #include <asm/pgtable.h>
diff --git a/pkgs/os-specific/linux/broadcom-sta-v6/linux-recent.patch b/pkgs/os-specific/linux/broadcom-sta/linux-recent.patch
index 97a331a2bd7..97a331a2bd7 100644
--- a/pkgs/os-specific/linux/broadcom-sta-v6/linux-recent.patch
+++ b/pkgs/os-specific/linux/broadcom-sta/linux-recent.patch
diff --git a/pkgs/os-specific/linux/broadcom-sta/makefile.patch b/pkgs/os-specific/linux/broadcom-sta/makefile.patch
deleted file mode 100644
index 6ba8527e267..00000000000
--- a/pkgs/os-specific/linux/broadcom-sta/makefile.patch
+++ /dev/null
@@ -1,16 +0,0 @@
---- src/Makefile	2010-10-08 00:32:59.000000000 +0200
-+++ src/Makefile	2010-11-09 11:06:28.832999850 +0100
-@@ -27,10 +27,10 @@
- EXTRA_LDFLAGS      := $(src)/lib/wlc_hybrid.o_shipped
- 
- all:
--	KBUILD_NOPEDANTIC=1 make -C /lib/modules/`uname -r`/build M=`pwd`
-+	KBUILD_NOPEDANTIC=1 make -C ${KDIR} M=`pwd`
- 
- clean:
--	KBUILD_NOPEDANTIC=1 make -C /lib/modules/`uname -r`/build M=`pwd` clean
-+	KBUILD_NOPEDANTIC=1 make -C ${KDIR} clean
- 
- install:
--	install -D -m 755 wl.ko /lib/modules/`uname -r`/kernel/drivers/net/wireless/wl.ko
-+	install -D -m 755 wl.ko $out/lib/modules/${kernelVersion}/kernel/drivers/net/wireless/wl.ko
diff --git a/pkgs/os-specific/linux/busybox/default.nix b/pkgs/os-specific/linux/busybox/default.nix
index a24e0fd2307..98fedb2d3f4 100644
--- a/pkgs/os-specific/linux/busybox/default.nix
+++ b/pkgs/os-specific/linux/busybox/default.nix
@@ -28,6 +28,10 @@ let
   nixConfig = ''
     CONFIG_PREFIX "$out"
     CONFIG_INSTALL_NO_USR y
+
+    # Use the external mount.cifs program.
+    CONFIG_FEATURE_MOUNT_CIFS n
+    CONFIG_FEATURE_MOUNT_HELPERS y
   '';
 
   staticConfig = stdenv.lib.optionalString enableStatic ''
@@ -37,23 +41,20 @@ let
 in
 
 stdenv.mkDerivation rec {
-  name = "busybox-1.20.2";
+  name = "busybox-1.22.1";
 
   src = fetchurl {
     url = "http://busybox.net/downloads/${name}.tar.bz2";
-    sha256 = "10k8kgrprll9hxfm9gc3jl7kkq79g6l2pygn5snqwqg5v80zy4zb";
+    sha256 = "12v7nri79v8gns3inmz4k24q7pcnwi00hybs0wddfkcy1afh42xf";
   };
 
-  # Remove this patch after the next busybox update.
-  patches = [ ./include-missing-sys-resource-header.patch ];
-
   configurePhase = ''
     make defconfig
     ${configParser}
     cat << EOF | parseconfig
     ${staticConfig}
-    ${extraConfig}
     ${nixConfig}
+    ${extraConfig}
     $extraCrossConfig
     EOF
     make oldconfig
@@ -73,7 +74,7 @@ stdenv.mkDerivation rec {
   meta = {
     description = "Tiny versions of common UNIX utilities in a single small executable";
     homepage = http://busybox.net/;
-    license = "GPLv2";
+    license = stdenv.lib.licenses.gpl2;
     maintainers = with stdenv.lib.maintainers; [viric];
     platforms = with stdenv.lib.platforms; linux;
   };
diff --git a/pkgs/os-specific/linux/can-utils/default.nix b/pkgs/os-specific/linux/can-utils/default.nix
new file mode 100644
index 00000000000..6a3fbd33d68
--- /dev/null
+++ b/pkgs/os-specific/linux/can-utils/default.nix
@@ -0,0 +1,24 @@
+{ stdenv, fetchgit }:
+
+stdenv.mkDerivation rec {
+  name = "can-utils-${version}";
+  # There are no releases (source archives or git tags), so use the date of the
+  # latest commit in git master as version number.
+  version = "20140227";
+
+  src = fetchgit {
+    url = "https://git.gitorious.org/linux-can/can-utils.git";
+    rev = "67a2bdcd336e6becfa5784742e18c88dbeddc973";
+    sha256 = "0pnnjl141wf3kbf256m6qz9mxz0144z36qqb43skialzcnlhga38";
+  };
+
+  preConfigure = ''makeFlagsArray+=(PREFIX="$out")'';
+
+  meta = with stdenv.lib; {
+    description = "CAN userspace utilities and tools (for use with Linux SocketCAN)";
+    homepage = "https://gitorious.org/linux-can/can-utils";
+    license = licenses.gpl2Plus;
+    platforms = platforms.linux;
+    maintainers = [ maintainers.bjornfor ];
+  };
+}
diff --git a/pkgs/os-specific/linux/checkpolicy/default.nix b/pkgs/os-specific/linux/checkpolicy/default.nix
index 9125c84bd7a..1f06fb66218 100644
--- a/pkgs/os-specific/linux/checkpolicy/default.nix
+++ b/pkgs/os-specific/linux/checkpolicy/default.nix
@@ -2,17 +2,20 @@
 stdenv.mkDerivation rec {
 
   name = "checkpolicy-${version}";
-  version = "2.1.11";
+  version = "2.3";
   inherit (libsepol) se_release se_url;
 
   src = fetchurl {
     url = "${se_url}/${se_release}/checkpolicy-${version}.tar.gz";
-    sha256 = "1wahs32l4jjlg0s3lyihdhvwmsy7yyvq5pk96q9lsiilc5vvrb06";
+    sha256 = "0yr0r2cxz9lbj7i0wqgcd4wjvc6zf1fmqk0xjybnkdpcmw8jsqwh";
   };
 
   buildInputs = [ libsepol libselinux bison flex ];
 
-  preBuild = '' makeFlags="$makeFlags LEX=flex LIBDIR=${libsepol}/lib PREFIX=$out" '';
+  preBuild = ''
+    makeFlags="$makeFlags LEX=flex LIBDIR=${libsepol}/lib PREFIX=$out"
+    sed -e 's@[.]o$@& ../lex.yy.o@' -i test/Makefile
+  '';
 
   meta = with stdenv.lib; {
     description = "SELinux policy compiler";
diff --git a/pkgs/os-specific/linux/checksec/0001-attempt-to-modprobe-config-before-checking-kernel.patch b/pkgs/os-specific/linux/checksec/0001-attempt-to-modprobe-config-before-checking-kernel.patch
new file mode 100644
index 00000000000..2caf52f3c0a
--- /dev/null
+++ b/pkgs/os-specific/linux/checksec/0001-attempt-to-modprobe-config-before-checking-kernel.patch
@@ -0,0 +1,27 @@
+From 6503848d9e0eb009e5f462116a963beacb208930 Mon Sep 17 00:00:00 2001
+From: Austin Seipp <aseipp@pobox.com>
+Date: Thu, 20 Feb 2014 00:11:44 -0600
+Subject: [PATCH] attempt to 'modprobe config' before checking kernel
+
+Signed-off-by: Austin Seipp <aseipp@pobox.com>
+---
+ checksec.sh | 3 ++-
+ 1 file changed, 2 insertions(+), 1 deletion(-)
+
+diff --git a/checksec.sh b/checksec.sh
+index dd1f72e..63acc29 100644
+--- a/checksec.sh
++++ b/checksec.sh
+@@ -337,7 +337,8 @@ kernelcheck() {
+   printf "  userspace processes, this option lists the status of kernel configuration\n"
+   printf "  options that harden the kernel itself against attack.\n\n"
+   printf "  Kernel config: "
+- 
++
++  modprobe configs 2> /dev/null
+   if [ -f /proc/config.gz ] ; then
+     kconfig="zcat /proc/config.gz"
+     printf "\033[32m/proc/config.gz\033[m\n\n"
+-- 
+1.8.3.2
+
diff --git a/pkgs/os-specific/linux/checksec/default.nix b/pkgs/os-specific/linux/checksec/default.nix
new file mode 100644
index 00000000000..4701d774dfd
--- /dev/null
+++ b/pkgs/os-specific/linux/checksec/default.nix
@@ -0,0 +1,42 @@
+{ stdenv, fetchurl, file, findutils, elfutils, glibc }:
+
+stdenv.mkDerivation rec {
+  name = "checksec-${version}";
+  version = "1.5";
+  src = fetchurl {
+    url    = "http://www.trapkit.de/tools/checksec.sh";
+    sha256 = "0iq9v568mk7g7ksa1939g5f5sx7ffq8s8n2ncvphvlckjgysgf3p";
+  };
+
+  patches = [ ./0001-attempt-to-modprobe-config-before-checking-kernel.patch ];
+
+  unpackPhase = ''
+    mkdir ${name}-${version}
+    cp $src ${name}-${version}/checksec.sh
+    cd ${name}-${version}
+  '';
+
+  installPhase = ''
+    mkdir -p $out/bin
+    cp checksec.sh $out/bin/checksec
+    chmod +x $out/bin/checksec
+    substituteInPlace $out/bin/checksec --replace /bin/bash ${stdenv.shell}
+    substituteInPlace $out/bin/checksec --replace /lib/libc.so.6 ${glibc}/lib/libc.so.6
+    substituteInPlace $out/bin/checksec --replace find ${findutils}/bin/find
+    substituteInPlace $out/bin/checksec --replace "file $" "${file}/bin/file $"
+    substituteInPlace $out/bin/checksec --replace "xargs file" "xargs ${file}/bin/file"
+    substituteInPlace $out/bin/checksec --replace " readelf -" " ${elfutils}/bin/readelf -"
+    substituteInPlace $out/bin/checksec --replace "(readelf -" "(${elfutils}/bin/readelf -"
+    substituteInPlace $out/bin/checksec --replace "command_exists readelf" "command_exists ${elfutils}/bin/readelf"
+  '';
+
+  phases = "unpackPhase patchPhase installPhase";
+
+  meta = {
+    description = "A tool for checking security bits on executables";
+    homepage    = "http://www.trapkit.de/tools/checksec.html";
+    license     = stdenv.lib.licenses.bsd3;
+    platforms   = stdenv.lib.platforms.linux;
+    maintainers = [ stdenv.lib.maintainers.thoughtpolice ];
+  };
+}
diff --git a/pkgs/os-specific/linux/cifs-utils/default.nix b/pkgs/os-specific/linux/cifs-utils/default.nix
index 0f8801ef58e..ce609c5be47 100644
--- a/pkgs/os-specific/linux/cifs-utils/default.nix
+++ b/pkgs/os-specific/linux/cifs-utils/default.nix
@@ -1,15 +1,13 @@
 { stdenv, fetchurl }:
 
 stdenv.mkDerivation rec {
-  name = "cifs-utils-5.6";
+  name = "cifs-utils-6.3";
 
   src = fetchurl {
     url = "ftp://ftp.samba.org/pub/linux-cifs/cifs-utils/${name}.tar.bz2";
-    sha256 = "0f619nw1163bcmfc83mmqj31qdkl68wfm81vynx3d8q0m0k1ll7i";
+    sha256 = "0nrpd3ibzfhdxgq1pw0jhzx163z5jvq4qcjxl35qlqj74lm3pxzz";
   };
 
-  patches = [ ./find-systemd-ask-password-via-path.patch ];
-
   makeFlags = "root_sbindir=$(out)/sbin";
 
   meta = {
diff --git a/pkgs/os-specific/linux/cifs-utils/find-systemd-ask-password-via-path.patch b/pkgs/os-specific/linux/cifs-utils/find-systemd-ask-password-via-path.patch
deleted file mode 100644
index 428cb75edad..00000000000
--- a/pkgs/os-specific/linux/cifs-utils/find-systemd-ask-password-via-path.patch
+++ /dev/null
@@ -1,22 +0,0 @@
-diff -ubr cifs-utils-5.9-orig/mount.cifs.c cifs-utils-5.9/mount.cifs.c
---- cifs-utils-5.9-orig/mount.cifs.c	2013-03-05 10:53:19.375464790 +0100
-+++ cifs-utils-5.9/mount.cifs.c	2013-03-05 11:41:40.704946110 +0100
-@@ -1634,7 +1634,7 @@
- }
- 
- /*
-- * If systemd is running and /bin/systemd-ask-password --
-+ * If systemd is running and systemd-ask-password --
-  * is available, then use that else fallback on getpass(..)
-  *
-  * Returns: @input or NULL on error
-@@ -1657,7 +1657,7 @@
- 		FILE *ask_pass_fp = NULL;
- 
- 		cmd = ret = NULL;
--		if (asprintf(&cmd, "/bin/systemd-ask-password \"%s\"", prompt) >= 0) {
-+		if (asprintf(&cmd, "/run/current-system/sw/bin/systemd-ask-password \"%s\"", prompt) >= 0) {
- 			ask_pass_fp = popen (cmd, "re");
- 			free (cmd);
- 		}
-Only in cifs-utils-5.9/: mount.cifs.c.orig
diff --git a/pkgs/os-specific/linux/conky/default.nix b/pkgs/os-specific/linux/conky/default.nix
index 086b792b4cd..92b97ffb592 100644
--- a/pkgs/os-specific/linux/conky/default.nix
+++ b/pkgs/os-specific/linux/conky/default.nix
@@ -1,5 +1,33 @@
-{ stdenv, fetchurl, pkgconfig, libxml2, curl, wirelesstools, glib, openssl
-, ncurses }:
+{ stdenv, fetchurl, pkgconfig
+
+# dependencies
+, glib, ncurses
+
+# optional features without extra dependencies
+, mpdSupport   ? true
+
+# optional features with extra dependencies
+, x11Support   ? false, x11           ? null
+, xdamage      ? false, libXdamage    ? null
+, wireless     ? false, wirelesstools ? null
+, luaSupport   ? false, lua5          ? null
+
+, rss          ? false
+, weatherMetar ? false
+, weatherXoap  ? false
+, curl ? null, libxml2 ? null
+}:
+
+assert luaSupport -> lua5          != null;
+assert wireless   -> wirelesstools != null;
+assert x11Support -> x11           != null;
+assert xdamage    -> x11Support && libXdamage != null;
+
+assert rss          -> curl != null && libxml2 != null;
+assert weatherMetar -> curl != null;
+assert weatherXoap  -> curl != null && libxml2 != null;
+
+with stdenv.lib;
 
 stdenv.mkDerivation rec {
   name = "conky-1.9.0";
@@ -9,17 +37,37 @@ stdenv.mkDerivation rec {
     sha256 = "0vxvjmi3cdvnp994sv5zcdyncfn0mlxa71p2wm9zpyrmy58bbwds";
   };
 
-  patches = [ ./stdbool.patch ];
+  NIX_LDFLAGS = "-lgcc_s";
+
+  buildInputs = [ pkgconfig glib ncurses ]
+    ++ optional  luaSupport   lua5
+    ++ optional  wireless     wirelesstools
+    ++ optional  x11Support   x11
+    ++ optional  xdamage      libXdamage
+
+    ++ optionals rss          [ curl libxml2 ]
+    ++ optional  weatherMetar curl
+    ++ optionals weatherXoap  [ curl libxml2 ]
+    ;
 
-  buildInputs = [ pkgconfig libxml2 curl wirelesstools glib openssl ncurses ];
   configureFlags =
-    (map (x: "--disable-${x}") [ "x11" "xdamage" "own-window" "xft" "lua" ])
-    ++ (map (x: "--enable-${x}") [ "mpd" "double-buffer" "wlan" "rss"
-                                   "weather-metar" "weather-xoap" ]);
+    let flag = state: flags: if state then map (x: "--enable-${x}")  flags
+                                      else map (x: "--disable-${x}") flags;
+     in flag mpdSupport   [ "mpd" ]
+
+     ++ flag luaSupport   [ "lua" ]
+     ++ flag wireless     [ "wlan" ]
+     ++ flag x11Support   [ "x11" "xft" "argb" "double-buffer" "own-window" ] # conky won't compile without --enable-own-window
+     ++ flag xdamage      [ "xdamage" ]
+
+     ++ flag rss          [ "rss" ]
+     ++ flag weatherMetar [ "weather-metar" ]
+     ++ flag weatherXoap  [ "weather-xoap" ]
+     ;
 
   meta = {
     homepage = http://conky.sourceforge.net/;
-    description = "Conky is an advanced, highly configurable system monitor complied without X based on torsmo";
+    description = "Conky is an advanced, highly configurable system monitor based on torsmo";
     maintainers = [ stdenv.lib.maintainers.guibert ];
     license = stdenv.lib.licenses.gpl3Plus;
   };
diff --git a/pkgs/os-specific/linux/conky/stdbool.patch b/pkgs/os-specific/linux/conky/stdbool.patch
deleted file mode 100644
index 3f0b714a1f0..00000000000
--- a/pkgs/os-specific/linux/conky/stdbool.patch
+++ /dev/null
@@ -1,12 +0,0 @@
-diff --git a/src/conky.c b/src/conky.c
-index 5848b61..69a3d45 100644
---- a/src/conky.c
-+++ b/src/conky.c
-@@ -34,6 +34,7 @@
- #include "common.h"
- #include "timed_thread.h"
- #include <stdarg.h>
-+#include <stdbool.h>
- #include <math.h>
- #include <time.h>
- #include <locale.h>
diff --git a/pkgs/os-specific/linux/consoletools/default.nix b/pkgs/os-specific/linux/consoletools/default.nix
index 537cc386402..f8be37edfe2 100644
--- a/pkgs/os-specific/linux/consoletools/default.nix
+++ b/pkgs/os-specific/linux/consoletools/default.nix
@@ -1,13 +1,12 @@
-{ stdenv, fetchgit, SDL }:
+{ stdenv, fetchurl, SDL }:
 
 stdenv.mkDerivation rec {
   name = "linuxconsoletools-${version}";
-  version = "1.4.3";
+  version = "1.4.6";
 
-  src = fetchgit {
-    url = "git://linuxconsole.git.sourceforge.net/gitroot/linuxconsole/linuxconsole";
-    rev = "dac2cae0e5795ddc27b76a92767dd9e07a10621e";
-    sha256 = "350b008e614923dbd548fcaaf2842b39433acdcf595e2ce8aaf1599f076d331d";
+  src = fetchurl {
+    url = "mirror://sourceforge/linuxconsole/${name}.tar.bz2";
+    sha256 = "0035yhjbjdis5wqmbdz67xq61065x7vrx5mb7kb1rhrx3ag43wcf";
   };
 
   buildInputs = [ SDL ];
diff --git a/pkgs/os-specific/linux/conspy/default.nix b/pkgs/os-specific/linux/conspy/default.nix
index 44689cd5d62..d252d9ce162 100644
--- a/pkgs/os-specific/linux/conspy/default.nix
+++ b/pkgs/os-specific/linux/conspy/default.nix
@@ -3,11 +3,11 @@ let
   s = # Generated upstream information
   rec {
     baseName="conspy";
-    version="1.8";
+    version="1.9";
     name="${baseName}-${version}";
-    hash=sha256;
-    url="http://ace-host.stuart.id.au/russell/files/conspy/conspy-1.8.tar.gz";
-    sha256="1jc2maqp4w4mzlr3s8yni03w1p9sir5hb7gha3ffxj4n32nx42dq";
+    hash="1ndwdx8x5lnjl6cddy1d8g8m7ndxyj3wrs100w2bp9gnvbxbb8vv";
+    url="http://ace-host.stuart.id.au/russell/files/conspy/conspy-1.9.tar.gz";
+    sha256="1ndwdx8x5lnjl6cddy1d8g8m7ndxyj3wrs100w2bp9gnvbxbb8vv";
   };
   buildInputs = [
     autoconf automake ncurses
diff --git a/pkgs/os-specific/linux/cpufrequtils/default.nix b/pkgs/os-specific/linux/cpufrequtils/default.nix
index 85907ff0212..d056e60f2da 100644
--- a/pkgs/os-specific/linux/cpufrequtils/default.nix
+++ b/pkgs/os-specific/linux/cpufrequtils/default.nix
@@ -2,14 +2,19 @@
 
 assert stdenv.system == "i686-linux" || stdenv.system == "x86_64-linux";
 
-stdenv.mkDerivation {
+stdenv.mkDerivation rec {
   name = "cpufrequtils-008";
 
   src = fetchurl {
-    url = http://ftp.be.debian.org/pub/linux/utils/kernel/cpufreq/cpufrequtils-008.tar.gz;
-    md5 = "52d3e09e47ffef634833f7fab168eccf";
+    url = "http://ftp.be.debian.org/pub/linux/utils/kernel/cpufreq/${name}.tar.gz";
+    sha256 = "127i38d4w1hv2dzdy756gmbhq25q3k34nqb2s0xlhsfhhdqs0lq0";
   };
 
+  patches = [
+    # I am not 100% sure that this is ok, but it breaks repeatable builds.
+    ./remove-pot-creation-date.patch
+  ];
+
   patchPhase = ''
     sed -e "s@= /usr/bin/@= @g" \
       -e "s@/usr/@$out/@" \
diff --git a/pkgs/os-specific/linux/cpufrequtils/remove-pot-creation-date.patch b/pkgs/os-specific/linux/cpufrequtils/remove-pot-creation-date.patch
new file mode 100644
index 00000000000..0116ed9eab0
--- /dev/null
+++ b/pkgs/os-specific/linux/cpufrequtils/remove-pot-creation-date.patch
@@ -0,0 +1,24 @@
+diff -u cpufrequtils-008/Makefile cpufrequtils-008.new/Makefile
+--- cpufrequtils-008/Makefile	2012-05-06 01:17:18.000000000 +0200
++++ cpufrequtils-008.new/Makefile	2013-08-16 20:52:29.961086536 +0200
+@@ -205,7 +205,8 @@
+ 	@xgettext --default-domain=$(PACKAGE) --add-comments \
+ 		--keyword=_ --keyword=N_ $(UTIL_SRC) && \
+ 	test -f $(PACKAGE).po && \
+-	mv -f $(PACKAGE).po po/$(PACKAGE).pot
++	mv -f $(PACKAGE).po po/$(PACKAGE).pot && \
++        sed -i -e'/POT-Creation/d' po/*.pot
+ 
+ update-gmo: po/$(PACKAGE).pot
+ 	 @for HLANG in $(LANGUAGES); do \
+@@ -217,6 +218,7 @@
+ 			echo "msgmerge for $$HLANG failed!"; \
+ 			rm -f po/$$HLANG.new.po; \
+ 		fi; \
++		sed -i -e'/POT-Creation/d' po/*.po; \
+ 		msgfmt --statistics -o po/$$HLANG.gmo po/$$HLANG.po; \
+ 	done;
+ 
+Common subdirectories: cpufrequtils-008/man and cpufrequtils-008.new/man
+Common subdirectories: cpufrequtils-008/po and cpufrequtils-008.new/po
+Common subdirectories: cpufrequtils-008/utils and cpufrequtils-008.new/utils
diff --git a/pkgs/os-specific/linux/cpupower/default.nix b/pkgs/os-specific/linux/cpupower/default.nix
new file mode 100644
index 00000000000..bf6e8c36f3d
--- /dev/null
+++ b/pkgs/os-specific/linux/cpupower/default.nix
@@ -0,0 +1,42 @@
+{ stdenv, fetchurl, kernel, coreutils, pciutils, gettext }:
+
+stdenv.mkDerivation {
+  name = "cpupower-${kernel.version}";
+
+  src = kernel.src;
+
+  buildInputs = [ coreutils pciutils gettext ];
+
+  configurePhase = ''
+    cd tools/power/cpupower
+    sed -i 's,/bin/true,${coreutils}/bin/true,' Makefile
+    sed -i 's,/bin/pwd,${coreutils}/bin/pwd,' Makefile
+    sed -i 's,/usr/bin/install,${coreutils}/bin/install,' Makefile
+  '';
+
+  buildPhase = ''
+    make
+  '';
+
+  installPhase = ''
+    make \
+      bindir="$out/bin" \
+      sbindir="$out/sbin" \
+      mandir="$out/share/man" \
+      includedir="$out/include" \
+      libdir="$out/lib" \
+      localedir="$out/share/locale" \
+      docdir="$out/share/doc/cpupower" \
+      confdir="$out/etc" \
+      install install-man
+  '';
+
+  enableParallelBuilding = true;
+
+  meta = with stdenv.lib; {
+    description = "Tool to examine and tune power saving features.";
+    homepage = https://www.kernel.org.org/;
+    license = licenses.gpl2;
+    platforms = platforms.linux;
+  };
+}
diff --git a/pkgs/os-specific/linux/criu/default.nix b/pkgs/os-specific/linux/criu/default.nix
new file mode 100644
index 00000000000..433cc2c81d7
--- /dev/null
+++ b/pkgs/os-specific/linux/criu/default.nix
@@ -0,0 +1,38 @@
+{ stdenv, fetchurl, protobuf, protobufc, asciidoc
+, xmlto, utillinux, docbook_xsl, libpaper }:
+
+stdenv.mkDerivation rec {
+  name    = "criu-${version}";
+  version = "1.3-rc2";
+
+  src = fetchurl {
+    url    = "http://download.openvz.org/criu/${name}.tar.bz2";
+    sha256 = "1h9ii91aq8cja22j3520vg3qb3y9h6c064s4115s2ldylm8jmi0s";
+  };
+
+  enableParallelBuilding = true;
+  buildInputs = [ protobuf protobufc asciidoc xmlto libpaper ];
+
+  patchPhase = ''
+    chmod +w ./scripts/gen-offsets.sh
+    substituteInPlace ./scripts/gen-offsets.sh --replace hexdump ${utillinux}/bin/hexdump
+    substituteInPlace ./Documentation/Makefile --replace "2>/dev/null" ""
+    substituteInPlace ./Documentation/Makefile --replace "--skip-validation" "--skip-validation -x ${docbook_xsl}/xml/xsl/docbook/manpages/docbook.xsl"
+  '';
+
+  configurePhase = "make config PREFIX=$out";
+  buildPhase     = "make PREFIX=$out";
+
+  installPhase = ''
+    mkdir -p $out/etc/logrotate.d
+    make install PREFIX=$out LIBDIR=$out/lib ASCIIDOC=${asciidoc}/bin/asciidoc XMLTO=${xmlto}/bin/xmlto
+  '';
+
+  meta = {
+    description = "userspace checkpoint/restore for Linux";
+    homepage    = "http://criu.org";
+    license     = stdenv.lib.licenses.gpl2;
+    platforms   = [ "x86_64-linux" ];
+    maintainers = [ stdenv.lib.maintainers.thoughtpolice ];
+  };
+}
diff --git a/pkgs/os-specific/linux/cryptodev/default.nix b/pkgs/os-specific/linux/cryptodev/default.nix
index e80256f7299..4ea9295ef4f 100644
--- a/pkgs/os-specific/linux/cryptodev/default.nix
+++ b/pkgs/os-specific/linux/cryptodev/default.nix
@@ -1,21 +1,21 @@
-{ fetchurl, stdenv, kernelDev, onlyHeaders ? false }:
+{ fetchurl, stdenv, kernel, onlyHeaders ? false }:
 
 stdenv.mkDerivation rec {
-  pname = "cryptodev-linux-1.5";
-  name = "${pname}-${kernelDev.version}";
+  pname = "cryptodev-linux-1.6";
+  name = "${pname}-${kernel.version}";
 
   src = fetchurl {
     url = "http://download.gna.org/cryptodev-linux/${pname}.tar.gz";
-    sha256 = "13hybl5p0ck0vgi2gxmiwa2810gcfk78kdy17ai8nczj8il15mn0";
+    sha256 = "0bryzdb4xz3fp2q00a0mlqkj629md825lnlh4gjwmy51irf45wbm";
   };
 
   buildPhase = if !onlyHeaders then ''
-    make -C ${kernelDev}/lib/modules/${kernelDev.modDirVersion}/build \
+    make -C ${kernel.dev}/lib/modules/${kernel.modDirVersion}/build \
       SUBDIRS=`pwd` INSTALL_PATH=$out
   '' else ":";
 
   installPhase = stdenv.lib.optionalString (!onlyHeaders) ''
-    make -C ${kernelDev}/lib/modules/${kernelDev.modDirVersion}/build \
+    make -C ${kernel.dev}/lib/modules/${kernel.modDirVersion}/build \
       INSTALL_MOD_PATH=$out SUBDIRS=`pwd` modules_install
   '' + ''
     mkdir -p $out/include/crypto
@@ -25,6 +25,6 @@ stdenv.mkDerivation rec {
   meta = {
     description = "Device that allows access to Linux kernel cryptographic drivers";
     homepage = http://home.gna.org/cryptodev-linux/;
-    license = "GPLv2+";
+    license = stdenv.lib.licenses.gpl2Plus;
   };
 }
diff --git a/pkgs/os-specific/linux/cryptsetup/default.nix b/pkgs/os-specific/linux/cryptsetup/default.nix
index 0eb4be30284..d3a0b827ed1 100644
--- a/pkgs/os-specific/linux/cryptsetup/default.nix
+++ b/pkgs/os-specific/linux/cryptsetup/default.nix
@@ -5,11 +5,11 @@
 assert enablePython -> python != null;
 
 stdenv.mkDerivation rec {
-  name = "cryptsetup-1.5.1";
+  name = "cryptsetup-1.6.3";
 
   src = fetchurl {
     url = "http://cryptsetup.googlecode.com/files/${name}.tar.bz2";
-    sha256 = "0dib3nw6ifd7d7hr9k4iyaha3hz0pkzairqa38l3fndkr9w3zlhn";
+    sha256 = "1n1qk5chyjspbiianrdb55fhb4wl0vfyqz2br05vfb24v4qlgbx2";
   };
 
   configureFlags = [ "--enable-cryptsetup-reencrypt" ]
@@ -21,7 +21,7 @@ stdenv.mkDerivation rec {
   meta = {
     homepage = http://code.google.com/p/cryptsetup/;
     description = "LUKS for dm-crypt";
-    license = "GPLv2";
+    license = stdenv.lib.licenses.gpl2;
     maintainers = with stdenv.lib.maintainers; [ viric chaoflow ];
     platforms = with stdenv.lib.platforms; linux;
   };
diff --git a/pkgs/os-specific/linux/disk-indicator/default.nix b/pkgs/os-specific/linux/disk-indicator/default.nix
new file mode 100644
index 00000000000..b60232a9b75
--- /dev/null
+++ b/pkgs/os-specific/linux/disk-indicator/default.nix
@@ -0,0 +1,36 @@
+{ stdenv, fetchgit, libX11 }:
+
+stdenv.mkDerivation {
+  name = "disk-indicator";
+
+  src = fetchgit {
+    url = git://github.com/MeanEYE/Disk-Indicator.git;
+    rev = "51ef4afd8141b8d0659cbc7dc62189c56ae9c2da";
+    sha256 = "0f8mxl3wqlap8zajdk6r9liliayp8w4xs4jy8jbwanmmppwz0nb9";
+  };
+
+  buildInputs = [ libX11 ];
+
+  patchPhase = ''
+    substituteInPlace ./makefile --replace "COMPILER=c99" "COMPILER=gcc -std=c99"
+    substituteInPlace ./makefile --replace "COMPILE_FLAGS=" "COMPILE_FLAGS=-O2 "
+  '';
+
+  buildPhase = "make -f makefile";
+
+  installPhase = ''
+    mkdir -p "$out/bin"
+    cp ./disk_indicator "$out/bin/"
+  '';
+
+  meta = {
+    homepage = https://github.com/MeanEYE/Disk-Indicator;
+    description = "A program that will turn a LED into a hard disk indicator";
+    longDescription = ''
+      Small program for Linux that will turn your Scroll, Caps or Num Lock LED
+      or LED on your ThinkPad laptop into a hard disk activity indicator.
+    '';
+    license = stdenv.lib.licenses.gpl3;
+    platforms = stdenv.lib.platforms.linux;
+  };
+}
diff --git a/pkgs/os-specific/linux/dmidecode/default.nix b/pkgs/os-specific/linux/dmidecode/default.nix
index e6b5035bd8e..19d4092ba78 100644
--- a/pkgs/os-specific/linux/dmidecode/default.nix
+++ b/pkgs/os-specific/linux/dmidecode/default.nix
@@ -1,17 +1,18 @@
 { stdenv, fetchurl }:
 
 stdenv.mkDerivation rec {
-  name = "dmidecode-2.11";
+  name = "dmidecode-2.12";
 
   src = fetchurl {
     url = "mirror://savannah/dmidecode/${name}.tar.bz2";
-    sha256 = "0l9v8985piykc98hmbg1cq5r4xwvp0jjl4li3avr3ddkg4s699bd";
+    sha256 = "122hgaw8mpqdfra159lfl6pyk3837giqx6vq42j64fjnbl2z6gwi";
   };
 
   makeFlags = "prefix=$(out)";
 
-  meta = {
+  meta = with stdenv.lib; {
     homepage = http://www.nongnu.org/dmidecode/;
     description = "A tool that reads information about your system's hardware from the BIOS according to the SMBIOS/DMI standard";
+    platforms = platforms.linux;
   };
 }
diff --git a/pkgs/os-specific/linux/drbd/default.nix b/pkgs/os-specific/linux/drbd/default.nix
index 7129b685eb9..068e49d0190 100644
--- a/pkgs/os-specific/linux/drbd/default.nix
+++ b/pkgs/os-specific/linux/drbd/default.nix
@@ -3,11 +3,11 @@
 assert stdenv.isLinux;
 
 stdenv.mkDerivation rec {
-  name = "drbd-8.4.0";
+  name = "drbd-8.4.4";
 
   src = fetchurl {
     url = "http://oss.linbit.com/drbd/8.4/${name}.tar.gz";
-    sha256 = "096njwxjpwvnl259gxq6cr6n0r6ba0h5aryvgk05hqi95jx927vg";
+    sha256 = "0hm1cnd7vsccyc22sg85f9aj48nijl2f1kgbvl5crv414ihv5giq";
   };
 
   patches = [ ./pass-force.patch ];
diff --git a/pkgs/os-specific/linux/dstat/default.nix b/pkgs/os-specific/linux/dstat/default.nix
index 138b4ff468f..c95532f1360 100644
--- a/pkgs/os-specific/linux/dstat/default.nix
+++ b/pkgs/os-specific/linux/dstat/default.nix
@@ -20,7 +20,7 @@ stdenv.mkDerivation rec {
   meta = {
     homepage = http://dag.wieers.com/home-made/dstat/;
     description = "Versatile resource statistics tool";
-    license = "GPLv2";
+    license = stdenv.lib.licenses.gpl2;
     platforms = stdenv.lib.platforms.linux;
     maintainers = [ ];
   };
diff --git a/pkgs/os-specific/linux/e1000e/default.nix b/pkgs/os-specific/linux/e1000e/default.nix
index e1abeea49b7..db5f88b935f 100644
--- a/pkgs/os-specific/linux/e1000e/default.nix
+++ b/pkgs/os-specific/linux/e1000e/default.nix
@@ -1,19 +1,17 @@
-{ stdenv, fetchurl, kernelDev }:
+{ stdenv, fetchurl, kernel }:
 
 stdenv.mkDerivation {
-  name = "e1000e-1.5.1-${kernelDev.version}";
+  name = "e1000e-2.5.4-${kernel.version}";
 
   src = fetchurl {
-    url = "mirror://sourceforge/e1000/e1000e-1.5.1.tar.gz";
-    sha256 = "0nzjlarpqcpm5y112n3vzra4qv32hiygpfkk10y8g4nln4adhqsw";
+    url = "mirror://sourceforge/e1000/e1000e-2.5.4.tar.gz";
+    sha256 = "0bmihkc7y37jzwi996ryqblnyflyhhbimbnrnmlk419vxlzg1pzi";
   };
 
-  buildInputs = [ kernelDev ];
-
   configurePhase = ''
     cd src
-    kernel_version=$( cd ${kernelDev}/lib/modules && echo * )
-    sed -i -e 's|/lib/modules|${kernelDev}/lib/modules|' Makefile
+    kernel_version=${kernel.modDirVersion}
+    sed -i -e 's|/lib/modules|${kernel.dev}/lib/modules|' Makefile
     export makeFlags="BUILD_KERNEL=$kernel_version"
   '';
 
diff --git a/pkgs/os-specific/linux/exmap/default.nix b/pkgs/os-specific/linux/exmap/default.nix
deleted file mode 100644
index 1b372ca3dbf..00000000000
--- a/pkgs/os-specific/linux/exmap/default.nix
+++ /dev/null
@@ -1,56 +0,0 @@
-{ fetchurl, stdenv, kernelDev, pkgconfig, gtkmm, boost, pcre }:
-
-stdenv.mkDerivation rec {
-  name = "exmap-0.10-${kernelDev.version}";
-
-  src = fetchurl {
-    url = "http://www.berthels.co.uk/exmap/download/${name}.tgz";
-    sha256 = "0z00dhl6bdmaz7p9wlvnj0izf0zlrlkv34fz449kxyislpzzxmgn";
-  };
-
-  patchPhase = ''
-    substituteInPlace "kernel/Makefile" \
-      --replace '/lib/modules/$(shell uname -r)/build' \
-                ${kernelDev}/lib/modules/*/build
-
-    # The `proc_root' variable (the root of `/proc') is no longer exported
-    # since 2.6.26.  Fortunately, one can pass `NULL' instead of `&proc_root'.
-    # See http://lkml.org/lkml/2008/3/30/57 .
-    substituteInPlace "kernel/exmap.c" \
-      --replace "&proc_root" "NULL"
-
-    substituteInPlace "src/Makefile" --replace "-Werror" ""
-  '';
-
-  buildInputs = [ kernelDev pkgconfig gtkmm boost pcre ];
-
-  buildPhase = "make build";
-
-  # XXX: The tests can only be run one the `exmap' module is loaded.
-  doCheck = false;
-  #checkPhase = "make test"
-
-  installPhase = ''
-    mkdir -p "$out/share/${name}"
-    cp kernel/*.ko "$out/share/${name}"
-
-    mkdir -p "$out/bin"
-    cp src/{gexmap,exmtool,elftool,showproc} "$out/bin"
-  '';
-
-  meta = {
-    description = "Exmap, a tool showing the physical memory usage of processes";
-
-    longDescription = ''
-      Exmap is a utility which takes a snapshot of how the physical
-      memory and swap space are currently used by all the processes on
-      your system.  It examines which page of memory are shared between
-      which processes, so that it can share the cost of the pages
-      fairly when calculating usage totals.
-    '';
-
-    homepage = http://www.berthels.co.uk/exmap/;
-
-    license = "GPLv2+";
-  };
-}
diff --git a/pkgs/os-specific/linux/ffado/default.nix b/pkgs/os-specific/linux/ffado/default.nix
index 834f98960df..e024a608a0b 100644
--- a/pkgs/os-specific/linux/ffado/default.nix
+++ b/pkgs/os-specific/linux/ffado/default.nix
@@ -44,5 +44,6 @@ stdenv.mkDerivation rec {
     description = "FireWire audio drivers";
     license = licenses.gpl3;
     maintainers = [ maintainers.goibhniu ];
+    platforms = platforms.linux;
   };
 }
diff --git a/pkgs/os-specific/linux/firejail/default.nix b/pkgs/os-specific/linux/firejail/default.nix
new file mode 100644
index 00000000000..c1fa2c26205
--- /dev/null
+++ b/pkgs/os-specific/linux/firejail/default.nix
@@ -0,0 +1,37 @@
+{stdenv, fetchurl}:
+let
+  s = # Generated upstream information
+  rec {
+    baseName="firejail";
+    version="0.9.8.1";
+    name="${baseName}-${version}";
+    hash="0wjanz42k301zdwv06ylnzqrabxy424j0k9dh4i4aqhvihvxr83x";
+    url="mirror://sourceforge/project/firejail/firejail/firejail-0.9.8.1.tar.bz2";
+    sha256="0wjanz42k301zdwv06ylnzqrabxy424j0k9dh4i4aqhvihvxr83x";
+  };
+  buildInputs = [
+  ];
+in
+stdenv.mkDerivation {
+  inherit (s) name version;
+  inherit buildInputs;
+  src = fetchurl {
+    inherit (s) url sha256;
+  };
+
+  preConfigure = ''
+    sed -e 's@/bin/bash@${stdenv.shell}@g' -i $( grep -lr /bin/bash .)
+    sed -e '/void fs_var_run(/achar *vrcs = get_link("/var/run/current-system")\;' -i ./src/firejail/fs_var.c
+    sed -e '/ \/run/iif(vrcs!=NULL){symlink(vrcs, "/var/run/current-system")\;free(vrcs)\;}' -i ./src/firejail/fs_var.c
+  '';
+
+  meta = {
+    inherit (s) version;
+    description = ''Namespace-based sandboxing tool for Linux'';
+    license = stdenv.lib.licenses.gpl2Plus ;
+    maintainers = [stdenv.lib.maintainers.raskin];
+    platforms = stdenv.lib.platforms.linux;
+    homepage = "http://l3net.wordpress.com/projects/firejail/";
+    downloadPage = "http://sourceforge.net/projects/firejail/files/firejail/";
+  };
+}
diff --git a/pkgs/os-specific/linux/firejail/default.upstream b/pkgs/os-specific/linux/firejail/default.upstream
new file mode 100644
index 00000000000..4a0037e8aa4
--- /dev/null
+++ b/pkgs/os-specific/linux/firejail/default.upstream
@@ -0,0 +1,3 @@
+url http://sourceforge.net/projects/firejail/files/firejail/
+version_link '[.]tar[.][a-z0-9]+/download$'
+SF_redirect
diff --git a/pkgs/os-specific/linux/firmware/b43-firmware-cutter/default.nix b/pkgs/os-specific/linux/firmware/b43-firmware-cutter/default.nix
index b6465c0d794..9d31fde2f0f 100644
--- a/pkgs/os-specific/linux/firmware/b43-firmware-cutter/default.nix
+++ b/pkgs/os-specific/linux/firmware/b43-firmware-cutter/default.nix
@@ -1,11 +1,11 @@
 { stdenv, fetchurl }:
 
 stdenv.mkDerivation rec {
-  name = "b43-fwcutter-015";
+  name = "b43-fwcutter-018";
 
   src = fetchurl {
     url = "http://bues.ch/b43/fwcutter/${name}.tar.bz2";
-    sha256 = "1sznw1jrhyfbx0ilwzrj6mzlgc96fzjbx56j4ji8lsypyp8m6sjc";
+    sha256 = "13v34pa0y1jf4hkhsh3zagyb7s8b8ymplffaayscwsd3s7f6kc2p";
   };
 
   patches = [ ./no-root-install.patch ];
@@ -16,7 +16,6 @@ stdenv.mkDerivation rec {
     description = "Firmware extractor for cards supported by the b43 kernel module";
     homepage = http://wireless.kernel.org/en/users/Drivers/b43;
     license = "free-non-copyleft";
-    maintainers = [ stdenv.lib.maintainers.shlevy ];
   };
 }
 
diff --git a/pkgs/os-specific/linux/firmware/b43-firmware/5.1.138.nix b/pkgs/os-specific/linux/firmware/b43-firmware/5.1.138.nix
index f941d9275c0..436f40712fc 100644
--- a/pkgs/os-specific/linux/firmware/b43-firmware/5.1.138.nix
+++ b/pkgs/os-specific/linux/firmware/b43-firmware/5.1.138.nix
@@ -23,7 +23,6 @@ stdenv.mkDerivation {
     description = "Firmware for cards supported by the b43 kernel module";
     homepage = http://wireless.kernel.org/en/users/Drivers/b43;
     license = stdenv.lib.licenses.unfree;
-    maintainers = [ stdenv.lib.maintainers.shlevy ];
   };
 }
 
diff --git a/pkgs/os-specific/linux/firmware/firmware-linux-nonfree/default.nix b/pkgs/os-specific/linux/firmware/firmware-linux-nonfree/default.nix
index f5efc565753..04823ffeda0 100644
--- a/pkgs/os-specific/linux/firmware/firmware-linux-nonfree/default.nix
+++ b/pkgs/os-specific/linux/firmware/firmware-linux-nonfree/default.nix
@@ -6,26 +6,27 @@
 { stdenv, fetchurl, dpkg }:
 
 let
-  version = "0.40";
+  version = "0.43";
 
   packages = [
-    { name = "adi"; sha256 = "0wwks9ff4n772435s57z1fjrffi4xl9nxnfn3v7xfcwdjb395d88"; }
-    { name = "atheros"; sha256 = "1gj7hfnyclzgyq06scynaclnfajhs6lw5i51j1w1hikv4yh20djz"; }
-    { name = "bnx2"; sha256 = "15qjj0sfjin5cbkpby29r5czn11xyiyyc4fmhwlqvgfgrnbp0aqk"; }
-    { name = "bnx2x"; sha256 = "08nvbln94ff47b2q0avxj1aa2wx4qih8sq8knbq54lp46kjf3k0h"; }
-    { name = "brcm80211"; sha256 = "1ndsw3s6xkr1n39nf9ig1xhnaglx5qvvvm8rh6ah41v644lzha79"; }
-    { name = "intelwimax"; sha256 = "1qwxmykh90v92asn4ivq0fak761hs7hd2zmz1dpkjidwsycrfyqn"; }
-    { name = "ipw2x00"; sha256 = "0a2nb17b5n3k1b6y4dbi5i8k1fm19ba2abq2jh2hjjmyyl3y388m"; }
-    { name = "ivtv"; sha256 = "1239gsjq16f4kd1yn77iq3ar8ndx3pzd16kpqafr1h2y0zwh452r"; }
-    { name = "iwlwifi"; sha256 = "03kmh5szd02pkbm1nlyz99fr2njhg88wiv73f1fz485m9rvgga43"; }
-    { name = "libertas"; sha256 = "0qjziwmwqbp83hxrjw7x3ralxg4ib9y23bcbn1g8yb5b6m84ca6b"; }
-    { name = "linux"; sha256 = "0ypidsrrfx4kvbfisdpgx2fzbil7g2jixgqhnv960iy5l348amrl"; }
-    { name = "linux-nonfree"; sha256 = "0p9ql3cdxljflh48r6z40kpyisbzp3s3g1qjb9f64n6cppllwjfr"; }
-    { name = "myricom"; sha256 = "12spfaq7z2bb93cy15zldlic1wx2v6h9sn7ny09nkzy4m26zds4q"; }
-    { name = "netxen"; sha256 = "03gmda16bdqw8a4x8x11ph41ksjh48hxydv0f0z3gi3czgbh7sn3"; }
-    { name = "qlogic"; sha256 = "1ah8rrwzi44p1l4q8qkql18djmn5kihsiinpy204xklm1csf3vs1"; }
-    { name = "ralink"; sha256 = "005549jk0wnyfnb247awv2wncsx5is05m1hdwcd33iq0dlbmm39b"; }
-    { name = "realtek"; sha256 = "1ai1klzrql8qxmb7945xiqlkfkyz8admrpb10b3r4ixvclkrvfi2"; }
+    { name = "adi"; sha256 = "13cwnbispivpd73k928l1i818ylhpahp6xh7d6pw59sswrsx6inw"; }
+    { name = "atheros"; sha256 = "0sw9d52k3ynx1cxg7cq49pmm8y6vlqyhb9843hbyf6nbmjqj72bx"; }
+    { name = "bnx2"; sha256 = "1r8scys27qj5shdbgl8ag9vi4hiidx4bp8yw4n4dcp288d9x7bbh"; }
+    { name = "bnx2x"; sha256 = "03jx4vnn8irlwswydf4h3ya1kf064jkaj67jry2hr6qwpd4l8pgq"; }
+    { name = "brcm80211"; sha256 = "01mkmjkg16kdd26pwlg4a1s1717fh0j602mwqhwh46k8zakg2lkh"; }
+    { name = "intelwimax"; sha256 = "1avls6sx0pbsffrcs267r2r2rqlx2xrv8j9znc7ix1bi8g4fx91v"; }
+    { name = "ipw2x00"; sha256 = "19zqc30hsz7snw020izm81qbap3xsygggnmbspxndw7jihz0amjs"; }
+    { name = "ivtv"; sha256 = "1f2004lpw5nr9rxj3cl4ba0jdm51wkvsrbiy4drakawpjwh5y4qw"; }
+    { name = "iwlwifi"; sha256 = "1538r751mx8nhg3xibnnrhnflvf3kl5y9rnm7rpl4wyrfgx61amd"; }
+    { name = "libertas"; sha256 = "0svkqlsiqgmh970r38nh0c1pjx41zdfql2k2k5djw99fscjklacd"; }
+    { name = "linux"; sha256 = "0j62v6vbh2287j3x5c9i0xspmhyh5k1z8dyajgix7k37xi4jvpy2"; }
+    { name = "linux-nonfree"; sha256 = "1f5x72rzicivwm0sn9l6wjkx7z9a0b8n6c9m60xrqg36ly7mizzp"; }
+    { name = "myricom"; sha256 = "17cdl885jlnja5m60l35xr2f84hv8z4cvg3d25vpp171s1vf1ks1"; }
+    { name = "netxen"; sha256 = "122nava9ld1v8gcnqbdpx0kffv0rxm9glp4xg09ssvldy4myfgl7"; }
+    { name = "qlogic"; sha256 = "02pgmprz1qwij7lw1lgmb8clgxj8v3mx0fyy1l4z7bffnpvip863"; }
+    { name = "ralink"; sha256 = "0yw9gf9gm3jxmsndr8kcsf6829smm88kshfb4c8jn0n6f4yy9l7x"; }
+    { name = "realtek"; sha256 = "0gay9x47pimdqj665sr1416l3bdyca9grsqpj0s9n6k1lmywrqx1"; }
+    { name = "ti-connectivity"; sha256 = "1m6yk0827991hs46l8pp8iiwh1ms0rwlmwn64k2wr725k5yzg29b"; }
   ];
 
   fetchPackage =
diff --git a/pkgs/os-specific/linux/frandom/default.nix b/pkgs/os-specific/linux/frandom/default.nix
index a28ba527218..80ad483b367 100644
--- a/pkgs/os-specific/linux/frandom/default.nix
+++ b/pkgs/os-specific/linux/frandom/default.nix
@@ -1,10 +1,10 @@
-{ stdenv, fetchurl, kernelDev }:
+{ stdenv, fetchurl, kernel }:
 
 let baseName = "frandom-1.1";
 in
 
 stdenv.mkDerivation rec {
-  name = "${baseName}-${kernelDev.version}";
+  name = "${baseName}-${kernel.version}";
 
   src = fetchurl {
     url = "mirror://sourceforge/frandom/${baseName}.tar.gz";
@@ -12,18 +12,18 @@ stdenv.mkDerivation rec {
   };
 
   preBuild = ''
-    kernelVersion=$(cd ${kernelDev}/lib/modules && ls)
+    kernelVersion=${kernel.modDirVersion}
     substituteInPlace Makefile \
       --replace "\$(shell uname -r)" "$kernelVersion" \
-      --replace "/lib/modules" "${kernelDev}/lib/modules"
+      --replace "/lib/modules" "${kernel.dev}/lib/modules"
   '';
  
   installPhase = ''
-    kernelVersion=$(cd ${kernelDev}/lib/modules && ls)
-    ensureDir $out/lib/modules/$kernelVersion/misc
+    kernelVersion=${kernel.modDirVersion}
+    mkdir -p $out/lib/modules/$kernelVersion/misc
     cp frandom.ko $out/lib/modules/$kernelVersion/misc
 
-    ensureDir $out/lib/udev/rules.d
+    mkdir -p $out/lib/udev/rules.d
     tee $out/lib/udev/rules.d/10-frandom.rules <<-EOF
     #
     # These are the rules for the frandom devices. In theory, we could let
@@ -40,8 +40,7 @@ stdenv.mkDerivation rec {
   meta = {
     description = "A very fast random number generator kernel module";
     homepage = http://frandom.sourceforge.net/;
-    license = "GPLv2";
+    license = stdenv.lib.licenses.gpl2;
     maintainers = [ stdenv.lib.maintainers.bluescreen303 ];
   };
 }
-
diff --git a/pkgs/os-specific/linux/fuse/default.nix b/pkgs/os-specific/linux/fuse/default.nix
index bd2507ec1bc..d6513f7ebb5 100644
--- a/pkgs/os-specific/linux/fuse/default.nix
+++ b/pkgs/os-specific/linux/fuse/default.nix
@@ -1,13 +1,13 @@
 { stdenv, fetchurl, utillinux }:
 
 stdenv.mkDerivation rec {
-  name = "fuse-2.9.2";
+  name = "fuse-2.9.3";
   
   builder = ./builder.sh;
   
   src = fetchurl {
     url = "mirror://sourceforge/fuse/${name}.tar.gz";
-    sha256 = "1z6fg593hy1j7mynhckx43gqkkg2nwpmwwv860337nl77zxji9w1";
+    sha256 = "071r6xjgssy8vwdn6m28qq1bqxsd2bphcd2mzhq0grf5ybm87sqb";
   };
   
   configureFlags = "--disable-kernel-module";
@@ -16,8 +16,10 @@ stdenv.mkDerivation rec {
   
   inherit utillinux;
 
-  meta = {
+  meta = with stdenv.lib; {
     homepage = http://fuse.sourceforge.net/;
     description = "Kernel module and library that allows filesystems to be implemented in user space";
+    platforms = platforms.linux;
+    maintainers = maintainers.mornfall;
   };
 }
diff --git a/pkgs/os-specific/linux/gogoclient/default.nix b/pkgs/os-specific/linux/gogoclient/default.nix
index 09a449bbede..a627a8cbcc9 100644
--- a/pkgs/os-specific/linux/gogoclient/default.nix
+++ b/pkgs/os-specific/linux/gogoclient/default.nix
@@ -19,7 +19,7 @@ stdenv.mkDerivation rec {
   buildInputs = [openssl];
 
   preFixup = ''
-    ensureDir $out/share/${name}
+    mkdir -p $out/share/${name}
     chmod 444 $out/bin/gogoc.conf
     mv $out/bin/gogoc.conf $out/share/${name}/gogoc.conf.sample
     rm $out/bin/gogoc.conf.sample
diff --git a/pkgs/os-specific/linux/google-authenticator/default.nix b/pkgs/os-specific/linux/google-authenticator/default.nix
index d7acc6778b4..0e38d94e1ed 100644
--- a/pkgs/os-specific/linux/google-authenticator/default.nix
+++ b/pkgs/os-specific/linux/google-authenticator/default.nix
@@ -1,4 +1,4 @@
-{ stdenv, fetchurl, pam }:
+{ stdenv, fetchurl, pam, qrencode }:
 
 stdenv.mkDerivation rec {
   name = "google-authenticator-1.0";
@@ -10,8 +10,12 @@ stdenv.mkDerivation rec {
 
   buildInputs = [ pam ];
 
+  preConfigure = ''
+    sed -i 's|libqrencode.so.3|${qrencode}/lib/libqrencode.so.3|' google-authenticator.c
+  '';
+
   installPhase = ''
-    ensureDir $out/bin $out/lib/security
+    mkdir -p $out/bin $out/lib/security
     cp pam_google_authenticator.so $out/lib/security
     cp google-authenticator $out/bin
   '';
@@ -19,6 +23,6 @@ stdenv.mkDerivation rec {
   meta = {
     homepage = https://code.google.com/p/google-authenticator/;
     description = "Two-step verification, with pam module";
-    license = "ASL2.0";
+    license = stdenv.lib.licenses.asl20;
   };
 }
diff --git a/pkgs/os-specific/linux/gradm/default.nix b/pkgs/os-specific/linux/gradm/default.nix
new file mode 100644
index 00000000000..87e8fa5b074
--- /dev/null
+++ b/pkgs/os-specific/linux/gradm/default.nix
@@ -0,0 +1,52 @@
+{ fetchurl, stdenv, bison, flex, pam,
+  gcc, coreutils, findutils, binutils, bash }:
+
+stdenv.mkDerivation rec {
+  name    = "gradm-${version}";
+  version = "3.0-201405281853";
+
+  src  = fetchurl {
+    url    = "http://grsecurity.net/stable/${name}.tar.gz";
+    sha256 = "0yjmbjhm71cik5j8h2prgk40wki3sflwbf2zqmc4pwaqlvis9s2f";
+  };
+
+  buildInputs = [ gcc coreutils findutils binutils pam flex bison bash ];
+  preBuild = ''
+    substituteInPlace ./Makefile --replace "/usr/include/security/pam_" "${pam}/include/security/pam_"
+    substituteInPlace ./gradm_defs.h --replace "/sbin/grlearn"   "$out/sbin/grlearn"
+    substituteInPlace ./gradm_defs.h --replace "/sbin/gradm"     "$out/sbin/gradm"
+  '';
+
+  postInstall = ''
+    mkdir -p $out/lib/udev/rules.d
+    cat > $out/lib/udev/rules.d/80-grsec.rules <<EOF
+    ACTION!="add|change", GOTO="permissions_end"
+    KERNEL=="grsec",          MODE="0622"
+    LABEL="permissions_end"
+    EOF
+
+    echo "inherit-learn /nix/store" >> $out/etc/grsec/learn_config
+  '';
+
+  makeFlags =
+    [ "DESTDIR=$(out)"
+      "CC=${gcc}/bin/gcc"
+      "FLEX=${flex}/bin/flex"
+      "BISON=${bison}/bin/bison"
+      "FIND=${findutils}/bin/find"
+      "STRIP=${binutils}/bin/strip"
+      "INSTALL=${coreutils}/bin/install"
+      "MANDIR=/share/man"
+      "MKNOD=true"
+    ];
+
+  enableParallelBuilding = true;
+
+  meta = with stdenv.lib; {
+    description = "grsecurity RBAC administration and policy analysis utility";
+    homepage    = "https://grsecurity.net";
+    license     = licenses.gpl2;
+    platforms   = platforms.linux;
+    maintainers = with maintainers; [ thoughtpolice wizeman ];
+  };
+}
diff --git a/pkgs/os-specific/linux/guvcview/default.nix b/pkgs/os-specific/linux/guvcview/default.nix
new file mode 100644
index 00000000000..6e4a2caba18
--- /dev/null
+++ b/pkgs/os-specific/linux/guvcview/default.nix
@@ -0,0 +1,39 @@
+{ stdenv, fetchgit, intltool, autoreconfHook, gettext, pkgconfig
+, gtk3, portaudio, libpng, SDL, ffmpeg, udev, libusb1, libv4l, alsaLib }:
+
+stdenv.mkDerivation rec {
+  version = "1.7.2";
+  rev = "ab84b0b1ed358f0504e1218a0ef792a02b307af8";
+  name = "guvcview-${version}_${rev}";
+
+  src = fetchgit {
+    inherit rev;
+    url = "git://git.code.sf.net/p/guvcview/git-master";
+    sha256 = "08cpbxq3dh2mlsgzk5dj3vfrgap4q281n9h6xzpbsvyifcj1a9n1";
+  };
+
+  buildInputs =
+    [ SDL
+      alsaLib
+      autoreconfHook
+      ffmpeg
+      gtk3
+      intltool
+      libusb1
+      libv4l
+      pkgconfig
+      portaudio
+      udev
+    ];
+
+  preConfigure = ''
+    ./bootstrap.sh
+  '';
+
+  meta = {
+    description = "A simple interface for devices supported by the linux UVC driver";
+    homepage = http://guvcview.sourceforge.net;
+    maintainers = [ stdenv.lib.maintainers.coconnor ];
+    platforms = stdenv.lib.platforms.linux;
+  };
+}
diff --git a/pkgs/os-specific/linux/hdparm/default.nix b/pkgs/os-specific/linux/hdparm/default.nix
index b627d664aef..bc83738acc8 100644
--- a/pkgs/os-specific/linux/hdparm/default.nix
+++ b/pkgs/os-specific/linux/hdparm/default.nix
@@ -1,11 +1,11 @@
 { stdenv, fetchurl }:
 
 stdenv.mkDerivation rec {
-  name = "hdparm-9.39";
+  name = "hdparm-9.43";
 
   src = fetchurl {
     url = "mirror://sourceforge/hdparm/${name}.tar.gz";
-    sha256 = "1siw9c2hrsck47jr9wpip9n677g31qd34y8whkq9dai68npm1mbj";
+    sha256 = "0amm2s67vzfgs0jv59jgj9pqkr6j9glj1chsj292263i94kr5gib";
   };
 
   preBuild = ''
diff --git a/pkgs/os-specific/linux/hibernate/default.nix b/pkgs/os-specific/linux/hibernate/default.nix
index 91dc9068103..6c5dd330f65 100644
--- a/pkgs/os-specific/linux/hibernate/default.nix
+++ b/pkgs/os-specific/linux/hibernate/default.nix
@@ -1,12 +1,12 @@
 { stdenv, fetchurl, gawk }:
 
-let version = "1.98.1";
+let version = "2.0";
 in
   stdenv.mkDerivation rec {
     name = "hibernate-${version}";
     src = fetchurl {
-      url = "http://www.tuxonice.net/downloads/all/hibernate-script-${version}.tar.gz";
-      sha256 = "1xpc2i16jczc3nhvxlkn6fb044srqrh528gnp92cwy4hxf2nzi1z";
+      url = "http://tuxonice.nigelcunningham.com.au/files/hibernate-script-${version}.tar.gz";
+      sha256 = "0ib5bac3spbcwmhf8f9apjbll8x7fgqj4k1s5q3srijh793rfifh";
     };
 
     patches = [ ./install.patch ./gen-manpages.patch ./hibernate.patch ];
@@ -38,7 +38,7 @@ in
 	it into "hibernation".  It works both with Linux swsusp and Tux-on-Ice.
       '';
 
-      license = "GPLv2+";
+      license = stdenv.lib.licenses.gpl2Plus;
       homepage = http://www.tuxonice.net/;
     };
   }
diff --git a/pkgs/os-specific/linux/hostapd/default.nix b/pkgs/os-specific/linux/hostapd/default.nix
index 410fa6a7ad6..a8988f0a452 100644
--- a/pkgs/os-specific/linux/hostapd/default.nix
+++ b/pkgs/os-specific/linux/hostapd/default.nix
@@ -2,11 +2,11 @@
 stdenv.mkDerivation rec {
 
   name = "hostapd-${version}";
-  version = "2.0";
+  version = "2.1";
 
   src = fetchurl {
     url = "http://hostap.epitest.fi/releases/${name}.tar.gz";
-    sha256 = "262ce394b930bccc3d65fb99ee380f28d36444978f524c845a98e8e29f4e9d35";
+    sha256 = "121gpcs1ws7m2v8jk091jhmz3pm2xmhwkv96gqkyb4k0bgsi0waw";
   };
 
   buildInputs = [ libnl openssl pkgconfig ];
@@ -23,6 +23,7 @@ stdenv.mkDerivation rec {
 
   meta = with stdenv.lib; {
     homepage = http://hostap.epitest.fi;
+    repositories.git = git://w1.fi/hostap.git;
     description = "A user space daemon for access point and authentication servers";
     license = licenses.gpl2;
     maintainers = [ maintainers.phreedom ];
diff --git a/pkgs/os-specific/linux/htop/default.nix b/pkgs/os-specific/linux/htop/default.nix
index 613adb5f5d2..d35b5340e9d 100644
--- a/pkgs/os-specific/linux/htop/default.nix
+++ b/pkgs/os-specific/linux/htop/default.nix
@@ -1,11 +1,11 @@
 { fetchurl, stdenv, ncurses }:
 
 stdenv.mkDerivation rec {
-  name = "htop-1.0.2";
+  name = "htop-1.0.3";
 
   src = fetchurl {
-    url = "mirror://sourceforge/htop/${name}.tar.gz";
-    sha256 = "18fqrhvnm7h4c3939av8lpiwrwxbyw6hcly0jvq0vkjf0ixnaq7f";
+    url = "http://hisham.hm/htop/releases/1.0.3/htop-1.0.3.tar.gz";
+    sha256 = "0a8qbpsifzjwc4f45xfwm48jhm59g6q5hlib4bf7z13mgy95fp05";
   };
 
   buildInputs = [ ncurses ];
@@ -14,6 +14,6 @@ stdenv.mkDerivation rec {
     description = "An interactive process viewer for Linux";
     homepage = "http://htop.sourceforge.net";
     platforms = stdenv.lib.platforms.linux;
-    maintainers = [ stdenv.lib.maintainers.rob stdenv.lib.maintainers.simons ];
+    maintainers = with stdenv.lib.maintainers; [ rob simons relrod ];
   };
 }
diff --git a/pkgs/os-specific/linux/hwdata/builder.sh b/pkgs/os-specific/linux/hwdata/builder.sh
deleted file mode 100644
index 50d11477324..00000000000
--- a/pkgs/os-specific/linux/hwdata/builder.sh
+++ /dev/null
@@ -1,5 +0,0 @@
-source $stdenv/setup
-
-export DESTDIR=$out
-
-genericBuild
diff --git a/pkgs/os-specific/linux/hwdata/default.nix b/pkgs/os-specific/linux/hwdata/default.nix
index 4c0a46f460c..325a44f97aa 100644
--- a/pkgs/os-specific/linux/hwdata/default.nix
+++ b/pkgs/os-specific/linux/hwdata/default.nix
@@ -1,10 +1,21 @@
 {stdenv, fetchurl}:
 
 stdenv.mkDerivation {
-  name = "hwdata-0.172";
-  builder = ./builder.sh;
+  name = "hwdata-0.249";
+
   src = fetchurl {
-    url = ftp://ftp.nluug.nl/pub/os/Linux/distr/debian/pool/main/h/hwdata/hwdata_0.172.orig.tar.gz;
-    md5 = "1c6b7f4dfe489f881702176c5f8e5a2e";
+    url = "https://git.fedorahosted.org/cgit/hwdata.git/snapshot/hwdata-0.249-1.tar.bz2";
+    sha256 = "1ak3h3psg3wk9yk0dqnzdzik3jadzja3ah22vjfmf71p3b5xc8ai";
+  };
+
+  preConfigure = "patchShebangs ./configure";
+
+  configureFlags = "--datadir=$(prefix)/data";
+
+  meta = {
+    homepage = "https://fedorahosted.org/hwdata/";
+    description = "Hardware Database, including Monitors, pci.ids, usb.ids, and video cards";
+    license = stdenv.lib.licenses.gpl2;
+    platforms = stdenv.lib.platforms.linux;
   };
 }
diff --git a/pkgs/os-specific/linux/i7z/default.nix b/pkgs/os-specific/linux/i7z/default.nix
index 33ac05aef47..1fe1f48f4ef 100644
--- a/pkgs/os-specific/linux/i7z/default.nix
+++ b/pkgs/os-specific/linux/i7z/default.nix
@@ -20,7 +20,7 @@ stdenv.mkDerivation rec {
   '';
 
   installPhase = ''
-    ensureDir $out/sbin
+    mkdir -p $out/sbin
     make install prefix=$out
     install -Dm755 GUI/i7z_GUI $out/sbin/i7z-gui
   '';
@@ -29,8 +29,7 @@ stdenv.mkDerivation rec {
     description = "A better i7 (and now i3, i5) reporting tool for Linux";
     homepage = http://code.google.com/p/i7z;
     repositories.git = https://github.com/ajaiantilal/i7z.git;
-    license = "GPLv2";
+    license = stdenv.lib.licenses.gpl2;
     maintainers = [ stdenv.lib.maintainers.bluescreen303 ];
   };
 }
-
diff --git a/pkgs/os-specific/linux/i810switch/default.nix b/pkgs/os-specific/linux/i810switch/default.nix
index 63a056712ac..00f27a43e65 100644
--- a/pkgs/os-specific/linux/i810switch/default.nix
+++ b/pkgs/os-specific/linux/i810switch/default.nix
@@ -20,6 +20,6 @@ stdenv.mkDerivation {
   meta = {
     description = "A utility for switching between the LCD and external VGA display on Intel graphics cards";
     homepage = "http://www16.plala.or.jp/mano-a-mano/i810switch.html";
-    license = "GPL2";
+    license = stdenv.lib.licenses.gpl2;
   };
 }
diff --git a/pkgs/os-specific/linux/ifenslave/default.nix b/pkgs/os-specific/linux/ifenslave/default.nix
new file mode 100644
index 00000000000..d8985003b41
--- /dev/null
+++ b/pkgs/os-specific/linux/ifenslave/default.nix
@@ -0,0 +1,26 @@
+{ stdenv, fetchurl }:
+
+stdenv.mkDerivation rec {
+  name = "ifenslave-${version}";
+  version = "1.1.0";
+
+  src = fetchurl {
+    url = "mirror://debian/pool/main/i/ifenslave-2.6/ifenslave-2.6_${version}.orig.tar.gz";
+    sha256 = "0h9hrmy19zdksl7ys250r158b943ihbgkb95n8p4k8l0vqsby5vr";
+  };
+
+  buildPhase = ''
+    gcc -o ifenslave ifenslave.c
+  '';
+
+  installPhase = ''
+    mkdir -p $out/bin
+    cp -a ifenslave $out/bin
+  '';
+
+  meta = {
+    description = "Utility for enslaving networking interfaces under a bond";
+    license = stdenv.lib.licenses.gpl2;
+    platforms = stdenv.lib.platforms.linux;
+  };
+}
diff --git a/pkgs/os-specific/linux/iomelt/default.nix b/pkgs/os-specific/linux/iomelt/default.nix
new file mode 100644
index 00000000000..fccf7b6b1cd
--- /dev/null
+++ b/pkgs/os-specific/linux/iomelt/default.nix
@@ -0,0 +1,25 @@
+{ stdenv, lib, fetchurl }:
+
+let version = "0.7";
+in stdenv.mkDerivation {
+  name = "iomelt-${version}";
+  src = fetchurl {
+    url = "http://iomelt.com/s/iomelt-${version}.tar.gz";
+    sha256 = "1jhrdm5b7f1bcbrdwcc4yzg26790jxl4d2ndqiwd9brl2g5537im";
+  };
+
+  preBuild = ''
+    mkdir -p $out/bin
+    mkdir -p $out/share/man/man1
+
+    substituteInPlace Makefile \
+      --replace /usr $out
+  '';
+
+  meta = with lib; {
+    description = "A simple yet effective way to benchmark disk IO in Linux systems";
+    homepage    = http://www.iomelt.com;
+    maintainers = with maintainers; [ cstrahan ];
+    platforms   = platforms.linux ++ platforms.darwin;
+  };
+}
diff --git a/pkgs/os-specific/linux/iotop/default.nix b/pkgs/os-specific/linux/iotop/default.nix
index 8e181d3d5cf..7481edeee7b 100644
--- a/pkgs/os-specific/linux/iotop/default.nix
+++ b/pkgs/os-specific/linux/iotop/default.nix
@@ -11,12 +11,6 @@ buildPythonPackage rec {
 
   pythonPath = [ pythonPackages.curses ];
 
-  postInstall =
-    ''
-      # Put the man page in the right place.
-      mv $out/lib/python*/site-packages/iotop-*/share $out
-    '';
-
   doCheck = false;
 
   meta = {
diff --git a/pkgs/os-specific/linux/iproute/default.nix b/pkgs/os-specific/linux/iproute/default.nix
index 4ea4152e30d..2cfbc2a1df1 100644
--- a/pkgs/os-specific/linux/iproute/default.nix
+++ b/pkgs/os-specific/linux/iproute/default.nix
@@ -1,14 +1,14 @@
-{ fetchurl, stdenv, flex, bison, db4, iptables, pkgconfig }:
+{ fetchurl, stdenv, flex, bison, db, iptables, pkgconfig }:
 
 stdenv.mkDerivation rec {
-  name = "iproute2-3.8.0";
+  name = "iproute2-3.12.0";
 
   src = fetchurl {
     url = "mirror://kernel/linux/utils/net/iproute2/${name}.tar.xz";
-    sha256 = "0kqy30wz2krbg4y7750hjq5218hgy2vj9pm5qzkn1bqskxs4b4ap";
+    sha256 = "04gi11gh087bg2nlxhj0lxrk8l9qxkpr88nsiil23917bm3h1xj4";
   };
 
-  patches = [ ./vpnc.patch ./no-werror.patch ];
+  patch = [ "vpnc.patch" ];
 
   preConfigure =
     ''
@@ -16,13 +16,11 @@ stdenv.mkDerivation rec {
       sed -e '/ARPDDIR/d' -i Makefile
     '';
 
-  postConfigure = "cat Config";
-
   makeFlags = "DESTDIR= LIBDIR=$(out)/lib SBINDIR=$(out)/sbin"
     + " CONFDIR=$(out)/etc DOCDIR=$(out)/share/doc/${name}"
     + " MANDIR=$(out)/share/man";
 
-  buildInputs = [ db4 iptables ];
+  buildInputs = [ db iptables ];
   nativeBuildInputs = [ bison flex pkgconfig ];
 
   enableParallelBuilding = true;
diff --git a/pkgs/os-specific/linux/iproute/no-werror.patch b/pkgs/os-specific/linux/iproute/no-werror.patch
deleted file mode 100644
index 593b56b8de0..00000000000
--- a/pkgs/os-specific/linux/iproute/no-werror.patch
+++ /dev/null
@@ -1,12 +0,0 @@
-diff -ubr iproute2-3.8.0-orig/Makefile iproute2-3.8.0/Makefile
---- iproute2-3.8.0-orig/Makefile	2013-04-06 00:03:21.072827860 +0200
-+++ iproute2-3.8.0/Makefile	2013-04-06 00:03:25.353837862 +0200
-@@ -30,7 +30,7 @@
- HOSTCC = gcc
- DEFINES += -D_GNU_SOURCE
- CCOPTS = -O2
--WFLAGS := -Wall -Wstrict-prototypes -Werror -Wmissing-prototypes
-+WFLAGS := -Wall -Wstrict-prototypes -Wmissing-prototypes
- WFLAGS += -Wmissing-declarations -Wold-style-definition
- 
- CFLAGS = $(WFLAGS) $(CCOPTS) -I../include $(DEFINES)
diff --git a/pkgs/os-specific/linux/ipsec-tools/default.nix b/pkgs/os-specific/linux/ipsec-tools/default.nix
index b28320c0625..6a42784d1f0 100644
--- a/pkgs/os-specific/linux/ipsec-tools/default.nix
+++ b/pkgs/os-specific/linux/ipsec-tools/default.nix
@@ -7,17 +7,20 @@
 # the time being.
 
 stdenv.mkDerivation rec {
-  name = "ipsec-tools-0.8.1";
+  name = "ipsec-tools-0.8.2";
 
   src = fetchurl {
     url = "mirror://sourceforge/ipsec-tools/${name}.tar.bz2";
-    sha256 = "1m1x2planqqxi0587g7d8xhy0gkyfaxs3ry4hhdh0bw46sxrajps";
+    sha256 = "0b9gfbz78k2nj0k7jdlm5kajig628ja9qm0z5yksiwz22s3v7dlf";
   };
 
   buildInputs = [ readline openssl flex krb5 pam ];
 
   patches = [ ./dont-create-localstatedir-during-install.patch ];
 
+  # fix build with newer gcc versions
+  preConfigure = ''substituteInPlace configure --replace "-Werror" "" '';
+
   configureFlags = ''
     --sysconfdir=/etc --localstatedir=/var
     --with-kernel-headers=${linuxHeaders}/include
diff --git a/pkgs/os-specific/linux/iptables/default.nix b/pkgs/os-specific/linux/iptables/default.nix
index 78d8ee52fb1..0e022e0c4a1 100644
--- a/pkgs/os-specific/linux/iptables/default.nix
+++ b/pkgs/os-specific/linux/iptables/default.nix
@@ -1,24 +1,17 @@
 {stdenv, fetchurl}:
 
 stdenv.mkDerivation rec {
-  name = "iptables-1.4.16.2";
+  name = "iptables-1.4.21";
 
   src = fetchurl {
     url = "http://www.netfilter.org/projects/iptables/files/${name}.tar.bz2";
-    md5 = "57220bb26866a713073e5614f88071fc";
+    sha256 = "1q6kg7sf0pgpq0qhab6sywl23cngxxfzc9zdzscsba8x09l4q02j";
   };
 
-  # Install header files required by miniupnpd.
-  postInstall =
-    ''
-      cp include/iptables.h $out/include
-      cp include/libiptc/libiptc.h include/libiptc/ipt_kernel_headers.h $out/include/libiptc
-      mkdir $out/include/iptables
-      cp include/iptables/internal.h $out/include/iptables
-      mkdir $out/include/net
-      cp -prd include/net/netfilter $out/include/net/netfilter
-      mkdir $out/include/linux
-    '';
+  configureFlags = ''
+    --enable-devel
+    --enable-shared
+  '';
 
   meta = {
     description = "A program to configure the Linux IP packet filtering ruleset";
diff --git a/pkgs/os-specific/linux/iscsitarget/default.nix b/pkgs/os-specific/linux/iscsitarget/default.nix
deleted file mode 100644
index e07409aa08d..00000000000
--- a/pkgs/os-specific/linux/iscsitarget/default.nix
+++ /dev/null
@@ -1,27 +0,0 @@
-{ stdenv, fetchurl, kernelDev, module_init_tools}:
-
-stdenv.mkDerivation rec {
-  name = "iscsitarget-1.4.20.2-${kernelDev.version}";
-  
-  src = fetchurl {
-    url = "mirror://sourceforge/iscsitarget/iscsitarget/1.4.20.2/${name}.tar.gz";
-    sha256 = "126kp0yc7vmvdbaw2xfav89340b0h91dvvyib5qbvyrq40n8wg0g";
-  };
-  
-  KSRC = "${kernelDev}/lib/modules/*/build";
-  
-  DESTDIR = "$(out)";
-  
-  preConfigure = ''
-    export PATH=$PATH:${module_init_tools}/sbin
-    sed -i 's|/usr/|/|' Makefile
-  '';
-  
-  buildInputs = [ module_init_tools ];
-  
-  meta = {
-    description = "iSCSI Enterprise Target (IET), software for building an iSCSI storage system on Linux";
-    license = "GPLv2+";
-    homepage = http://iscsitarget.sourceforge.net;
-  };
-}
diff --git a/pkgs/os-specific/linux/iw/default.nix b/pkgs/os-specific/linux/iw/default.nix
index ac8d4824c62..ab01231f334 100644
--- a/pkgs/os-specific/linux/iw/default.nix
+++ b/pkgs/os-specific/linux/iw/default.nix
@@ -1,11 +1,11 @@
 {stdenv, fetchurl, libnl, pkgconfig}:
 
 stdenv.mkDerivation rec {
-  name = "iw-3.10";
+  name = "iw-3.14";
 
   src = fetchurl {
     url = "https://www.kernel.org/pub/software/network/iw/${name}.tar.xz";
-    sha256 = "1sagsrl2s0d3ar3q2yc5qxk2d47zgn551akwcs9f4a5prw9f4vj5";
+    sha256 = "16fr13cl02702d9yjqlgvnxvpv0w0mqn0acba39iwn2lln5b4747";
   };
 
   buildInputs = [ libnl pkgconfig ];
diff --git a/pkgs/os-specific/linux/iwlwifi/default.nix b/pkgs/os-specific/linux/iwlwifi/default.nix
deleted file mode 100644
index 1a28720f004..00000000000
--- a/pkgs/os-specific/linux/iwlwifi/default.nix
+++ /dev/null
@@ -1,40 +0,0 @@
-{stdenv, fetchurl, kernelDev}:
-
-let version = "1.2.25"; in
-
-stdenv.mkDerivation rec {
-  name = "iwlwifi-${version}-${kernelDev.version}";
-
-  src = fetchurl {
-    url = "http://www.intellinuxwireless.org/iwlwifi/downloads/iwlwifi-${version}.tgz";
-    sha256 = "09fjy0swcyd77fdp8x2825wj5cd73hwbzl8mz9sy2ha21p1qwq1d";
-  };
-
-  preBuild = ''
-    substituteInPlace scripts/generate_compatible \
-      --replace '/usr/bin/env /bin/bash' $shell
-    substituteInPlace Makefile \
-      --replace /sbin/depmod true
-
-    # Urgh, we need the complete kernel sources for some header
-    # files.  So unpack the original kernel source tarball and copy
-    # the configured include directory etc. on top of it.
-    kernelVersion=$(cd ${kernelDev}/lib/modules && ls)
-    kernelBuild=$(echo ${kernelDev}/lib/modules/$kernelVersion/source)
-    tar xvfj ${kernelDev.src}
-    kernelSource=$(echo $(pwd)/linux-*)
-    cp -prd $kernelBuild/* $kernelSource
-
-    makeFlags=KSRC=$kernelSource
-    make $makeFlags || true
-    make $makeFlags
-
-    installFlags=KMISC=$out/lib/modules/$kernelVersion/misc
-  ''; # */
-
-  meta = {
-    description = "Intel Wireless WiFi Link drivers for Linux";
-    homepage = http://www.intellinuxwireless.org/;
-    license = "GPLv2";
-  };
-}
diff --git a/pkgs/os-specific/linux/jujuutils/default.nix b/pkgs/os-specific/linux/jujuutils/default.nix
index 7c688943ea8..a47b59e9e56 100644
--- a/pkgs/os-specific/linux/jujuutils/default.nix
+++ b/pkgs/os-specific/linux/jujuutils/default.nix
@@ -13,6 +13,6 @@ stdenv.mkDerivation {
   meta = {
     homepage = "http://code.google.com/p/jujuutils/";
     description = "Utilities around FireWire devices connected to a Linux computer";
-    license = "GPLv2";
+    license = stdenv.lib.licenses.gpl2;
   };
 }
diff --git a/pkgs/os-specific/linux/kernel-headers/2.6.28.nix b/pkgs/os-specific/linux/kernel-headers/3.14.nix
index 1ba03010f8a..d9d0ce7e3b3 100644
--- a/pkgs/os-specific/linux/kernel-headers/2.6.28.nix
+++ b/pkgs/os-specific/linux/kernel-headers/3.14.nix
@@ -1,46 +1,50 @@
-{stdenv, fetchurl, perl, cross ? null}:
+{ stdenv, fetchurl, perl, cross ? null }:
 
 assert cross == null -> stdenv.isLinux;
 
-let version = "2.6.28.5"; in
+let
+
+  version = "3.14.1";
+
+  kernelHeadersBaseConfig =
+    if cross == null
+    then stdenv.platform.kernelHeadersBaseConfig
+    else cross.platform.kernelHeadersBaseConfig;
+
+in
 
 stdenv.mkDerivation {
   name = "linux-headers-${version}";
 
   src = fetchurl {
-    url = "mirror://kernel/linux/kernel/v2.6/linux-${version}.tar.bz2";
-    sha256 = "0hifjh75sinifr5138v22zwbpqln6lhn65k8b57a1dyzlqca7cl9";
+    url = "mirror://kernel/linux/kernel/v3.x/linux-${version}.tar.xz";
+    sha256 = "1njm8gvlj7cq0m1051yxszl4f63383a7sv1na13hkqkv36kipgqx";
   };
 
   targetConfig = if cross != null then cross.config else null;
 
   platform =
-    if cross != null then cross.arch else
+    if cross != null then cross.platform.kernelArch else
     if stdenv.system == "i686-linux" then "i386" else
     if stdenv.system == "x86_64-linux" then "x86_64" else
     if stdenv.system == "powerpc-linux" then "powerpc" else
     if stdenv.isArm then "arm" else
-    if stdenv.system == "mips64el-linux" then "mips" else
+    if stdenv.platform ? kernelArch then stdenv.platform.kernelArch else
     abort "don't know what the kernel include directory is called for this platform";
 
   buildInputs = [perl];
 
   extraIncludeDirs =
     if cross != null then
-	(if cross.arch == "powerpc" then ["ppc"] else [])
+        (if cross.arch == "powerpc" then ["ppc"] else [])
     else if stdenv.system == "powerpc-linux" then ["ppc"] else [];
 
-  patchPhase = ''
-    patch --verbose -p1 < "${./unifdef-getline.patch}"
-    sed -i '/scsi/d' include/Kbuild
-    sed -i 's|/ %/: prepare scripts FORCE|%/: prepare scripts FORCE|' Makefile
-  '';
-
   buildPhase = ''
     if test -n "$targetConfig"; then
        export ARCH=$platform
     fi
-    make mrproper headers_check
+    make ${kernelHeadersBaseConfig} SHELL=bash
+    make mrproper headers_check SHELL=bash
   '';
 
   installPhase = ''
@@ -58,4 +62,10 @@ stdenv.mkDerivation {
       ln -s asm $out/include/asm-x86
     fi
   '';
+
+  meta = with stdenv.lib; {
+    description = "Header files and scripts for Linux kernel";
+    license = licenses.gpl2;
+    platforms = platforms.linux;
+  };
 }
diff --git a/pkgs/os-specific/linux/kernel-headers/3.7.nix b/pkgs/os-specific/linux/kernel-headers/3.7.nix
index 4371bf7df9c..e6fbf9bb9bc 100644
--- a/pkgs/os-specific/linux/kernel-headers/3.7.nix
+++ b/pkgs/os-specific/linux/kernel-headers/3.7.nix
@@ -62,4 +62,10 @@ stdenv.mkDerivation {
       ln -s asm $out/include/asm-x86
     fi
   '';
+
+  meta = with stdenv.lib; {
+    description = "Header files and scripts for Linux kernel";
+    license = licenses.gpl2;
+    platforms = platforms.linux;
+  };
 }
diff --git a/pkgs/os-specific/linux/kernel-headers/default.nix b/pkgs/os-specific/linux/kernel-headers/default.nix
new file mode 100644
index 00000000000..e4ce1945705
--- /dev/null
+++ b/pkgs/os-specific/linux/kernel-headers/default.nix
@@ -0,0 +1,25 @@
+{ stdenv, kernel, perl }:
+
+let
+  baseBuildFlags = [ "INSTALL_HDR_PATH=$(out)" "headers_install" ];
+in stdenv.mkDerivation {
+  name = "linux-headers-${kernel.version}";
+
+  inherit (kernel) src patches;
+
+  nativeBuildInputs = [ perl ];
+
+  buildFlags = [ "ARCH=${stdenv.platform.kernelArch}" ] ++ baseBuildFlags;
+
+  crossAttrs = {
+    inherit (kernel.crossDrv) src patches;
+    buildFlags = [ "ARCH=${stdenv.cross.platform.kernelArch}" ] ++ baseBuildFlags;
+  };
+
+  installPhase = ''
+    find $out \( -name ..install.cmd -o -name .install \) -print0 | xargs -0 rm
+  '';
+
+  # Headers shouldn't reference anything else
+  allowedReferences = [];
+}
diff --git a/pkgs/os-specific/linux/kernel/apparmor-patches/3.2/0001-AppArmor-compatibility-patch-for-v5-network-controll.patch b/pkgs/os-specific/linux/kernel/apparmor-patches/3.2/0001-AppArmor-compatibility-patch-for-v5-network-controll.patch
new file mode 100644
index 00000000000..b411f43298c
--- /dev/null
+++ b/pkgs/os-specific/linux/kernel/apparmor-patches/3.2/0001-AppArmor-compatibility-patch-for-v5-network-controll.patch
@@ -0,0 +1,553 @@
+From 125fccb600288968aa3395883c0a394c47176fcd Mon Sep 17 00:00:00 2001
+From: John Johansen <john.johansen@canonical.com>
+Date: Wed, 10 Aug 2011 22:02:39 -0700
+Subject: [PATCH 1/3] AppArmor: compatibility patch for v5 network controll
+
+Add compatibility for v5 network rules.
+
+Signed-off-by: John Johansen <john.johansen@canonical.com>
+---
+ include/linux/lsm_audit.h          |    4 +
+ security/apparmor/Makefile         |   19 +++-
+ security/apparmor/include/net.h    |   40 +++++++++
+ security/apparmor/include/policy.h |    3 +
+ security/apparmor/lsm.c            |  112 ++++++++++++++++++++++++
+ security/apparmor/net.c            |  170 ++++++++++++++++++++++++++++++++++++
+ security/apparmor/policy.c         |    1 +
+ security/apparmor/policy_unpack.c  |   48 +++++++++-
+ 8 files changed, 394 insertions(+), 3 deletions(-)
+ create mode 100644 security/apparmor/include/net.h
+ create mode 100644 security/apparmor/net.c
+
+diff --git a/include/linux/lsm_audit.h b/include/linux/lsm_audit.h
+index 88e78de..c63979a 100644
+--- a/include/linux/lsm_audit.h
++++ b/include/linux/lsm_audit.h
+@@ -124,6 +124,10 @@ struct common_audit_data {
+ 					u32 denied;
+ 					uid_t ouid;
+ 				} fs;
++				struct {
++					int type, protocol;
++					struct sock *sk;
++				} net;
+ 			};
+ 		} apparmor_audit_data;
+ #endif
+diff --git a/security/apparmor/Makefile b/security/apparmor/Makefile
+index 2dafe50..7cefef9 100644
+--- a/security/apparmor/Makefile
++++ b/security/apparmor/Makefile
+@@ -4,9 +4,9 @@ obj-$(CONFIG_SECURITY_APPARMOR) += apparmor.o
+ 
+ apparmor-y := apparmorfs.o audit.o capability.o context.o ipc.o lib.o match.o \
+               path.o domain.o policy.o policy_unpack.o procattr.o lsm.o \
+-              resource.o sid.o file.o
++              resource.o sid.o file.o net.o
+ 
+-clean-files := capability_names.h rlim_names.h
++clean-files := capability_names.h rlim_names.h af_names.h
+ 
+ 
+ # Build a lower case string table of capability names
+@@ -44,9 +44,24 @@ cmd_make-rlim = echo "static const char *rlim_names[] = {" > $@ ;\
+ 	sed -r -n "s/^\# ?define[ \t]+(RLIMIT_[A-Z0-9_]+).*/\1,/p" $< >> $@ ;\
+ 	echo "};" >> $@
+ 
++# Build a lower case string table of address family names.
++# Transform lines from
++# #define AF_INET		2	/* Internet IP Protocol 	*/
++# to
++# [2] = "inet",
++quiet_cmd_make-af = GEN     $@
++cmd_make-af = echo "static const char *address_family_names[] = {" > $@ ;\
++	sed $< >> $@ -r -n -e "/AF_MAX/d" -e "/AF_LOCAL/d" -e \
++	  's/^\#define[ \t]+AF_([A-Z0-9_]+)[ \t]+([0-9]+).*/[\2] = "\L\1",/p';\
++	echo "};" >> $@
++
++
+ $(obj)/capability.o : $(obj)/capability_names.h
+ $(obj)/resource.o : $(obj)/rlim_names.h
++$(obj)/net.o : $(obj)/af_names.h
+ $(obj)/capability_names.h : $(srctree)/include/linux/capability.h
+ 	$(call cmd,make-caps)
+ $(obj)/rlim_names.h : $(srctree)/include/asm-generic/resource.h
+ 	$(call cmd,make-rlim)
++$(obj)/af_names.h : $(srctree)/include/linux/socket.h
++	$(call cmd,make-af)
+\ No newline at end of file
+diff --git a/security/apparmor/include/net.h b/security/apparmor/include/net.h
+new file mode 100644
+index 0000000..3c7d599
+--- /dev/null
++++ b/security/apparmor/include/net.h
+@@ -0,0 +1,40 @@
++/*
++ * AppArmor security module
++ *
++ * This file contains AppArmor network mediation definitions.
++ *
++ * Copyright (C) 1998-2008 Novell/SUSE
++ * Copyright 2009-2010 Canonical Ltd.
++ *
++ * 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, version 2 of the
++ * License.
++ */
++
++#ifndef __AA_NET_H
++#define __AA_NET_H
++
++#include <net/sock.h>
++
++/* struct aa_net - network confinement data
++ * @allowed: basic network families permissions
++ * @audit_network: which network permissions to force audit
++ * @quiet_network: which network permissions to quiet rejects
++ */
++struct aa_net {
++	u16 allow[AF_MAX];
++	u16 audit[AF_MAX];
++	u16 quiet[AF_MAX];
++};
++
++extern int aa_net_perm(int op, struct aa_profile *profile, u16 family,
++		       int type, int protocol, struct sock *sk);
++extern int aa_revalidate_sk(int op, struct sock *sk);
++
++static inline void aa_free_net_rules(struct aa_net *new)
++{
++	/* NOP */
++}
++
++#endif /* __AA_NET_H */
+diff --git a/security/apparmor/include/policy.h b/security/apparmor/include/policy.h
+index aeda5cf..6776929 100644
+--- a/security/apparmor/include/policy.h
++++ b/security/apparmor/include/policy.h
+@@ -27,6 +27,7 @@
+ #include "capability.h"
+ #include "domain.h"
+ #include "file.h"
++#include "net.h"
+ #include "resource.h"
+ 
+ extern const char *profile_mode_names[];
+@@ -145,6 +146,7 @@ struct aa_namespace {
+  * @size: the memory consumed by this profiles rules
+  * @file: The set of rules governing basic file access and domain transitions
+  * @caps: capabilities for the profile
++ * @net: network controls for the profile
+  * @rlimits: rlimits for the profile
+  *
+  * The AppArmor profile contains the basic confinement data.  Each profile
+@@ -181,6 +183,7 @@ struct aa_profile {
+ 
+ 	struct aa_file_rules file;
+ 	struct aa_caps caps;
++	struct aa_net net;
+ 	struct aa_rlimit rlimits;
+ };
+ 
+diff --git a/security/apparmor/lsm.c b/security/apparmor/lsm.c
+index 3783202..7459547 100644
+--- a/security/apparmor/lsm.c
++++ b/security/apparmor/lsm.c
+@@ -32,6 +32,7 @@
+ #include "include/context.h"
+ #include "include/file.h"
+ #include "include/ipc.h"
++#include "include/net.h"
+ #include "include/path.h"
+ #include "include/policy.h"
+ #include "include/procattr.h"
+@@ -621,6 +622,104 @@ static int apparmor_task_setrlimit(struct task_struct *task,
+ 	return error;
+ }
+ 
++static int apparmor_socket_create(int family, int type, int protocol, int kern)
++{
++	struct aa_profile *profile;
++	int error = 0;
++
++	if (kern)
++		return 0;
++
++	profile = __aa_current_profile();
++	if (!unconfined(profile))
++		error = aa_net_perm(OP_CREATE, profile, family, type, protocol,
++				    NULL);
++	return error;
++}
++
++static int apparmor_socket_bind(struct socket *sock,
++				struct sockaddr *address, int addrlen)
++{
++	struct sock *sk = sock->sk;
++
++	return aa_revalidate_sk(OP_BIND, sk);
++}
++
++static int apparmor_socket_connect(struct socket *sock,
++				   struct sockaddr *address, int addrlen)
++{
++	struct sock *sk = sock->sk;
++
++	return aa_revalidate_sk(OP_CONNECT, sk);
++}
++
++static int apparmor_socket_listen(struct socket *sock, int backlog)
++{
++	struct sock *sk = sock->sk;
++
++	return aa_revalidate_sk(OP_LISTEN, sk);
++}
++
++static int apparmor_socket_accept(struct socket *sock, struct socket *newsock)
++{
++	struct sock *sk = sock->sk;
++
++	return aa_revalidate_sk(OP_ACCEPT, sk);
++}
++
++static int apparmor_socket_sendmsg(struct socket *sock,
++				   struct msghdr *msg, int size)
++{
++	struct sock *sk = sock->sk;
++
++	return aa_revalidate_sk(OP_SENDMSG, sk);
++}
++
++static int apparmor_socket_recvmsg(struct socket *sock,
++				   struct msghdr *msg, int size, int flags)
++{
++	struct sock *sk = sock->sk;
++
++	return aa_revalidate_sk(OP_RECVMSG, sk);
++}
++
++static int apparmor_socket_getsockname(struct socket *sock)
++{
++	struct sock *sk = sock->sk;
++
++	return aa_revalidate_sk(OP_GETSOCKNAME, sk);
++}
++
++static int apparmor_socket_getpeername(struct socket *sock)
++{
++	struct sock *sk = sock->sk;
++
++	return aa_revalidate_sk(OP_GETPEERNAME, sk);
++}
++
++static int apparmor_socket_getsockopt(struct socket *sock, int level,
++				      int optname)
++{
++	struct sock *sk = sock->sk;
++
++	return aa_revalidate_sk(OP_GETSOCKOPT, sk);
++}
++
++static int apparmor_socket_setsockopt(struct socket *sock, int level,
++				      int optname)
++{
++	struct sock *sk = sock->sk;
++
++	return aa_revalidate_sk(OP_SETSOCKOPT, sk);
++}
++
++static int apparmor_socket_shutdown(struct socket *sock, int how)
++{
++	struct sock *sk = sock->sk;
++
++	return aa_revalidate_sk(OP_SOCK_SHUTDOWN, sk);
++}
++
+ static struct security_operations apparmor_ops = {
+ 	.name =				"apparmor",
+ 
+@@ -652,6 +751,19 @@ static struct security_operations apparmor_ops = {
+ 	.getprocattr =			apparmor_getprocattr,
+ 	.setprocattr =			apparmor_setprocattr,
+ 
++	.socket_create =		apparmor_socket_create,
++	.socket_bind =			apparmor_socket_bind,
++	.socket_connect =		apparmor_socket_connect,
++	.socket_listen =		apparmor_socket_listen,
++	.socket_accept =		apparmor_socket_accept,
++	.socket_sendmsg =		apparmor_socket_sendmsg,
++	.socket_recvmsg =		apparmor_socket_recvmsg,
++	.socket_getsockname =		apparmor_socket_getsockname,
++	.socket_getpeername =		apparmor_socket_getpeername,
++	.socket_getsockopt =		apparmor_socket_getsockopt,
++	.socket_setsockopt =		apparmor_socket_setsockopt,
++	.socket_shutdown =		apparmor_socket_shutdown,
++
+ 	.cred_alloc_blank =		apparmor_cred_alloc_blank,
+ 	.cred_free =			apparmor_cred_free,
+ 	.cred_prepare =			apparmor_cred_prepare,
+diff --git a/security/apparmor/net.c b/security/apparmor/net.c
+new file mode 100644
+index 0000000..1765901
+--- /dev/null
++++ b/security/apparmor/net.c
+@@ -0,0 +1,170 @@
++/*
++ * AppArmor security module
++ *
++ * This file contains AppArmor network mediation
++ *
++ * Copyright (C) 1998-2008 Novell/SUSE
++ * Copyright 2009-2010 Canonical Ltd.
++ *
++ * 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, version 2 of the
++ * License.
++ */
++
++#include "include/apparmor.h"
++#include "include/audit.h"
++#include "include/context.h"
++#include "include/net.h"
++#include "include/policy.h"
++
++#include "af_names.h"
++
++static const char *sock_type_names[] = {
++	"unknown(0)",
++	"stream",
++	"dgram",
++	"raw",
++	"rdm",
++	"seqpacket",
++	"dccp",
++	"unknown(7)",
++	"unknown(8)",
++	"unknown(9)",
++	"packet",
++};
++
++/* audit callback for net specific fields */
++static void audit_cb(struct audit_buffer *ab, void *va)
++{
++	struct common_audit_data *sa = va;
++
++	audit_log_format(ab, " family=");
++	if (address_family_names[sa->u.net.family]) {
++		audit_log_string(ab, address_family_names[sa->u.net.family]);
++	} else {
++		audit_log_format(ab, " \"unknown(%d)\"", sa->u.net.family);
++	}
++
++	audit_log_format(ab, " sock_type=");
++	if (sock_type_names[sa->aad.net.type]) {
++		audit_log_string(ab, sock_type_names[sa->aad.net.type]);
++	} else {
++		audit_log_format(ab, "\"unknown(%d)\"", sa->aad.net.type);
++	}
++
++	audit_log_format(ab, " protocol=%d", sa->aad.net.protocol);
++}
++
++/**
++ * audit_net - audit network access
++ * @profile: profile being enforced  (NOT NULL)
++ * @op: operation being checked
++ * @family: network family
++ * @type:   network type
++ * @protocol: network protocol
++ * @sk: socket auditing is being applied to
++ * @error: error code for failure else 0
++ *
++ * Returns: %0 or sa->error else other errorcode on failure
++ */
++static int audit_net(struct aa_profile *profile, int op, u16 family, int type,
++		     int protocol, struct sock *sk, int error)
++{
++	int audit_type = AUDIT_APPARMOR_AUTO;
++	struct common_audit_data sa;
++	if (sk) {
++		COMMON_AUDIT_DATA_INIT(&sa, NET);
++	} else {
++		COMMON_AUDIT_DATA_INIT(&sa, NONE);
++	}
++	/* todo fill in socket addr info */
++
++	sa.aad.op = op,
++	sa.u.net.family = family;
++	sa.u.net.sk = sk;
++	sa.aad.net.type = type;
++	sa.aad.net.protocol = protocol;
++	sa.aad.error = error;
++
++	if (likely(!sa.aad.error)) {
++		u16 audit_mask = profile->net.audit[sa.u.net.family];
++		if (likely((AUDIT_MODE(profile) != AUDIT_ALL) &&
++			   !(1 << sa.aad.net.type & audit_mask)))
++			return 0;
++		audit_type = AUDIT_APPARMOR_AUDIT;
++	} else {
++		u16 quiet_mask = profile->net.quiet[sa.u.net.family];
++		u16 kill_mask = 0;
++		u16 denied = (1 << sa.aad.net.type) & ~quiet_mask;
++
++		if (denied & kill_mask)
++			audit_type = AUDIT_APPARMOR_KILL;
++
++		if ((denied & quiet_mask) &&
++		    AUDIT_MODE(profile) != AUDIT_NOQUIET &&
++		    AUDIT_MODE(profile) != AUDIT_ALL)
++			return COMPLAIN_MODE(profile) ? 0 : sa.aad.error;
++	}
++
++	return aa_audit(audit_type, profile, GFP_KERNEL, &sa, audit_cb);
++}
++
++/**
++ * aa_net_perm - very course network access check
++ * @op: operation being checked
++ * @profile: profile being enforced  (NOT NULL)
++ * @family: network family
++ * @type:   network type
++ * @protocol: network protocol
++ *
++ * Returns: %0 else error if permission denied
++ */
++int aa_net_perm(int op, struct aa_profile *profile, u16 family, int type,
++		int protocol, struct sock *sk)
++{
++	u16 family_mask;
++	int error;
++
++	if ((family < 0) || (family >= AF_MAX))
++		return -EINVAL;
++
++	if ((type < 0) || (type >= SOCK_MAX))
++		return -EINVAL;
++
++	/* unix domain and netlink sockets are handled by ipc */
++	if (family == AF_UNIX || family == AF_NETLINK)
++		return 0;
++
++	family_mask = profile->net.allow[family];
++
++	error = (family_mask & (1 << type)) ? 0 : -EACCES;
++
++	return audit_net(profile, op, family, type, protocol, sk, error);
++}
++
++/**
++ * aa_revalidate_sk - Revalidate access to a sock
++ * @op: operation being checked
++ * @sk: sock being revalidated  (NOT NULL)
++ *
++ * Returns: %0 else error if permission denied
++ */
++int aa_revalidate_sk(int op, struct sock *sk)
++{
++	struct aa_profile *profile;
++	int error = 0;
++
++	/* aa_revalidate_sk should not be called from interrupt context
++	 * don't mediate these calls as they are not task related
++	 */
++	if (in_interrupt())
++		return 0;
++
++	profile = __aa_current_profile();
++	if (!unconfined(profile))
++		error = aa_net_perm(op, profile, sk->sk_family, sk->sk_type,
++				    sk->sk_protocol, sk);
++
++	return error;
++}
+diff --git a/security/apparmor/policy.c b/security/apparmor/policy.c
+index 4f0eade..4d5ce13 100644
+--- a/security/apparmor/policy.c
++++ b/security/apparmor/policy.c
+@@ -745,6 +745,7 @@ static void free_profile(struct aa_profile *profile)
+ 
+ 	aa_free_file_rules(&profile->file);
+ 	aa_free_cap_rules(&profile->caps);
++	aa_free_net_rules(&profile->net);
+ 	aa_free_rlimit_rules(&profile->rlimits);
+ 
+ 	aa_free_sid(profile->sid);
+diff --git a/security/apparmor/policy_unpack.c b/security/apparmor/policy_unpack.c
+index 741dd13..ee8043e 100644
+--- a/security/apparmor/policy_unpack.c
++++ b/security/apparmor/policy_unpack.c
+@@ -190,6 +190,19 @@ fail:
+ 	return 0;
+ }
+ 
++static bool unpack_u16(struct aa_ext *e, u16 *data, const char *name)
++{
++	if (unpack_nameX(e, AA_U16, name)) {
++		if (!inbounds(e, sizeof(u16)))
++			return 0;
++		if (data)
++			*data = le16_to_cpu(get_unaligned((u16 *) e->pos));
++		e->pos += sizeof(u16);
++		return 1;
++	}
++	return 0;
++}
++
+ static bool unpack_u32(struct aa_ext *e, u32 *data, const char *name)
+ {
+ 	if (unpack_nameX(e, AA_U32, name)) {
+@@ -468,7 +481,8 @@ static struct aa_profile *unpack_profile(struct aa_ext *e)
+ {
+ 	struct aa_profile *profile = NULL;
+ 	const char *name = NULL;
+-	int error = -EPROTO;
++	size_t size = 0;
++	int i, error = -EPROTO;
+ 	kernel_cap_t tmpcap;
+ 	u32 tmp;
+ 
+@@ -559,6 +573,38 @@ static struct aa_profile *unpack_profile(struct aa_ext *e)
+ 	if (!unpack_rlimits(e, profile))
+ 		goto fail;
+ 
++	size = unpack_array(e, "net_allowed_af");
++	if (size) {
++
++		for (i = 0; i < size; i++) {
++			/* discard extraneous rules that this kernel will
++			 * never request
++			 */
++			if (i >= AF_MAX) {
++				u16 tmp;
++				if (!unpack_u16(e, &tmp, NULL) ||
++				    !unpack_u16(e, &tmp, NULL) ||
++				    !unpack_u16(e, &tmp, NULL))
++					goto fail;
++				continue;
++			}
++			if (!unpack_u16(e, &profile->net.allow[i], NULL))
++				goto fail;
++			if (!unpack_u16(e, &profile->net.audit[i], NULL))
++				goto fail;
++			if (!unpack_u16(e, &profile->net.quiet[i], NULL))
++				goto fail;
++		}
++		if (!unpack_nameX(e, AA_ARRAYEND, NULL))
++			goto fail;
++		/*
++		 * allow unix domain and netlink sockets they are handled
++		 * by IPC
++		 */
++	}
++	profile->net.allow[AF_UNIX] = 0xffff;
++	profile->net.allow[AF_NETLINK] = 0xffff;
++
+ 	/* get file rules */
+ 	profile->file.dfa = unpack_dfa(e);
+ 	if (IS_ERR(profile->file.dfa)) {
+-- 
+1.7.9.5
+
diff --git a/pkgs/os-specific/linux/kernel/apparmor-patches/3.2/0002-AppArmor-compatibility-patch-for-v5-interface.patch b/pkgs/os-specific/linux/kernel/apparmor-patches/3.2/0002-AppArmor-compatibility-patch-for-v5-interface.patch
new file mode 100644
index 00000000000..aa4b6b1109f
--- /dev/null
+++ b/pkgs/os-specific/linux/kernel/apparmor-patches/3.2/0002-AppArmor-compatibility-patch-for-v5-interface.patch
@@ -0,0 +1,391 @@
+From 004192fb5223c7b81a949e36a080a5da56132826 Mon Sep 17 00:00:00 2001
+From: John Johansen <john.johansen@canonical.com>
+Date: Wed, 10 Aug 2011 22:02:40 -0700
+Subject: [PATCH 2/3] AppArmor: compatibility patch for v5 interface
+
+Signed-off-by: John Johansen <john.johansen@canonical.com>
+---
+ security/apparmor/Kconfig              |    9 +
+ security/apparmor/Makefile             |    1 +
+ security/apparmor/apparmorfs-24.c      |  287 ++++++++++++++++++++++++++++++++
+ security/apparmor/apparmorfs.c         |   18 +-
+ security/apparmor/include/apparmorfs.h |    6 +
+ 5 files changed, 319 insertions(+), 2 deletions(-)
+ create mode 100644 security/apparmor/apparmorfs-24.c
+
+diff --git a/security/apparmor/Kconfig b/security/apparmor/Kconfig
+index 9b9013b..51ebf96 100644
+--- a/security/apparmor/Kconfig
++++ b/security/apparmor/Kconfig
+@@ -29,3 +29,12 @@ config SECURITY_APPARMOR_BOOTPARAM_VALUE
+ 	  boot.
+ 
+ 	  If you are unsure how to answer this question, answer 1.
++
++config SECURITY_APPARMOR_COMPAT_24
++	bool "Enable AppArmor 2.4 compatability"
++	depends on SECURITY_APPARMOR
++	default y
++	help
++	  This option enables compatability with AppArmor 2.4.  It is
++          recommended if compatability with older versions of AppArmor
++          is desired.
+diff --git a/security/apparmor/Makefile b/security/apparmor/Makefile
+index 7cefef9..0bb604b 100644
+--- a/security/apparmor/Makefile
++++ b/security/apparmor/Makefile
+@@ -5,6 +5,7 @@ obj-$(CONFIG_SECURITY_APPARMOR) += apparmor.o
+ apparmor-y := apparmorfs.o audit.o capability.o context.o ipc.o lib.o match.o \
+               path.o domain.o policy.o policy_unpack.o procattr.o lsm.o \
+               resource.o sid.o file.o net.o
++apparmor-$(CONFIG_SECURITY_APPARMOR_COMPAT_24) += apparmorfs-24.o
+ 
+ clean-files := capability_names.h rlim_names.h af_names.h
+ 
+diff --git a/security/apparmor/apparmorfs-24.c b/security/apparmor/apparmorfs-24.c
+new file mode 100644
+index 0000000..dc8c744
+--- /dev/null
++++ b/security/apparmor/apparmorfs-24.c
+@@ -0,0 +1,287 @@
++/*
++ * AppArmor security module
++ *
++ * This file contains AppArmor /sys/kernel/secrutiy/apparmor interface functions
++ *
++ * Copyright (C) 1998-2008 Novell/SUSE
++ * Copyright 2009-2010 Canonical Ltd.
++ *
++ * 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, version 2 of the
++ * License.
++ *
++ *
++ * This file contain functions providing an interface for <= AppArmor 2.4
++ * compatibility.  It is dependent on CONFIG_SECURITY_APPARMOR_COMPAT_24
++ * being set (see Makefile).
++ */
++
++#include <linux/security.h>
++#include <linux/vmalloc.h>
++#include <linux/module.h>
++#include <linux/seq_file.h>
++#include <linux/uaccess.h>
++#include <linux/namei.h>
++
++#include "include/apparmor.h"
++#include "include/audit.h"
++#include "include/context.h"
++#include "include/policy.h"
++
++
++/* apparmor/matching */
++static ssize_t aa_matching_read(struct file *file, char __user *buf,
++				size_t size, loff_t *ppos)
++{
++	const char matching[] = "pattern=aadfa audit perms=crwxamlk/ "
++	    "user::other";
++
++	return simple_read_from_buffer(buf, size, ppos, matching,
++				       sizeof(matching) - 1);
++}
++
++const struct file_operations aa_fs_matching_fops = {
++	.read = aa_matching_read,
++};
++
++/* apparmor/features */
++static ssize_t aa_features_read(struct file *file, char __user *buf,
++				size_t size, loff_t *ppos)
++{
++	const char features[] = "file=3.1 capability=2.0 network=1.0 "
++	    "change_hat=1.5 change_profile=1.1 " "aanamespaces=1.1 rlimit=1.1";
++
++	return simple_read_from_buffer(buf, size, ppos, features,
++				       sizeof(features) - 1);
++}
++
++const struct file_operations aa_fs_features_fops = {
++	.read = aa_features_read,
++};
++
++/**
++ * __next_namespace - find the next namespace to list
++ * @root: root namespace to stop search at (NOT NULL)
++ * @ns: current ns position (NOT NULL)
++ *
++ * Find the next namespace from @ns under @root and handle all locking needed
++ * while switching current namespace.
++ *
++ * Returns: next namespace or NULL if at last namespace under @root
++ * NOTE: will not unlock root->lock
++ */
++static struct aa_namespace *__next_namespace(struct aa_namespace *root,
++					     struct aa_namespace *ns)
++{
++	struct aa_namespace *parent;
++
++	/* is next namespace a child */
++	if (!list_empty(&ns->sub_ns)) {
++		struct aa_namespace *next;
++		next = list_first_entry(&ns->sub_ns, typeof(*ns), base.list);
++		read_lock(&next->lock);
++		return next;
++	}
++
++	/* check if the next ns is a sibling, parent, gp, .. */
++	parent = ns->parent;
++	while (parent) {
++		read_unlock(&ns->lock);
++		list_for_each_entry_continue(ns, &parent->sub_ns, base.list) {
++			read_lock(&ns->lock);
++			return ns;
++		}
++		if (parent == root)
++			return NULL;
++		ns = parent;
++		parent = parent->parent;
++	}
++
++	return NULL;
++}
++
++/**
++ * __first_profile - find the first profile in a namespace
++ * @root: namespace that is root of profiles being displayed (NOT NULL)
++ * @ns: namespace to start in   (NOT NULL)
++ *
++ * Returns: unrefcounted profile or NULL if no profile
++ */
++static struct aa_profile *__first_profile(struct aa_namespace *root,
++					  struct aa_namespace *ns)
++{
++	for ( ; ns; ns = __next_namespace(root, ns)) {
++		if (!list_empty(&ns->base.profiles))
++			return list_first_entry(&ns->base.profiles,
++						struct aa_profile, base.list);
++	}
++	return NULL;
++}
++
++/**
++ * __next_profile - step to the next profile in a profile tree
++ * @profile: current profile in tree (NOT NULL)
++ *
++ * Perform a depth first taversal on the profile tree in a namespace
++ *
++ * Returns: next profile or NULL if done
++ * Requires: profile->ns.lock to be held
++ */
++static struct aa_profile *__next_profile(struct aa_profile *p)
++{
++	struct aa_profile *parent;
++	struct aa_namespace *ns = p->ns;
++
++	/* is next profile a child */
++	if (!list_empty(&p->base.profiles))
++		return list_first_entry(&p->base.profiles, typeof(*p),
++					base.list);
++
++	/* is next profile a sibling, parent sibling, gp, subling, .. */
++	parent = p->parent;
++	while (parent) {
++		list_for_each_entry_continue(p, &parent->base.profiles,
++					     base.list)
++				return p;
++		p = parent;
++		parent = parent->parent;
++	}
++
++	/* is next another profile in the namespace */
++	list_for_each_entry_continue(p, &ns->base.profiles, base.list)
++		return p;
++
++	return NULL;
++}
++
++/**
++ * next_profile - step to the next profile in where ever it may be
++ * @root: root namespace  (NOT NULL)
++ * @profile: current profile  (NOT NULL)
++ *
++ * Returns: next profile or NULL if there isn't one
++ */
++static struct aa_profile *next_profile(struct aa_namespace *root,
++				       struct aa_profile *profile)
++{
++	struct aa_profile *next = __next_profile(profile);
++	if (next)
++		return next;
++
++	/* finished all profiles in namespace move to next namespace */
++	return __first_profile(root, __next_namespace(root, profile->ns));
++}
++
++/**
++ * p_start - start a depth first traversal of profile tree
++ * @f: seq_file to fill
++ * @pos: current position
++ *
++ * Returns: first profile under current namespace or NULL if none found
++ *
++ * acquires first ns->lock
++ */
++static void *p_start(struct seq_file *f, loff_t *pos)
++	__acquires(root->lock)
++{
++	struct aa_profile *profile = NULL;
++	struct aa_namespace *root = aa_current_profile()->ns;
++	loff_t l = *pos;
++	f->private = aa_get_namespace(root);
++
++
++	/* find the first profile */
++	read_lock(&root->lock);
++	profile = __first_profile(root, root);
++
++	/* skip to position */
++	for (; profile && l > 0; l--)
++		profile = next_profile(root, profile);
++
++	return profile;
++}
++
++/**
++ * p_next - read the next profile entry
++ * @f: seq_file to fill
++ * @p: profile previously returned
++ * @pos: current position
++ *
++ * Returns: next profile after @p or NULL if none
++ *
++ * may acquire/release locks in namespace tree as necessary
++ */
++static void *p_next(struct seq_file *f, void *p, loff_t *pos)
++{
++	struct aa_profile *profile = p;
++	struct aa_namespace *root = f->private;
++	(*pos)++;
++
++	return next_profile(root, profile);
++}
++
++/**
++ * p_stop - stop depth first traversal
++ * @f: seq_file we are filling
++ * @p: the last profile writen
++ *
++ * Release all locking done by p_start/p_next on namespace tree
++ */
++static void p_stop(struct seq_file *f, void *p)
++	__releases(root->lock)
++{
++	struct aa_profile *profile = p;
++	struct aa_namespace *root = f->private, *ns;
++
++	if (profile) {
++		for (ns = profile->ns; ns && ns != root; ns = ns->parent)
++			read_unlock(&ns->lock);
++	}
++	read_unlock(&root->lock);
++	aa_put_namespace(root);
++}
++
++/**
++ * seq_show_profile - show a profile entry
++ * @f: seq_file to file
++ * @p: current position (profile)    (NOT NULL)
++ *
++ * Returns: error on failure
++ */
++static int seq_show_profile(struct seq_file *f, void *p)
++{
++	struct aa_profile *profile = (struct aa_profile *)p;
++	struct aa_namespace *root = f->private;
++
++	if (profile->ns != root)
++		seq_printf(f, ":%s://", aa_ns_name(root, profile->ns));
++	seq_printf(f, "%s (%s)\n", profile->base.hname,
++		   COMPLAIN_MODE(profile) ? "complain" : "enforce");
++
++	return 0;
++}
++
++static const struct seq_operations aa_fs_profiles_op = {
++	.start = p_start,
++	.next = p_next,
++	.stop = p_stop,
++	.show = seq_show_profile,
++};
++
++static int profiles_open(struct inode *inode, struct file *file)
++{
++	return seq_open(file, &aa_fs_profiles_op);
++}
++
++static int profiles_release(struct inode *inode, struct file *file)
++{
++	return seq_release(inode, file);
++}
++
++const struct file_operations aa_fs_profiles_fops = {
++	.open = profiles_open,
++	.read = seq_read,
++	.llseek = seq_lseek,
++	.release = profiles_release,
++};
+diff --git a/security/apparmor/apparmorfs.c b/security/apparmor/apparmorfs.c
+index 69ddb47..867995c 100644
+--- a/security/apparmor/apparmorfs.c
++++ b/security/apparmor/apparmorfs.c
+@@ -187,7 +187,11 @@ void __init aa_destroy_aafs(void)
+ 		aafs_remove(".remove");
+ 		aafs_remove(".replace");
+ 		aafs_remove(".load");
+-
++#ifdef CONFIG_SECURITY_APPARMOR_COMPAT_24
++		aafs_remove("profiles");
++		aafs_remove("matching");
++		aafs_remove("features");
++#endif
+ 		securityfs_remove(aa_fs_dentry);
+ 		aa_fs_dentry = NULL;
+ 	}
+@@ -218,7 +222,17 @@ static int __init aa_create_aafs(void)
+ 		aa_fs_dentry = NULL;
+ 		goto error;
+ 	}
+-
++#ifdef CONFIG_SECURITY_APPARMOR_COMPAT_24
++	error = aafs_create("matching", 0444, &aa_fs_matching_fops);
++	if (error)
++		goto error;
++	error = aafs_create("features", 0444, &aa_fs_features_fops);
++	if (error)
++		goto error;
++#endif
++	error = aafs_create("profiles", 0440, &aa_fs_profiles_fops);
++	if (error)
++		goto error;
+ 	error = aafs_create(".load", 0640, &aa_fs_profile_load);
+ 	if (error)
+ 		goto error;
+diff --git a/security/apparmor/include/apparmorfs.h b/security/apparmor/include/apparmorfs.h
+index cb1e93a..14f955c 100644
+--- a/security/apparmor/include/apparmorfs.h
++++ b/security/apparmor/include/apparmorfs.h
+@@ -17,4 +17,10 @@
+ 
+ extern void __init aa_destroy_aafs(void);
+ 
++#ifdef CONFIG_SECURITY_APPARMOR_COMPAT_24
++extern const struct file_operations aa_fs_matching_fops;
++extern const struct file_operations aa_fs_features_fops;
++extern const struct file_operations aa_fs_profiles_fops;
++#endif
++
+ #endif /* __AA_APPARMORFS_H */
+-- 
+1.7.9.5
+
diff --git a/pkgs/os-specific/linux/kernel/apparmor-patches/3.2/0003-AppArmor-Allow-dfa-backward-compatibility-with-broke.patch b/pkgs/os-specific/linux/kernel/apparmor-patches/3.2/0003-AppArmor-Allow-dfa-backward-compatibility-with-broke.patch
new file mode 100644
index 00000000000..7dd55781fda
--- /dev/null
+++ b/pkgs/os-specific/linux/kernel/apparmor-patches/3.2/0003-AppArmor-Allow-dfa-backward-compatibility-with-broke.patch
@@ -0,0 +1,69 @@
+From e5d90918aa31f948ecec2f3c088567dbab30c90b Mon Sep 17 00:00:00 2001
+From: John Johansen <john.johansen@canonical.com>
+Date: Wed, 10 Aug 2011 22:02:41 -0700
+Subject: [PATCH 3/3] AppArmor: Allow dfa backward compatibility with broken
+ userspace
+
+The apparmor_parser when compiling policy could generate invalid dfas
+that did not have sufficient padding to avoid invalid references, when
+used by the kernel.  The kernels check to verify the next/check table
+size was broken meaning invalid dfas were being created by userspace
+and not caught.
+
+To remain compatible with old tools that are not fixed, pad the loaded
+dfas next/check table.  The dfa's themselves are valid except for the
+high padding for potentially invalid transitions (high bounds error),
+which have a maximimum is 256 entries.  So just allocate an extra null filled
+256 entries for the next/check tables.  This will guarentee all bounds
+are good and invalid transitions go to the null (0) state.
+
+Signed-off-by: John Johansen <john.johansen@canonical.com>
+---
+ security/apparmor/match.c |   17 +++++++++++++++++
+ 1 file changed, 17 insertions(+)
+
+diff --git a/security/apparmor/match.c b/security/apparmor/match.c
+index 94de6b4..081491e 100644
+--- a/security/apparmor/match.c
++++ b/security/apparmor/match.c
+@@ -57,8 +57,17 @@ static struct table_header *unpack_table(char *blob, size_t bsize)
+ 	if (bsize < tsize)
+ 		goto out;
+ 
++	/* Pad table allocation for next/check by 256 entries to remain
++	 * backwards compatible with old (buggy) tools and remain safe without
++	 * run time checks
++	 */
++	if (th.td_id == YYTD_ID_NXT || th.td_id == YYTD_ID_CHK)
++		tsize += 256 * th.td_flags;
++
+ 	table = kvmalloc(tsize);
+ 	if (table) {
++		/* ensure the pad is clear, else there will be errors */
++		memset(table, 0, tsize);
+ 		*table = th;
+ 		if (th.td_flags == YYTD_DATA8)
+ 			UNPACK_ARRAY(table->td_data, blob, th.td_lolen,
+@@ -134,11 +143,19 @@ static int verify_dfa(struct aa_dfa *dfa, int flags)
+ 		goto out;
+ 
+ 	if (flags & DFA_FLAG_VERIFY_STATES) {
++		int warning = 0;
+ 		for (i = 0; i < state_count; i++) {
+ 			if (DEFAULT_TABLE(dfa)[i] >= state_count)
+ 				goto out;
+ 			/* TODO: do check that DEF state recursion terminates */
+ 			if (BASE_TABLE(dfa)[i] + 255 >= trans_count) {
++				if (warning)
++					continue;
++				printk(KERN_WARNING "AppArmor DFA next/check "
++				       "upper bounds error fixed, upgrade "
++				       "user space tools \n");
++				warning = 1;
++			} else if (BASE_TABLE(dfa)[i] >= trans_count) {
+ 				printk(KERN_ERR "AppArmor DFA next/check upper "
+ 				       "bounds error\n");
+ 				goto out;
+-- 
+1.7.9.5
+
diff --git a/pkgs/os-specific/linux/kernel/apparmor-patches/3.4/0001-UBUNTU-SAUCE-AppArmor-Add-profile-introspection-file.patch b/pkgs/os-specific/linux/kernel/apparmor-patches/3.4/0001-UBUNTU-SAUCE-AppArmor-Add-profile-introspection-file.patch
new file mode 100644
index 00000000000..88a50ca780a
--- /dev/null
+++ b/pkgs/os-specific/linux/kernel/apparmor-patches/3.4/0001-UBUNTU-SAUCE-AppArmor-Add-profile-introspection-file.patch
@@ -0,0 +1,264 @@
+From 8de755e4dfdbc40bfcaca848ae6b5aeaf0ede0e8 Mon Sep 17 00:00:00 2001
+From: John Johansen <john.johansen@canonical.com>
+Date: Thu, 22 Jul 2010 02:32:02 -0700
+Subject: [PATCH 1/3] UBUNTU: SAUCE: AppArmor: Add profile introspection file
+ to interface
+
+Add the dynamic profiles file to the interace, to allow load policy
+introspection.
+
+Signed-off-by: John Johansen <john.johansen@canonical.com>
+Acked-by: Kees Cook <kees@ubuntu.com>
+Signed-off-by: Tim Gardner <tim.gardner@canonical.com>
+---
+ security/apparmor/apparmorfs.c |  227 ++++++++++++++++++++++++++++++++++++++++
+ 1 file changed, 227 insertions(+)
+
+diff --git a/security/apparmor/apparmorfs.c b/security/apparmor/apparmorfs.c
+index 16c15ec..89bdc62 100644
+--- a/security/apparmor/apparmorfs.c
++++ b/security/apparmor/apparmorfs.c
+@@ -182,6 +182,232 @@ const struct file_operations aa_fs_seq_file_ops = {
+ 	.release	= single_release,
+ };
+ 
++/**
++ * __next_namespace - find the next namespace to list
++ * @root: root namespace to stop search at (NOT NULL)
++ * @ns: current ns position (NOT NULL)
++ *
++ * Find the next namespace from @ns under @root and handle all locking needed
++ * while switching current namespace.
++ *
++ * Returns: next namespace or NULL if at last namespace under @root
++ * NOTE: will not unlock root->lock
++ */
++static struct aa_namespace *__next_namespace(struct aa_namespace *root,
++					     struct aa_namespace *ns)
++{
++	struct aa_namespace *parent;
++
++	/* is next namespace a child */
++	if (!list_empty(&ns->sub_ns)) {
++		struct aa_namespace *next;
++		next = list_first_entry(&ns->sub_ns, typeof(*ns), base.list);
++		read_lock(&next->lock);
++		return next;
++	}
++
++	/* check if the next ns is a sibling, parent, gp, .. */
++	parent = ns->parent;
++	while (parent) {
++		read_unlock(&ns->lock);
++		list_for_each_entry_continue(ns, &parent->sub_ns, base.list) {
++			read_lock(&ns->lock);
++			return ns;
++		}
++		if (parent == root)
++			return NULL;
++		ns = parent;
++		parent = parent->parent;
++	}
++
++	return NULL;
++}
++
++/**
++ * __first_profile - find the first profile in a namespace
++ * @root: namespace that is root of profiles being displayed (NOT NULL)
++ * @ns: namespace to start in   (NOT NULL)
++ *
++ * Returns: unrefcounted profile or NULL if no profile
++ */
++static struct aa_profile *__first_profile(struct aa_namespace *root,
++					  struct aa_namespace *ns)
++{
++	for ( ; ns; ns = __next_namespace(root, ns)) {
++		if (!list_empty(&ns->base.profiles))
++			return list_first_entry(&ns->base.profiles,
++						struct aa_profile, base.list);
++	}
++	return NULL;
++}
++
++/**
++ * __next_profile - step to the next profile in a profile tree
++ * @profile: current profile in tree (NOT NULL)
++ *
++ * Perform a depth first taversal on the profile tree in a namespace
++ *
++ * Returns: next profile or NULL if done
++ * Requires: profile->ns.lock to be held
++ */
++static struct aa_profile *__next_profile(struct aa_profile *p)
++{
++	struct aa_profile *parent;
++	struct aa_namespace *ns = p->ns;
++
++	/* is next profile a child */
++	if (!list_empty(&p->base.profiles))
++		return list_first_entry(&p->base.profiles, typeof(*p),
++					base.list);
++
++	/* is next profile a sibling, parent sibling, gp, subling, .. */
++	parent = p->parent;
++	while (parent) {
++		list_for_each_entry_continue(p, &parent->base.profiles,
++					     base.list)
++				return p;
++		p = parent;
++		parent = parent->parent;
++	}
++
++	/* is next another profile in the namespace */
++	list_for_each_entry_continue(p, &ns->base.profiles, base.list)
++		return p;
++
++	return NULL;
++}
++
++/**
++ * next_profile - step to the next profile in where ever it may be
++ * @root: root namespace  (NOT NULL)
++ * @profile: current profile  (NOT NULL)
++ *
++ * Returns: next profile or NULL if there isn't one
++ */
++static struct aa_profile *next_profile(struct aa_namespace *root,
++				       struct aa_profile *profile)
++{
++	struct aa_profile *next = __next_profile(profile);
++	if (next)
++		return next;
++
++	/* finished all profiles in namespace move to next namespace */
++	return __first_profile(root, __next_namespace(root, profile->ns));
++}
++
++/**
++ * p_start - start a depth first traversal of profile tree
++ * @f: seq_file to fill
++ * @pos: current position
++ *
++ * Returns: first profile under current namespace or NULL if none found
++ *
++ * acquires first ns->lock
++ */
++static void *p_start(struct seq_file *f, loff_t *pos)
++	__acquires(root->lock)
++{
++	struct aa_profile *profile = NULL;
++	struct aa_namespace *root = aa_current_profile()->ns;
++	loff_t l = *pos;
++	f->private = aa_get_namespace(root);
++
++
++	/* find the first profile */
++	read_lock(&root->lock);
++	profile = __first_profile(root, root);
++
++	/* skip to position */
++	for (; profile && l > 0; l--)
++		profile = next_profile(root, profile);
++
++	return profile;
++}
++
++/**
++ * p_next - read the next profile entry
++ * @f: seq_file to fill
++ * @p: profile previously returned
++ * @pos: current position
++ *
++ * Returns: next profile after @p or NULL if none
++ *
++ * may acquire/release locks in namespace tree as necessary
++ */
++static void *p_next(struct seq_file *f, void *p, loff_t *pos)
++{
++	struct aa_profile *profile = p;
++	struct aa_namespace *root = f->private;
++	(*pos)++;
++
++	return next_profile(root, profile);
++}
++
++/**
++ * p_stop - stop depth first traversal
++ * @f: seq_file we are filling
++ * @p: the last profile writen
++ *
++ * Release all locking done by p_start/p_next on namespace tree
++ */
++static void p_stop(struct seq_file *f, void *p)
++	__releases(root->lock)
++{
++	struct aa_profile *profile = p;
++	struct aa_namespace *root = f->private, *ns;
++
++	if (profile) {
++		for (ns = profile->ns; ns && ns != root; ns = ns->parent)
++			read_unlock(&ns->lock);
++	}
++	read_unlock(&root->lock);
++	aa_put_namespace(root);
++}
++
++/**
++ * seq_show_profile - show a profile entry
++ * @f: seq_file to file
++ * @p: current position (profile)    (NOT NULL)
++ *
++ * Returns: error on failure
++ */
++static int seq_show_profile(struct seq_file *f, void *p)
++{
++	struct aa_profile *profile = (struct aa_profile *)p;
++	struct aa_namespace *root = f->private;
++
++	if (profile->ns != root)
++		seq_printf(f, ":%s://", aa_ns_name(root, profile->ns));
++	seq_printf(f, "%s (%s)\n", profile->base.hname,
++		   COMPLAIN_MODE(profile) ? "complain" : "enforce");
++
++	return 0;
++}
++
++static const struct seq_operations aa_fs_profiles_op = {
++	.start = p_start,
++	.next = p_next,
++	.stop = p_stop,
++	.show = seq_show_profile,
++};
++
++static int profiles_open(struct inode *inode, struct file *file)
++{
++	return seq_open(file, &aa_fs_profiles_op);
++}
++
++static int profiles_release(struct inode *inode, struct file *file)
++{
++	return seq_release(inode, file);
++}
++
++const struct file_operations aa_fs_profiles_fops = {
++	.open = profiles_open,
++	.read = seq_read,
++	.llseek = seq_lseek,
++	.release = profiles_release,
++};
++
+ /** Base file system setup **/
+ 
+ static struct aa_fs_entry aa_fs_entry_file[] = {
+@@ -210,6 +436,7 @@ static struct aa_fs_entry aa_fs_entry_apparmor[] = {
+ 	AA_FS_FILE_FOPS(".load", 0640, &aa_fs_profile_load),
+ 	AA_FS_FILE_FOPS(".replace", 0640, &aa_fs_profile_replace),
+ 	AA_FS_FILE_FOPS(".remove", 0640, &aa_fs_profile_remove),
++	AA_FS_FILE_FOPS("profiles", 0640, &aa_fs_profiles_fops),
+ 	AA_FS_DIR("features", aa_fs_entry_features),
+ 	{ }
+ };
+-- 
+1.7.9.5
+
diff --git a/pkgs/os-specific/linux/kernel/apparmor-patches/3.4/0002-UBUNTU-SAUCE-AppArmor-basic-networking-rules.patch b/pkgs/os-specific/linux/kernel/apparmor-patches/3.4/0002-UBUNTU-SAUCE-AppArmor-basic-networking-rules.patch
new file mode 100644
index 00000000000..01316b9db78
--- /dev/null
+++ b/pkgs/os-specific/linux/kernel/apparmor-patches/3.4/0002-UBUNTU-SAUCE-AppArmor-basic-networking-rules.patch
@@ -0,0 +1,603 @@
+From 423e2cb454d75d6185eecd0c1b5cf6ccc2d8482d Mon Sep 17 00:00:00 2001
+From: John Johansen <john.johansen@canonical.com>
+Date: Mon, 4 Oct 2010 15:03:36 -0700
+Subject: [PATCH 2/3] UBUNTU: SAUCE: AppArmor: basic networking rules
+
+Base support for network mediation.
+
+Signed-off-by: John Johansen <john.johansen@canonical.com>
+---
+ security/apparmor/.gitignore       |    2 +-
+ security/apparmor/Makefile         |   42 +++++++++-
+ security/apparmor/apparmorfs.c     |    1 +
+ security/apparmor/include/audit.h  |    4 +
+ security/apparmor/include/net.h    |   44 ++++++++++
+ security/apparmor/include/policy.h |    3 +
+ security/apparmor/lsm.c            |  112 +++++++++++++++++++++++++
+ security/apparmor/net.c            |  162 ++++++++++++++++++++++++++++++++++++
+ security/apparmor/policy.c         |    1 +
+ security/apparmor/policy_unpack.c  |   46 ++++++++++
+ 10 files changed, 414 insertions(+), 3 deletions(-)
+ create mode 100644 security/apparmor/include/net.h
+ create mode 100644 security/apparmor/net.c
+
+diff --git a/security/apparmor/.gitignore b/security/apparmor/.gitignore
+index 4d995ae..d5b291e 100644
+--- a/security/apparmor/.gitignore
++++ b/security/apparmor/.gitignore
+@@ -1,6 +1,6 @@
+ #
+ # Generated include files
+ #
+-af_names.h
++net_names.h
+ capability_names.h
+ rlim_names.h
+diff --git a/security/apparmor/Makefile b/security/apparmor/Makefile
+index 806bd19..19daa85 100644
+--- a/security/apparmor/Makefile
++++ b/security/apparmor/Makefile
+@@ -4,9 +4,9 @@ obj-$(CONFIG_SECURITY_APPARMOR) += apparmor.o
+ 
+ apparmor-y := apparmorfs.o audit.o capability.o context.o ipc.o lib.o match.o \
+               path.o domain.o policy.o policy_unpack.o procattr.o lsm.o \
+-              resource.o sid.o file.o
++              resource.o sid.o file.o net.o
+ 
+-clean-files := capability_names.h rlim_names.h
++clean-files := capability_names.h rlim_names.h net_names.h
+ 
+ 
+ # Build a lower case string table of capability names
+@@ -20,6 +20,38 @@ cmd_make-caps = echo "static const char *const capability_names[] = {" > $@ ;\
+ 	-e 's/^\#define[ \t]+CAP_([A-Z0-9_]+)[ \t]+([0-9]+)/[\2] = "\L\1",/p';\
+ 	echo "};" >> $@
+ 
++# Build a lower case string table of address family names
++# Transform lines from
++#    define AF_LOCAL	1	/* POSIX name for AF_UNIX	*/
++#    #define AF_INET		2	/* Internet IP Protocol 	*/
++# to
++#    [1] = "local",
++#    [2] = "inet",
++#
++# and build the securityfs entries for the mapping.
++# Transforms lines from
++#    #define AF_INET		2	/* Internet IP Protocol 	*/
++# to
++#    #define AA_FS_AF_MASK "local inet"
++quiet_cmd_make-af = GEN     $@
++cmd_make-af = echo "static const char *address_family_names[] = {" > $@ ;\
++	sed $< >>$@ -r -n -e "/AF_MAX/d" -e "/AF_LOCAL/d" -e \
++	 's/^\#define[ \t]+AF_([A-Z0-9_]+)[ \t]+([0-9]+)(.*)/[\2] = "\L\1",/p';\
++	echo "};" >> $@ ;\
++	echo -n '\#define AA_FS_AF_MASK "' >> $@ ;\
++	sed -r -n 's/^\#define[ \t]+AF_([A-Z0-9_]+)[ \t]+([0-9]+)(.*)/\L\1/p'\
++	 $< | tr '\n' ' ' | sed -e 's/ $$/"\n/' >> $@
++
++# Build a lower case string table of sock type names
++# Transform lines from
++#    SOCK_STREAM	= 1,
++# to
++#    [1] = "stream",
++quiet_cmd_make-sock = GEN     $@
++cmd_make-sock = echo "static const char *sock_type_names[] = {" >> $@ ;\
++	sed $^ >>$@ -r -n \
++	-e 's/^\tSOCK_([A-Z0-9_]+)[\t]+=[ \t]+([0-9]+)(.*)/[\2] = "\L\1",/p';\
++	echo "};" >> $@
+ 
+ # Build a lower case string table of rlimit names.
+ # Transforms lines from
+@@ -56,6 +88,7 @@ cmd_make-rlim = echo "static const char *const rlim_names[RLIM_NLIMITS] = {" \
+ 	    tr '\n' ' ' | sed -e 's/ $$/"\n/' >> $@
+ 
+ $(obj)/capability.o : $(obj)/capability_names.h
++$(obj)/net.o : $(obj)/net_names.h
+ $(obj)/resource.o : $(obj)/rlim_names.h
+ $(obj)/capability_names.h : $(srctree)/include/linux/capability.h \
+ 			    $(src)/Makefile
+@@ -63,3 +96,8 @@ $(obj)/capability_names.h : $(srctree)/include/linux/capability.h \
+ $(obj)/rlim_names.h : $(srctree)/include/asm-generic/resource.h \
+ 		      $(src)/Makefile
+ 	$(call cmd,make-rlim)
++$(obj)/net_names.h : $(srctree)/include/linux/socket.h \
++		     $(srctree)/include/linux/net.h \
++		     $(src)/Makefile
++	$(call cmd,make-af)
++	$(call cmd,make-sock)
+diff --git a/security/apparmor/apparmorfs.c b/security/apparmor/apparmorfs.c
+index 89bdc62..c66315d 100644
+--- a/security/apparmor/apparmorfs.c
++++ b/security/apparmor/apparmorfs.c
+@@ -427,6 +427,7 @@ static struct aa_fs_entry aa_fs_entry_domain[] = {
+ static struct aa_fs_entry aa_fs_entry_features[] = {
+ 	AA_FS_DIR("domain",			aa_fs_entry_domain),
+ 	AA_FS_DIR("file",			aa_fs_entry_file),
++	AA_FS_DIR("network",                    aa_fs_entry_network),
+ 	AA_FS_FILE_U64("capability",		VFS_CAP_FLAGS_MASK),
+ 	AA_FS_DIR("rlimit",			aa_fs_entry_rlimit),
+ 	{ }
+diff --git a/security/apparmor/include/audit.h b/security/apparmor/include/audit.h
+index 3868b1e..c1ff09c 100644
+--- a/security/apparmor/include/audit.h
++++ b/security/apparmor/include/audit.h
+@@ -126,6 +126,10 @@ struct apparmor_audit_data {
+ 			u32 denied;
+ 			uid_t ouid;
+ 		} fs;
++		struct {
++			int type, protocol;
++			struct sock *sk;
++		} net;
+ 	};
+ };
+ 
+diff --git a/security/apparmor/include/net.h b/security/apparmor/include/net.h
+new file mode 100644
+index 0000000..cb8a121
+--- /dev/null
++++ b/security/apparmor/include/net.h
+@@ -0,0 +1,44 @@
++/*
++ * AppArmor security module
++ *
++ * This file contains AppArmor network mediation definitions.
++ *
++ * Copyright (C) 1998-2008 Novell/SUSE
++ * Copyright 2009-2012 Canonical Ltd.
++ *
++ * 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, version 2 of the
++ * License.
++ */
++
++#ifndef __AA_NET_H
++#define __AA_NET_H
++
++#include <net/sock.h>
++
++#include "apparmorfs.h"
++
++/* struct aa_net - network confinement data
++ * @allowed: basic network families permissions
++ * @audit_network: which network permissions to force audit
++ * @quiet_network: which network permissions to quiet rejects
++ */
++struct aa_net {
++	u16 allow[AF_MAX];
++	u16 audit[AF_MAX];
++	u16 quiet[AF_MAX];
++};
++
++extern struct aa_fs_entry aa_fs_entry_network[];
++
++extern int aa_net_perm(int op, struct aa_profile *profile, u16 family,
++		       int type, int protocol, struct sock *sk);
++extern int aa_revalidate_sk(int op, struct sock *sk);
++
++static inline void aa_free_net_rules(struct aa_net *new)
++{
++	/* NOP */
++}
++
++#endif /* __AA_NET_H */
+diff --git a/security/apparmor/include/policy.h b/security/apparmor/include/policy.h
+index bda4569..eb13a73 100644
+--- a/security/apparmor/include/policy.h
++++ b/security/apparmor/include/policy.h
+@@ -27,6 +27,7 @@
+ #include "capability.h"
+ #include "domain.h"
+ #include "file.h"
++#include "net.h"
+ #include "resource.h"
+ 
+ extern const char *const profile_mode_names[];
+@@ -157,6 +158,7 @@ struct aa_policydb {
+  * @policy: general match rules governing policy
+  * @file: The set of rules governing basic file access and domain transitions
+  * @caps: capabilities for the profile
++ * @net: network controls for the profile
+  * @rlimits: rlimits for the profile
+  *
+  * The AppArmor profile contains the basic confinement data.  Each profile
+@@ -194,6 +196,7 @@ struct aa_profile {
+ 	struct aa_policydb policy;
+ 	struct aa_file_rules file;
+ 	struct aa_caps caps;
++	struct aa_net net;
+ 	struct aa_rlimit rlimits;
+ };
+ 
+diff --git a/security/apparmor/lsm.c b/security/apparmor/lsm.c
+index ad05d39..3cde194 100644
+--- a/security/apparmor/lsm.c
++++ b/security/apparmor/lsm.c
+@@ -32,6 +32,7 @@
+ #include "include/context.h"
+ #include "include/file.h"
+ #include "include/ipc.h"
++#include "include/net.h"
+ #include "include/path.h"
+ #include "include/policy.h"
+ #include "include/procattr.h"
+@@ -622,6 +623,104 @@ static int apparmor_task_setrlimit(struct task_struct *task,
+ 	return error;
+ }
+ 
++static int apparmor_socket_create(int family, int type, int protocol, int kern)
++{
++	struct aa_profile *profile;
++	int error = 0;
++
++	if (kern)
++		return 0;
++
++	profile = __aa_current_profile();
++	if (!unconfined(profile))
++		error = aa_net_perm(OP_CREATE, profile, family, type, protocol,
++				    NULL);
++	return error;
++}
++
++static int apparmor_socket_bind(struct socket *sock,
++				struct sockaddr *address, int addrlen)
++{
++	struct sock *sk = sock->sk;
++
++	return aa_revalidate_sk(OP_BIND, sk);
++}
++
++static int apparmor_socket_connect(struct socket *sock,
++				   struct sockaddr *address, int addrlen)
++{
++	struct sock *sk = sock->sk;
++
++	return aa_revalidate_sk(OP_CONNECT, sk);
++}
++
++static int apparmor_socket_listen(struct socket *sock, int backlog)
++{
++	struct sock *sk = sock->sk;
++
++	return aa_revalidate_sk(OP_LISTEN, sk);
++}
++
++static int apparmor_socket_accept(struct socket *sock, struct socket *newsock)
++{
++	struct sock *sk = sock->sk;
++
++	return aa_revalidate_sk(OP_ACCEPT, sk);
++}
++
++static int apparmor_socket_sendmsg(struct socket *sock,
++				   struct msghdr *msg, int size)
++{
++	struct sock *sk = sock->sk;
++
++	return aa_revalidate_sk(OP_SENDMSG, sk);
++}
++
++static int apparmor_socket_recvmsg(struct socket *sock,
++				   struct msghdr *msg, int size, int flags)
++{
++	struct sock *sk = sock->sk;
++
++	return aa_revalidate_sk(OP_RECVMSG, sk);
++}
++
++static int apparmor_socket_getsockname(struct socket *sock)
++{
++	struct sock *sk = sock->sk;
++
++	return aa_revalidate_sk(OP_GETSOCKNAME, sk);
++}
++
++static int apparmor_socket_getpeername(struct socket *sock)
++{
++	struct sock *sk = sock->sk;
++
++	return aa_revalidate_sk(OP_GETPEERNAME, sk);
++}
++
++static int apparmor_socket_getsockopt(struct socket *sock, int level,
++				      int optname)
++{
++	struct sock *sk = sock->sk;
++
++	return aa_revalidate_sk(OP_GETSOCKOPT, sk);
++}
++
++static int apparmor_socket_setsockopt(struct socket *sock, int level,
++				      int optname)
++{
++	struct sock *sk = sock->sk;
++
++	return aa_revalidate_sk(OP_SETSOCKOPT, sk);
++}
++
++static int apparmor_socket_shutdown(struct socket *sock, int how)
++{
++	struct sock *sk = sock->sk;
++
++	return aa_revalidate_sk(OP_SOCK_SHUTDOWN, sk);
++}
++
+ static struct security_operations apparmor_ops = {
+ 	.name =				"apparmor",
+ 
+@@ -653,6 +752,19 @@ static struct security_operations apparmor_ops = {
+ 	.getprocattr =			apparmor_getprocattr,
+ 	.setprocattr =			apparmor_setprocattr,
+ 
++	.socket_create =		apparmor_socket_create,
++	.socket_bind =			apparmor_socket_bind,
++	.socket_connect =		apparmor_socket_connect,
++	.socket_listen =		apparmor_socket_listen,
++	.socket_accept =		apparmor_socket_accept,
++	.socket_sendmsg =		apparmor_socket_sendmsg,
++	.socket_recvmsg =		apparmor_socket_recvmsg,
++	.socket_getsockname =		apparmor_socket_getsockname,
++	.socket_getpeername =		apparmor_socket_getpeername,
++	.socket_getsockopt =		apparmor_socket_getsockopt,
++	.socket_setsockopt =		apparmor_socket_setsockopt,
++	.socket_shutdown =		apparmor_socket_shutdown,
++
+ 	.cred_alloc_blank =		apparmor_cred_alloc_blank,
+ 	.cred_free =			apparmor_cred_free,
+ 	.cred_prepare =			apparmor_cred_prepare,
+diff --git a/security/apparmor/net.c b/security/apparmor/net.c
+new file mode 100644
+index 0000000..084232b
+--- /dev/null
++++ b/security/apparmor/net.c
+@@ -0,0 +1,162 @@
++/*
++ * AppArmor security module
++ *
++ * This file contains AppArmor network mediation
++ *
++ * Copyright (C) 1998-2008 Novell/SUSE
++ * Copyright 2009-2012 Canonical Ltd.
++ *
++ * 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, version 2 of the
++ * License.
++ */
++
++#include "include/apparmor.h"
++#include "include/audit.h"
++#include "include/context.h"
++#include "include/net.h"
++#include "include/policy.h"
++
++#include "net_names.h"
++
++struct aa_fs_entry aa_fs_entry_network[] = {
++	AA_FS_FILE_STRING("af_mask", AA_FS_AF_MASK),
++	{ }
++};
++
++/* audit callback for net specific fields */
++static void audit_cb(struct audit_buffer *ab, void *va)
++{
++	struct common_audit_data *sa = va;
++
++	audit_log_format(ab, " family=");
++	if (address_family_names[sa->u.net->family]) {
++		audit_log_string(ab, address_family_names[sa->u.net->family]);
++	} else {
++		audit_log_format(ab, "\"unknown(%d)\"", sa->u.net->family);
++	}
++	audit_log_format(ab, " sock_type=");
++	if (sock_type_names[sa->aad->net.type]) {
++		audit_log_string(ab, sock_type_names[sa->aad->net.type]);
++	} else {
++		audit_log_format(ab, "\"unknown(%d)\"", sa->aad->net.type);
++	}
++	audit_log_format(ab, " protocol=%d", sa->aad->net.protocol);
++}
++
++/**
++ * audit_net - audit network access
++ * @profile: profile being enforced  (NOT NULL)
++ * @op: operation being checked
++ * @family: network family
++ * @type:   network type
++ * @protocol: network protocol
++ * @sk: socket auditing is being applied to
++ * @error: error code for failure else 0
++ *
++ * Returns: %0 or sa->error else other errorcode on failure
++ */
++static int audit_net(struct aa_profile *profile, int op, u16 family, int type,
++		     int protocol, struct sock *sk, int error)
++{
++	int audit_type = AUDIT_APPARMOR_AUTO;
++	struct common_audit_data sa;
++	struct apparmor_audit_data aad = { };
++	struct lsm_network_audit net = { };
++	if (sk) {
++		COMMON_AUDIT_DATA_INIT(&sa, NET);
++	} else {
++		COMMON_AUDIT_DATA_INIT(&sa, NONE);
++	}
++	/* todo fill in socket addr info */
++	sa.aad = &aad;
++	sa.u.net = &net;
++	sa.aad->op = op,
++	sa.u.net->family = family;
++	sa.u.net->sk = sk;
++	sa.aad->net.type = type;
++	sa.aad->net.protocol = protocol;
++	sa.aad->error = error;
++
++	if (likely(!sa.aad->error)) {
++		u16 audit_mask = profile->net.audit[sa.u.net->family];
++		if (likely((AUDIT_MODE(profile) != AUDIT_ALL) &&
++			   !(1 << sa.aad->net.type & audit_mask)))
++			return 0;
++		audit_type = AUDIT_APPARMOR_AUDIT;
++	} else {
++		u16 quiet_mask = profile->net.quiet[sa.u.net->family];
++		u16 kill_mask = 0;
++		u16 denied = (1 << sa.aad->net.type) & ~quiet_mask;
++
++		if (denied & kill_mask)
++			audit_type = AUDIT_APPARMOR_KILL;
++
++		if ((denied & quiet_mask) &&
++		    AUDIT_MODE(profile) != AUDIT_NOQUIET &&
++		    AUDIT_MODE(profile) != AUDIT_ALL)
++			return COMPLAIN_MODE(profile) ? 0 : sa.aad->error;
++	}
++
++	return aa_audit(audit_type, profile, GFP_KERNEL, &sa, audit_cb);
++}
++
++/**
++ * aa_net_perm - very course network access check
++ * @op: operation being checked
++ * @profile: profile being enforced  (NOT NULL)
++ * @family: network family
++ * @type:   network type
++ * @protocol: network protocol
++ *
++ * Returns: %0 else error if permission denied
++ */
++int aa_net_perm(int op, struct aa_profile *profile, u16 family, int type,
++		int protocol, struct sock *sk)
++{
++	u16 family_mask;
++	int error;
++
++	if ((family < 0) || (family >= AF_MAX))
++		return -EINVAL;
++
++	if ((type < 0) || (type >= SOCK_MAX))
++		return -EINVAL;
++
++	/* unix domain and netlink sockets are handled by ipc */
++	if (family == AF_UNIX || family == AF_NETLINK)
++		return 0;
++
++	family_mask = profile->net.allow[family];
++
++	error = (family_mask & (1 << type)) ? 0 : -EACCES;
++
++	return audit_net(profile, op, family, type, protocol, sk, error);
++}
++
++/**
++ * aa_revalidate_sk - Revalidate access to a sock
++ * @op: operation being checked
++ * @sk: sock being revalidated  (NOT NULL)
++ *
++ * Returns: %0 else error if permission denied
++ */
++int aa_revalidate_sk(int op, struct sock *sk)
++{
++	struct aa_profile *profile;
++	int error = 0;
++
++	/* aa_revalidate_sk should not be called from interrupt context
++	 * don't mediate these calls as they are not task related
++	 */
++	if (in_interrupt())
++		return 0;
++
++	profile = __aa_current_profile();
++	if (!unconfined(profile))
++		error = aa_net_perm(op, profile, sk->sk_family, sk->sk_type,
++				    sk->sk_protocol, sk);
++
++	return error;
++}
+diff --git a/security/apparmor/policy.c b/security/apparmor/policy.c
+index f1f7506..b8100a7 100644
+--- a/security/apparmor/policy.c
++++ b/security/apparmor/policy.c
+@@ -745,6 +745,7 @@ static void free_profile(struct aa_profile *profile)
+ 
+ 	aa_free_file_rules(&profile->file);
+ 	aa_free_cap_rules(&profile->caps);
++	aa_free_net_rules(&profile->net);
+ 	aa_free_rlimit_rules(&profile->rlimits);
+ 
+ 	aa_free_sid(profile->sid);
+diff --git a/security/apparmor/policy_unpack.c b/security/apparmor/policy_unpack.c
+index deab7c7..8f8e9c1 100644
+--- a/security/apparmor/policy_unpack.c
++++ b/security/apparmor/policy_unpack.c
+@@ -193,6 +193,19 @@ fail:
+ 	return 0;
+ }
+ 
++static bool unpack_u16(struct aa_ext *e, u16 *data, const char *name)
++{
++	if (unpack_nameX(e, AA_U16, name)) {
++		if (!inbounds(e, sizeof(u16)))
++			return 0;
++		if (data)
++			*data = le16_to_cpu(get_unaligned((u16 *) e->pos));
++		e->pos += sizeof(u16);
++		return 1;
++	}
++	return 0;
++}
++
+ static bool unpack_u32(struct aa_ext *e, u32 *data, const char *name)
+ {
+ 	if (unpack_nameX(e, AA_U32, name)) {
+@@ -471,6 +484,7 @@ static struct aa_profile *unpack_profile(struct aa_ext *e)
+ {
+ 	struct aa_profile *profile = NULL;
+ 	const char *name = NULL;
++	size_t size = 0;
+ 	int i, error = -EPROTO;
+ 	kernel_cap_t tmpcap;
+ 	u32 tmp;
+@@ -564,6 +578,38 @@ static struct aa_profile *unpack_profile(struct aa_ext *e)
+ 	if (!unpack_rlimits(e, profile))
+ 		goto fail;
+ 
++	size = unpack_array(e, "net_allowed_af");
++	if (size) {
++
++		for (i = 0; i < size; i++) {
++			/* discard extraneous rules that this kernel will
++			 * never request
++			 */
++			if (i >= AF_MAX) {
++				u16 tmp;
++				if (!unpack_u16(e, &tmp, NULL) ||
++				    !unpack_u16(e, &tmp, NULL) ||
++				    !unpack_u16(e, &tmp, NULL))
++					goto fail;
++				continue;
++			}
++			if (!unpack_u16(e, &profile->net.allow[i], NULL))
++				goto fail;
++			if (!unpack_u16(e, &profile->net.audit[i], NULL))
++				goto fail;
++			if (!unpack_u16(e, &profile->net.quiet[i], NULL))
++				goto fail;
++		}
++		if (!unpack_nameX(e, AA_ARRAYEND, NULL))
++			goto fail;
++	}
++	/*
++	 * allow unix domain and netlink sockets they are handled
++	 * by IPC
++	 */
++	profile->net.allow[AF_UNIX] = 0xffff;
++	profile->net.allow[AF_NETLINK] = 0xffff;
++
+ 	if (unpack_nameX(e, AA_STRUCT, "policydb")) {
+ 		/* generic policy dfa - optional and may be NULL */
+ 		profile->policy.dfa = unpack_dfa(e);
+-- 
+1.7.9.5
+
diff --git a/pkgs/os-specific/linux/kernel/apparmor-patches/3.4/0003-UBUNTU-SAUCE-apparmor-Add-the-ability-to-mediate-mou.patch b/pkgs/os-specific/linux/kernel/apparmor-patches/3.4/0003-UBUNTU-SAUCE-apparmor-Add-the-ability-to-mediate-mou.patch
new file mode 100644
index 00000000000..48b34343e0b
--- /dev/null
+++ b/pkgs/os-specific/linux/kernel/apparmor-patches/3.4/0003-UBUNTU-SAUCE-apparmor-Add-the-ability-to-mediate-mou.patch
@@ -0,0 +1,957 @@
+From a94d5e11c0484af59e5feebf144cc48c186892ad Mon Sep 17 00:00:00 2001
+From: John Johansen <john.johansen@canonical.com>
+Date: Wed, 16 May 2012 10:58:05 -0700
+Subject: [PATCH 3/3] UBUNTU: SAUCE: apparmor: Add the ability to mediate
+ mount
+
+Add the ability for apparmor to do mediation of mount operations. Mount
+rules require an updated apparmor_parser (2.8 series) for policy compilation.
+
+The basic form of the rules are.
+
+  [audit] [deny] mount [conds]* [device] [ -> [conds] path],
+  [audit] [deny] remount [conds]* [path],
+  [audit] [deny] umount [conds]* [path],
+  [audit] [deny] pivotroot [oldroot=<value>] <path>
+
+  remount is just a short cut for mount options=remount
+
+  where [conds] can be
+    fstype=<expr>
+    options=<expr>
+
+Example mount commands
+  mount,		# allow all mounts, but not umount or pivotroot
+
+  mount fstype=procfs,  # allow mounting procfs anywhere
+
+  mount options=(bind, ro) /foo -> /bar,  # readonly bind mount
+
+  mount /dev/sda -> /mnt,
+
+  mount /dev/sd** -> /mnt/**,
+
+  mount fstype=overlayfs options=(rw,upperdir=/tmp/upper/,lowerdir=/) -> /mnt/
+
+  umount,
+
+  umount /m*,
+
+See the apparmor userspace for full documentation
+
+Signed-off-by: John Johansen <john.johansen@canonical.com>
+Acked-by: Kees Cook <kees@ubuntu.com>
+---
+ security/apparmor/Makefile           |    2 +-
+ security/apparmor/apparmorfs.c       |   13 +
+ security/apparmor/audit.c            |    4 +
+ security/apparmor/domain.c           |    2 +-
+ security/apparmor/include/apparmor.h |    3 +-
+ security/apparmor/include/audit.h    |   11 +
+ security/apparmor/include/domain.h   |    2 +
+ security/apparmor/include/mount.h    |   54 +++
+ security/apparmor/lsm.c              |   59 ++++
+ security/apparmor/mount.c            |  620 ++++++++++++++++++++++++++++++++++
+ 10 files changed, 767 insertions(+), 3 deletions(-)
+ create mode 100644 security/apparmor/include/mount.h
+ create mode 100644 security/apparmor/mount.c
+
+diff --git a/security/apparmor/Makefile b/security/apparmor/Makefile
+index 19daa85..63e0a4c 100644
+--- a/security/apparmor/Makefile
++++ b/security/apparmor/Makefile
+@@ -4,7 +4,7 @@ obj-$(CONFIG_SECURITY_APPARMOR) += apparmor.o
+ 
+ apparmor-y := apparmorfs.o audit.o capability.o context.o ipc.o lib.o match.o \
+               path.o domain.o policy.o policy_unpack.o procattr.o lsm.o \
+-              resource.o sid.o file.o net.o
++              resource.o sid.o file.o net.o mount.o
+ 
+ clean-files := capability_names.h rlim_names.h net_names.h
+ 
+diff --git a/security/apparmor/apparmorfs.c b/security/apparmor/apparmorfs.c
+index c66315d..ff19009 100644
+--- a/security/apparmor/apparmorfs.c
++++ b/security/apparmor/apparmorfs.c
+@@ -424,10 +424,23 @@ static struct aa_fs_entry aa_fs_entry_domain[] = {
+ 	{ }
+ };
+ 
++static struct aa_fs_entry aa_fs_entry_mount[] = {
++	AA_FS_FILE_STRING("mask", "mount umount"),
++	{ }
++};
++
++static struct aa_fs_entry aa_fs_entry_namespaces[] = {
++	AA_FS_FILE_BOOLEAN("profile",           1),
++	AA_FS_FILE_BOOLEAN("pivot_root",        1),
++	{ }
++};
++
+ static struct aa_fs_entry aa_fs_entry_features[] = {
+ 	AA_FS_DIR("domain",			aa_fs_entry_domain),
+ 	AA_FS_DIR("file",			aa_fs_entry_file),
+ 	AA_FS_DIR("network",                    aa_fs_entry_network),
++	AA_FS_DIR("mount",                      aa_fs_entry_mount),
++	AA_FS_DIR("namespaces",                 aa_fs_entry_namespaces),
+ 	AA_FS_FILE_U64("capability",		VFS_CAP_FLAGS_MASK),
+ 	AA_FS_DIR("rlimit",			aa_fs_entry_rlimit),
+ 	{ }
+diff --git a/security/apparmor/audit.c b/security/apparmor/audit.c
+index cc3520d..b9f5ee9 100644
+--- a/security/apparmor/audit.c
++++ b/security/apparmor/audit.c
+@@ -44,6 +44,10 @@ const char *const op_table[] = {
+ 	"file_mmap",
+ 	"file_mprotect",
+ 
++	"pivotroot",
++	"mount",
++	"umount",
++
+ 	"create",
+ 	"post_create",
+ 	"bind",
+diff --git a/security/apparmor/domain.c b/security/apparmor/domain.c
+index 6327685..dfdc47b 100644
+--- a/security/apparmor/domain.c
++++ b/security/apparmor/domain.c
+@@ -242,7 +242,7 @@ static const char *next_name(int xtype, const char *name)
+  *
+  * Returns: refcounted profile, or NULL on failure (MAYBE NULL)
+  */
+-static struct aa_profile *x_table_lookup(struct aa_profile *profile, u32 xindex)
++struct aa_profile *x_table_lookup(struct aa_profile *profile, u32 xindex)
+ {
+ 	struct aa_profile *new_profile = NULL;
+ 	struct aa_namespace *ns = profile->ns;
+diff --git a/security/apparmor/include/apparmor.h b/security/apparmor/include/apparmor.h
+index 40aedd9..e243d96 100644
+--- a/security/apparmor/include/apparmor.h
++++ b/security/apparmor/include/apparmor.h
+@@ -29,8 +29,9 @@
+ #define AA_CLASS_NET		4
+ #define AA_CLASS_RLIMITS	5
+ #define AA_CLASS_DOMAIN		6
++#define AA_CLASS_MOUNT		7
+ 
+-#define AA_CLASS_LAST		AA_CLASS_DOMAIN
++#define AA_CLASS_LAST		AA_CLASS_MOUNT
+ 
+ /* Control parameters settable through module/boot flags */
+ extern enum audit_mode aa_g_audit;
+diff --git a/security/apparmor/include/audit.h b/security/apparmor/include/audit.h
+index c1ff09c..7b90900c 100644
+--- a/security/apparmor/include/audit.h
++++ b/security/apparmor/include/audit.h
+@@ -73,6 +73,10 @@ enum aa_ops {
+ 	OP_FMMAP,
+ 	OP_FMPROT,
+ 
++	OP_PIVOTROOT,
++	OP_MOUNT,
++	OP_UMOUNT,
++
+ 	OP_CREATE,
+ 	OP_POST_CREATE,
+ 	OP_BIND,
+@@ -121,6 +125,13 @@ struct apparmor_audit_data {
+ 			unsigned long max;
+ 		} rlim;
+ 		struct {
++			const char *src_name;
++			const char *type;
++			const char *trans;
++			const char *data;
++			unsigned long flags;
++		} mnt;
++		struct {
+ 			const char *target;
+ 			u32 request;
+ 			u32 denied;
+diff --git a/security/apparmor/include/domain.h b/security/apparmor/include/domain.h
+index de04464..a3f70c5 100644
+--- a/security/apparmor/include/domain.h
++++ b/security/apparmor/include/domain.h
+@@ -23,6 +23,8 @@ struct aa_domain {
+ 	char **table;
+ };
+ 
++struct aa_profile *x_table_lookup(struct aa_profile *profile, u32 xindex);
++
+ int apparmor_bprm_set_creds(struct linux_binprm *bprm);
+ int apparmor_bprm_secureexec(struct linux_binprm *bprm);
+ void apparmor_bprm_committing_creds(struct linux_binprm *bprm);
+diff --git a/security/apparmor/include/mount.h b/security/apparmor/include/mount.h
+new file mode 100644
+index 0000000..bc17a53
+--- /dev/null
++++ b/security/apparmor/include/mount.h
+@@ -0,0 +1,54 @@
++/*
++ * AppArmor security module
++ *
++ * This file contains AppArmor file mediation function definitions.
++ *
++ * Copyright 2012 Canonical Ltd.
++ *
++ * 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, version 2 of the
++ * License.
++ */
++
++#ifndef __AA_MOUNT_H
++#define __AA_MOUNT_H
++
++#include <linux/fs.h>
++#include <linux/path.h>
++
++#include "domain.h"
++#include "policy.h"
++
++/* mount perms */
++#define AA_MAY_PIVOTROOT	0x01
++#define AA_MAY_MOUNT		0x02
++#define AA_MAY_UMOUNT		0x04
++#define AA_AUDIT_DATA		0x40
++#define AA_CONT_MATCH		0x40
++
++#define AA_MS_IGNORE_MASK (MS_KERNMOUNT | MS_NOSEC | MS_ACTIVE | MS_BORN)
++
++int aa_remount(struct aa_profile *profile, struct path *path,
++	       unsigned long flags, void *data);
++
++int aa_bind_mount(struct aa_profile *profile, struct path *path,
++		  const char *old_name, unsigned long flags);
++
++
++int aa_mount_change_type(struct aa_profile *profile, struct path *path,
++			 unsigned long flags);
++
++int aa_move_mount(struct aa_profile *profile, struct path *path,
++		  const char *old_name);
++
++int aa_new_mount(struct aa_profile *profile, const char *dev_name,
++		 struct path *path, const char *type, unsigned long flags,
++		 void *data);
++
++int aa_umount(struct aa_profile *profile, struct vfsmount *mnt, int flags);
++
++int aa_pivotroot(struct aa_profile *profile, struct path *old_path,
++		  struct path *new_path);
++
++#endif /* __AA_MOUNT_H */
+diff --git a/security/apparmor/lsm.c b/security/apparmor/lsm.c
+index 3cde194..4512cc6 100644
+--- a/security/apparmor/lsm.c
++++ b/security/apparmor/lsm.c
+@@ -36,6 +36,7 @@
+ #include "include/path.h"
+ #include "include/policy.h"
+ #include "include/procattr.h"
++#include "include/mount.h"
+ 
+ /* Flag indicating whether initialization completed */
+ int apparmor_initialized __initdata;
+@@ -512,6 +513,60 @@ static int apparmor_file_mprotect(struct vm_area_struct *vma,
+ 			   !(vma->vm_flags & VM_SHARED) ? MAP_PRIVATE : 0);
+ }
+ 
++static int apparmor_sb_mount(char *dev_name, struct path *path, char *type,
++			     unsigned long flags, void *data)
++{
++	struct aa_profile *profile;
++	int error = 0;
++
++	/* Discard magic */
++	if ((flags & MS_MGC_MSK) == MS_MGC_VAL)
++		flags &= ~MS_MGC_MSK;
++
++	flags &= ~AA_MS_IGNORE_MASK;
++
++	profile = __aa_current_profile();
++	if (!unconfined(profile)) {
++		if (flags & MS_REMOUNT)
++			error = aa_remount(profile, path, flags, data);
++		else if (flags & MS_BIND)
++			error = aa_bind_mount(profile, path, dev_name, flags);
++		else if (flags & (MS_SHARED | MS_PRIVATE | MS_SLAVE |
++				  MS_UNBINDABLE))
++			error = aa_mount_change_type(profile, path, flags);
++		else if (flags & MS_MOVE)
++			error = aa_move_mount(profile, path, dev_name);
++		else
++			error = aa_new_mount(profile, dev_name, path, type,
++					     flags, data);
++	}
++	return error;
++}
++
++static int apparmor_sb_umount(struct vfsmount *mnt, int flags)
++{
++	struct aa_profile *profile;
++	int error = 0;
++
++	profile = __aa_current_profile();
++	if (!unconfined(profile))
++		error = aa_umount(profile, mnt, flags);
++
++	return error;
++}
++
++static int apparmor_sb_pivotroot(struct path *old_path, struct path *new_path)
++{
++	struct aa_profile *profile;
++	int error = 0;
++
++	profile = __aa_current_profile();
++	if (!unconfined(profile))
++		error = aa_pivotroot(profile, old_path, new_path);
++
++	return error;
++}
++
+ static int apparmor_getprocattr(struct task_struct *task, char *name,
+ 				char **value)
+ {
+@@ -729,6 +784,10 @@ static struct security_operations apparmor_ops = {
+ 	.capget =			apparmor_capget,
+ 	.capable =			apparmor_capable,
+ 
++	.sb_mount =			apparmor_sb_mount,
++	.sb_umount =			apparmor_sb_umount,
++	.sb_pivotroot =			apparmor_sb_pivotroot,
++
+ 	.path_link =			apparmor_path_link,
+ 	.path_unlink =			apparmor_path_unlink,
+ 	.path_symlink =			apparmor_path_symlink,
+diff --git a/security/apparmor/mount.c b/security/apparmor/mount.c
+new file mode 100644
+index 0000000..63d8493
+--- /dev/null
++++ b/security/apparmor/mount.c
+@@ -0,0 +1,620 @@
++/*
++ * AppArmor security module
++ *
++ * This file contains AppArmor mediation of files
++ *
++ * Copyright (C) 1998-2008 Novell/SUSE
++ * Copyright 2009-2012 Canonical Ltd.
++ *
++ * 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, version 2 of the
++ * License.
++ */
++
++#include <linux/fs.h>
++#include <linux/mount.h>
++#include <linux/namei.h>
++
++#include "include/apparmor.h"
++#include "include/audit.h"
++#include "include/context.h"
++#include "include/domain.h"
++#include "include/file.h"
++#include "include/match.h"
++#include "include/mount.h"
++#include "include/path.h"
++#include "include/policy.h"
++
++
++static void audit_mnt_flags(struct audit_buffer *ab, unsigned long flags)
++{
++	if (flags & MS_RDONLY)
++		audit_log_format(ab, "ro");
++	else
++		audit_log_format(ab, "rw");
++	if (flags & MS_NOSUID)
++		audit_log_format(ab, ", nosuid");
++	if (flags & MS_NODEV)
++		audit_log_format(ab, ", nodev");
++	if (flags & MS_NOEXEC)
++		audit_log_format(ab, ", noexec");
++	if (flags & MS_SYNCHRONOUS)
++		audit_log_format(ab, ", sync");
++	if (flags & MS_REMOUNT)
++		audit_log_format(ab, ", remount");
++	if (flags & MS_MANDLOCK)
++		audit_log_format(ab, ", mand");
++	if (flags & MS_DIRSYNC)
++		audit_log_format(ab, ", dirsync");
++	if (flags & MS_NOATIME)
++		audit_log_format(ab, ", noatime");
++	if (flags & MS_NODIRATIME)
++		audit_log_format(ab, ", nodiratime");
++	if (flags & MS_BIND)
++		audit_log_format(ab, flags & MS_REC ? ", rbind" : ", bind");
++	if (flags & MS_MOVE)
++		audit_log_format(ab, ", move");
++	if (flags & MS_SILENT)
++		audit_log_format(ab, ", silent");
++	if (flags & MS_POSIXACL)
++		audit_log_format(ab, ", acl");
++	if (flags & MS_UNBINDABLE)
++		audit_log_format(ab, flags & MS_REC ? ", runbindable" :
++				 ", unbindable");
++	if (flags & MS_PRIVATE)
++		audit_log_format(ab, flags & MS_REC ? ", rprivate" :
++				 ", private");
++	if (flags & MS_SLAVE)
++		audit_log_format(ab, flags & MS_REC ? ", rslave" :
++				 ", slave");
++	if (flags & MS_SHARED)
++		audit_log_format(ab, flags & MS_REC ? ", rshared" :
++				 ", shared");
++	if (flags & MS_RELATIME)
++		audit_log_format(ab, ", relatime");
++	if (flags & MS_I_VERSION)
++		audit_log_format(ab, ", iversion");
++	if (flags & MS_STRICTATIME)
++		audit_log_format(ab, ", strictatime");
++	if (flags & MS_NOUSER)
++		audit_log_format(ab, ", nouser");
++}
++
++/**
++ * audit_cb - call back for mount specific audit fields
++ * @ab: audit_buffer  (NOT NULL)
++ * @va: audit struct to audit values of  (NOT NULL)
++ */
++static void audit_cb(struct audit_buffer *ab, void *va)
++{
++	struct common_audit_data *sa = va;
++
++	if (sa->aad->mnt.type) {
++		audit_log_format(ab, " fstype=");
++		audit_log_untrustedstring(ab, sa->aad->mnt.type);
++	}
++	if (sa->aad->mnt.src_name) {
++		audit_log_format(ab, " srcname=");
++		audit_log_untrustedstring(ab, sa->aad->mnt.src_name);
++	}
++	if (sa->aad->mnt.trans) {
++		audit_log_format(ab, " trans=");
++		audit_log_untrustedstring(ab, sa->aad->mnt.trans);
++	}
++	if (sa->aad->mnt.flags || sa->aad->op == OP_MOUNT) {
++		audit_log_format(ab, " flags=\"");
++		audit_mnt_flags(ab, sa->aad->mnt.flags);
++		audit_log_format(ab, "\"");
++	}
++	if (sa->aad->mnt.data) {
++		audit_log_format(ab, " options=");
++		audit_log_untrustedstring(ab, sa->aad->mnt.data);
++	}
++}
++
++/**
++ * audit_mount - handle the auditing of mount operations
++ * @profile: the profile being enforced  (NOT NULL)
++ * @gfp: allocation flags
++ * @op: operation being mediated (NOT NULL)
++ * @name: name of object being mediated (MAYBE NULL)
++ * @src_name: src_name of object being mediated (MAYBE_NULL)
++ * @type: type of filesystem (MAYBE_NULL)
++ * @trans: name of trans (MAYBE NULL)
++ * @flags: filesystem idependent mount flags
++ * @data: filesystem mount flags
++ * @request: permissions requested
++ * @perms: the permissions computed for the request (NOT NULL)
++ * @info: extra information message (MAYBE NULL)
++ * @error: 0 if operation allowed else failure error code
++ *
++ * Returns: %0 or error on failure
++ */
++static int audit_mount(struct aa_profile *profile, gfp_t gfp, int op,
++		       const char *name, const char *src_name,
++		       const char *type, const char *trans,
++		       unsigned long flags, const void *data, u32 request,
++		       struct file_perms *perms, const char *info, int error)
++{
++	int audit_type = AUDIT_APPARMOR_AUTO;
++	struct common_audit_data sa;
++	struct apparmor_audit_data aad = { };
++
++	if (likely(!error)) {
++		u32 mask = perms->audit;
++
++		if (unlikely(AUDIT_MODE(profile) == AUDIT_ALL))
++			mask = 0xffff;
++
++		/* mask off perms that are not being force audited */
++		request &= mask;
++
++		if (likely(!request))
++			return 0;
++		audit_type = AUDIT_APPARMOR_AUDIT;
++	} else {
++		/* only report permissions that were denied */
++		request = request & ~perms->allow;
++
++		if (request & perms->kill)
++			audit_type = AUDIT_APPARMOR_KILL;
++
++		/* quiet known rejects, assumes quiet and kill do not overlap */
++		if ((request & perms->quiet) &&
++		    AUDIT_MODE(profile) != AUDIT_NOQUIET &&
++		    AUDIT_MODE(profile) != AUDIT_ALL)
++			request &= ~perms->quiet;
++
++		if (!request)
++			return COMPLAIN_MODE(profile) ?
++				complain_error(error) : error;
++	}
++
++	COMMON_AUDIT_DATA_INIT(&sa, NONE);
++	sa.aad = &aad;
++	sa.aad->op = op;
++	sa.aad->name = name;
++	sa.aad->mnt.src_name = src_name;
++	sa.aad->mnt.type = type;
++	sa.aad->mnt.trans = trans;
++	sa.aad->mnt.flags = flags;
++	if (data && (perms->audit & AA_AUDIT_DATA))
++		sa.aad->mnt.data = data;
++	sa.aad->info = info;
++	sa.aad->error = error;
++
++	return aa_audit(audit_type, profile, gfp, &sa, audit_cb);
++}
++
++/**
++ * match_mnt_flags - Do an ordered match on mount flags
++ * @dfa: dfa to match against
++ * @state: state to start in
++ * @flags: mount flags to match against
++ *
++ * Mount flags are encoded as an ordered match. This is done instead of
++ * checking against a simple bitmask, to allow for logical operations
++ * on the flags.
++ *
++ * Returns: next state after flags match
++ */
++static unsigned int match_mnt_flags(struct aa_dfa *dfa, unsigned int state,
++				    unsigned long flags)
++{
++	unsigned int i;
++
++	for (i = 0; i <= 31 ; ++i) {
++		if ((1 << i) & flags)
++			state = aa_dfa_next(dfa, state, i + 1);
++	}
++
++	return state;
++}
++
++/**
++ * compute_mnt_perms - compute mount permission associated with @state
++ * @dfa: dfa to match against (NOT NULL)
++ * @state: state match finished in
++ *
++ * Returns: mount permissions
++ */
++static struct file_perms compute_mnt_perms(struct aa_dfa *dfa,
++					   unsigned int state)
++{
++	struct file_perms perms;
++
++	perms.kill = 0;
++	perms.allow = dfa_user_allow(dfa, state);
++	perms.audit = dfa_user_audit(dfa, state);
++	perms.quiet = dfa_user_quiet(dfa, state);
++	perms.xindex = dfa_user_xindex(dfa, state);
++
++	return perms;
++}
++
++static const char const *mnt_info_table[] = {
++	"match succeeded",
++	"failed mntpnt match",
++	"failed srcname match",
++	"failed type match",
++	"failed flags match",
++	"failed data match"
++};
++
++/*
++ * Returns 0 on success else element that match failed in, this is the
++ * index into the mnt_info_table above
++ */
++static int do_match_mnt(struct aa_dfa *dfa, unsigned int start,
++			const char *mntpnt, const char *devname,
++			const char *type, unsigned long flags,
++			void *data, bool binary, struct file_perms *perms)
++{
++	unsigned int state;
++
++	state = aa_dfa_match(dfa, start, mntpnt);
++	state = aa_dfa_null_transition(dfa, state);
++	if (!state)
++		return 1;
++
++	if (devname)
++		state = aa_dfa_match(dfa, state, devname);
++	state = aa_dfa_null_transition(dfa, state);
++	if (!state)
++		return 2;
++
++	if (type)
++		state = aa_dfa_match(dfa, state, type);
++	state = aa_dfa_null_transition(dfa, state);
++	if (!state)
++		return 3;
++
++	state = match_mnt_flags(dfa, state, flags);
++	if (!state)
++		return 4;
++	*perms = compute_mnt_perms(dfa, state);
++	if (perms->allow & AA_MAY_MOUNT)
++		return 0;
++
++	/* only match data if not binary and the DFA flags data is expected */
++	if (data && !binary && (perms->allow & AA_CONT_MATCH)) {
++		state = aa_dfa_null_transition(dfa, state);
++		if (!state)
++			return 4;
++
++		state = aa_dfa_match(dfa, state, data);
++		if (!state)
++			return 5;
++		*perms = compute_mnt_perms(dfa, state);
++		if (perms->allow & AA_MAY_MOUNT)
++			return 0;
++	}
++
++	/* failed at end of flags match */
++	return 4;
++}
++
++/**
++ * match_mnt - handle path matching for mount
++ * @profile: the confining profile
++ * @mntpnt: string for the mntpnt (NOT NULL)
++ * @devname: string for the devname/src_name (MAYBE NULL)
++ * @type: string for the dev type (MAYBE NULL)
++ * @flags: mount flags to match
++ * @data: fs mount data (MAYBE NULL)
++ * @binary: whether @data is binary
++ * @perms: Returns: permission found by the match
++ * @info: Returns: infomation string about the match for logging
++ *
++ * Returns: 0 on success else error
++ */
++static int match_mnt(struct aa_profile *profile, const char *mntpnt,
++		     const char *devname, const char *type,
++		     unsigned long flags, void *data, bool binary,
++		     struct file_perms *perms, const char **info)
++{
++	int pos;
++
++	if (!profile->policy.dfa)
++		return -EACCES;
++
++	pos = do_match_mnt(profile->policy.dfa,
++			   profile->policy.start[AA_CLASS_MOUNT],
++			   mntpnt, devname, type, flags, data, binary, perms);
++	if (pos) {
++		*info = mnt_info_table[pos];
++		return -EACCES;
++	}
++
++	return 0;
++}
++
++static int path_flags(struct aa_profile *profile, struct path *path)
++{
++	return profile->path_flags |
++		S_ISDIR(path->dentry->d_inode->i_mode) ? PATH_IS_DIR : 0;
++}
++
++int aa_remount(struct aa_profile *profile, struct path *path,
++	       unsigned long flags, void *data)
++{
++	struct file_perms perms = { };
++	const char *name, *info = NULL;
++	char *buffer = NULL;
++	int binary, error;
++
++	binary = path->dentry->d_sb->s_type->fs_flags & FS_BINARY_MOUNTDATA;
++
++	error = aa_path_name(path, path_flags(profile, path), &buffer, &name,
++			     &info);
++	if (error)
++		goto audit;
++
++	error = match_mnt(profile, name, NULL, NULL, flags, data, binary,
++			  &perms, &info);
++
++audit:
++	error = audit_mount(profile, GFP_KERNEL, OP_MOUNT, name, NULL, NULL,
++			    NULL, flags, data, AA_MAY_MOUNT, &perms, info,
++			    error);
++	kfree(buffer);
++
++	return error;
++}
++
++int aa_bind_mount(struct aa_profile *profile, struct path *path,
++		  const char *dev_name, unsigned long flags)
++{
++	struct file_perms perms = { };
++	char *buffer = NULL, *old_buffer = NULL;
++	const char *name, *old_name = NULL, *info = NULL;
++	struct path old_path;
++	int error;
++
++	if (!dev_name || !*dev_name)
++		return -EINVAL;
++
++	flags &= MS_REC | MS_BIND;
++
++	error = aa_path_name(path, path_flags(profile, path), &buffer, &name,
++			     &info);
++	if (error)
++		goto audit;
++
++	error = kern_path(dev_name, LOOKUP_FOLLOW|LOOKUP_AUTOMOUNT, &old_path);
++	if (error)
++		goto audit;
++
++	error = aa_path_name(&old_path, path_flags(profile, &old_path),
++			     &old_buffer, &old_name, &info);
++	path_put(&old_path);
++	if (error)
++		goto audit;
++
++	error = match_mnt(profile, name, old_name, NULL, flags, NULL, 0,
++			  &perms, &info);
++
++audit:
++	error = audit_mount(profile, GFP_KERNEL, OP_MOUNT, name, old_name,
++			    NULL, NULL, flags, NULL, AA_MAY_MOUNT, &perms,
++			    info, error);
++	kfree(buffer);
++	kfree(old_buffer);
++
++	return error;
++}
++
++int aa_mount_change_type(struct aa_profile *profile, struct path *path,
++			 unsigned long flags)
++{
++	struct file_perms perms = { };
++	char *buffer = NULL;
++	const char *name, *info = NULL;
++	int error;
++
++	/* These are the flags allowed by do_change_type() */
++	flags &= (MS_REC | MS_SILENT | MS_SHARED | MS_PRIVATE | MS_SLAVE |
++		  MS_UNBINDABLE);
++
++	error = aa_path_name(path, path_flags(profile, path), &buffer, &name,
++			     &info);
++	if (error)
++		goto audit;
++
++	error = match_mnt(profile, name, NULL, NULL, flags, NULL, 0, &perms,
++			  &info);
++
++audit:
++	error = audit_mount(profile, GFP_KERNEL, OP_MOUNT, name, NULL, NULL,
++			    NULL, flags, NULL, AA_MAY_MOUNT, &perms, info,
++			    error);
++	kfree(buffer);
++
++	return error;
++}
++
++int aa_move_mount(struct aa_profile *profile, struct path *path,
++		  const char *orig_name)
++{
++	struct file_perms perms = { };
++	char *buffer = NULL, *old_buffer = NULL;
++	const char *name, *old_name = NULL, *info = NULL;
++	struct path old_path;
++	int error;
++
++	if (!orig_name || !*orig_name)
++		return -EINVAL;
++
++	error = aa_path_name(path, path_flags(profile, path), &buffer, &name,
++			     &info);
++	if (error)
++		goto audit;
++
++	error = kern_path(orig_name, LOOKUP_FOLLOW, &old_path);
++	if (error)
++		goto audit;
++
++	error = aa_path_name(&old_path, path_flags(profile, &old_path),
++			     &old_buffer, &old_name, &info);
++	path_put(&old_path);
++	if (error)
++		goto audit;
++
++	error = match_mnt(profile, name, old_name, NULL, MS_MOVE, NULL, 0,
++			  &perms, &info);
++
++audit:
++	error = audit_mount(profile, GFP_KERNEL, OP_MOUNT, name, old_name,
++			    NULL, NULL, MS_MOVE, NULL, AA_MAY_MOUNT, &perms,
++			    info, error);
++	kfree(buffer);
++	kfree(old_buffer);
++
++	return error;
++}
++
++int aa_new_mount(struct aa_profile *profile, const char *orig_dev_name,
++		 struct path *path, const char *type, unsigned long flags,
++		 void *data)
++{
++	struct file_perms perms = { };
++	char *buffer = NULL, *dev_buffer = NULL;
++	const char *name = NULL, *dev_name = NULL, *info = NULL;
++	int binary = 1;
++	int error;
++
++	dev_name = orig_dev_name;
++	if (type) {
++		int requires_dev;
++		struct file_system_type *fstype = get_fs_type(type);
++		if (!fstype)
++			return -ENODEV;
++
++		binary = fstype->fs_flags & FS_BINARY_MOUNTDATA;
++		requires_dev = fstype->fs_flags & FS_REQUIRES_DEV;
++		put_filesystem(fstype);
++
++		if (requires_dev) {
++			struct path dev_path;
++
++			if (!dev_name || !*dev_name) {
++				error = -ENOENT;
++				goto out;
++			}
++
++			error = kern_path(dev_name, LOOKUP_FOLLOW, &dev_path);
++			if (error)
++				goto audit;
++
++			error = aa_path_name(&dev_path,
++					     path_flags(profile, &dev_path),
++					     &dev_buffer, &dev_name, &info);
++			path_put(&dev_path);
++			if (error)
++				goto audit;
++		}
++	}
++
++	error = aa_path_name(path, path_flags(profile, path), &buffer, &name,
++			     &info);
++	if (error)
++		goto audit;
++
++	error = match_mnt(profile, name, dev_name, type, flags, data, binary,
++			  &perms, &info);
++
++audit:
++	error = audit_mount(profile, GFP_KERNEL, OP_MOUNT, name,  dev_name,
++			    type, NULL, flags, data, AA_MAY_MOUNT, &perms, info,
++			    error);
++	kfree(buffer);
++	kfree(dev_buffer);
++
++out:
++	return error;
++
++}
++
++int aa_umount(struct aa_profile *profile, struct vfsmount *mnt, int flags)
++{
++	struct file_perms perms = { };
++	char *buffer = NULL;
++	const char *name, *info = NULL;
++	int error;
++
++	struct path path = { mnt, mnt->mnt_root };
++	error = aa_path_name(&path, path_flags(profile, &path), &buffer, &name,
++			     &info);
++	if (error)
++		goto audit;
++
++	if (!error && profile->policy.dfa) {
++		unsigned int state;
++		state = aa_dfa_match(profile->policy.dfa,
++				     profile->policy.start[AA_CLASS_MOUNT],
++				     name);
++		perms = compute_mnt_perms(profile->policy.dfa, state);
++	}
++
++	if (AA_MAY_UMOUNT & ~perms.allow)
++		error = -EACCES;
++
++audit:
++	error = audit_mount(profile, GFP_KERNEL, OP_UMOUNT, name, NULL, NULL,
++			    NULL, 0, NULL, AA_MAY_UMOUNT, &perms, info, error);
++	kfree(buffer);
++
++	return error;
++}
++
++int aa_pivotroot(struct aa_profile *profile, struct path *old_path,
++		  struct path *new_path)
++{
++	struct file_perms perms = { };
++	struct aa_profile *target = NULL;
++	char *old_buffer = NULL, *new_buffer = NULL;
++	const char *old_name, *new_name = NULL, *info = NULL;
++	int error;
++
++	error = aa_path_name(old_path, path_flags(profile, old_path),
++			     &old_buffer, &old_name, &info);
++	if (error)
++		goto audit;
++
++	error = aa_path_name(new_path, path_flags(profile, new_path),
++			     &new_buffer, &new_name, &info);
++	if (error)
++		goto audit;
++
++	if (profile->policy.dfa) {
++		unsigned int state;
++		state = aa_dfa_match(profile->policy.dfa,
++				     profile->policy.start[AA_CLASS_MOUNT],
++				     new_name);
++		state = aa_dfa_null_transition(profile->policy.dfa, state);
++		state = aa_dfa_match(profile->policy.dfa, state, old_name);
++		perms = compute_mnt_perms(profile->policy.dfa, state);
++	}
++
++	if (AA_MAY_PIVOTROOT & perms.allow) {
++		if ((perms.xindex & AA_X_TYPE_MASK) == AA_X_TABLE) {
++			target = x_table_lookup(profile, perms.xindex);
++			if (!target)
++				error = -ENOENT;
++			else
++				error = aa_replace_current_profile(target);
++		}
++	} else
++		error = -EACCES;
++
++audit:
++	error = audit_mount(profile, GFP_KERNEL, OP_PIVOTROOT, new_name,
++			    old_name, NULL, target ? target->base.name : NULL,
++			    0, NULL,  AA_MAY_PIVOTROOT, &perms, info, error);
++	aa_put_profile(target);
++	kfree(old_buffer);
++	kfree(new_buffer);
++
++	return error;
++}
+-- 
+1.7.9.5
+
diff --git a/pkgs/os-specific/linux/kernel/builder.sh b/pkgs/os-specific/linux/kernel/builder.sh
deleted file mode 100644
index 8fb5e9f91eb..00000000000
--- a/pkgs/os-specific/linux/kernel/builder.sh
+++ /dev/null
@@ -1,149 +0,0 @@
-source $stdenv/setup
-
-
-makeFlags="ARCH=$arch SHELL=/bin/sh KBUILD_BUILD_VERSION=1-NixOS $makeFlags"
-if [ -n "$crossConfig" ]; then
-  makeFlags="$makeFlags CROSS_COMPILE=$crossConfig-"
-fi
-
-postPatch() {
-    # Makefiles are full of /bin/pwd, /bin/false, /bin/bash, etc.
-    # Patch these away, assuming the tools are in $PATH.
-    for mf in $(find -name Makefile); do
-        echo "stripping FHS paths in \`$mf'..."
-        sed -i "$mf" -e 's|/usr/bin/||g ; s|/bin/||g'
-    done
-}
-
-configurePhase() {
-    if test -n "$preConfigure"; then
-        eval "$preConfigure"
-    fi
-
-    export INSTALL_PATH=$out
-    export INSTALL_MOD_PATH=$out
-
-    # Set our own localversion, if specified.
-    rm -f localversion*
-    if test -n "$localVersion"; then
-        echo "$localVersion" > localversion-nix
-    fi
-
-    # Patch kconfig to print "###" after every question so that
-    # generate-config.pl can answer them.
-    sed -e '/fflush(stdout);/i\printf("###");' -i scripts/kconfig/conf.c
-
-    # Get a basic config file for later refinement with $generateConfig.
-    make $kernelBaseConfig ARCH=$arch
-
-    # Create the config file.
-    echo "generating kernel configuration..."
-    echo "$kernelConfig" > kernel-config
-    DEBUG=1 ARCH=$arch KERNEL_CONFIG=kernel-config AUTO_MODULES=$autoModules \
-        perl -w $generateConfig
-}
-
-
-installPhase() {
-
-    mkdir -p $out
-
-    # New kernel versions have a combined tree for i386 and x86_64.
-    archDir=$arch
-    if test -e arch/x86 -a \( "$arch" = i386 -o "$arch" = x86_64 \); then
-        archDir=x86
-    fi
-
-
-    # Copy the bzImage and System.map.
-    cp System.map $out
-    if test "$arch" = um; then
-        mkdir -p $out/bin
-        cp linux $out/bin
-    elif test "$kernelTarget" != "vmlinux"; then
-        # In any case we copy the 'vmlinux' ELF in the next lines
-        cp arch/$archDir/boot/$kernelTarget $out
-    fi
-
-    cp vmlinux $out
-
-    if grep -q "CONFIG_MODULES=y" .config; then
-        # Install the modules in $out/lib/modules.
-        make modules_install \
-            DEPMOD=$kmod/sbin/depmod \
-            $makeFlags "${makeFlagsArray[@]}" \
-            $installFlags "${installFlagsArray[@]}"
-
-        if test -z "$dontStrip"; then
-            # Strip the kernel modules.
-        echo "Stripping kernel modules..."
-        if [ -z "$crossConfig" ]; then
-                find $out -name "*.ko" -print0 | xargs -0 strip -S
-        else
-                find $out -name "*.ko" -print0 | xargs -0 $crossConfig-strip -S
-        fi
-        fi
-
-        # move this to install later on
-        # largely copied from early FC3 kernel spec files
-        version=$(cd $out/lib/modules && ls -d *)
-
-        # remove symlinks and create directories
-        rm -f $out/lib/modules/$version/build
-        rm -f $out/lib/modules/$version/source
-        mkdir $out/lib/modules/$version/build
-
-        # copy config
-        cp .config $out/lib/modules/$version/build/.config
-        ln -s $out/lib/modules/$version/build/.config $out/config
-
-        if test "$arch" != um; then
-            # copy all Makefiles and Kconfig files
-            ln -s $out/lib/modules/$version/build $out/lib/modules/$version/source
-            cp --parents `find  -type f -name Makefile -o -name "Kconfig*"` $out/lib/modules/$version/build
-            cp Module.symvers $out/lib/modules/$version/build
-
-        if test "$dontStrip" = "1"; then
-            # copy any debugging info that can be found
-            cp --parents -rv `find -name \*.debug -o -name debug.a`     \
-               "$out/lib/modules/$version/build"
-        fi
-
-            # weed out unneeded stuff
-            rm -rf $out/lib/modules/$version/build/Documentation
-            rm -rf $out/lib/modules/$version/build/scripts
-            rm -rf $out/lib/modules/$version/build/include
-
-            # copy architecture dependent files
-            cp -a arch/$archDir/scripts $out/lib/modules/$version/build/ || true
-            cp -a arch/$archDir/*lds $out/lib/modules/$version/build/ || true
-            cp -a arch/$archDir/Makefile*.cpu $out/lib/modules/$version/build/arch/$archDir/ || true
-            cp -a --parents arch/$archDir/kernel/asm-offsets.s $out/lib/modules/$version/build/arch/$archDir/kernel/ || true
-
-            # copy scripts
-            rm -f scripts/*.o
-            rm -f scripts/*/*.o
-            cp -a scripts $out/lib/modules/$version/build
-
-            # copy include files
-            includeDir=$out/lib/modules/$version/build/include
-            mkdir -p $includeDir
-            (cd include && cp -a * $includeDir)
-        (cd arch/$archDir/include && cp -a * $includeDir || true)
-        (cd arch/$archDir/include && cp -a asm/* $includeDir/asm/ || true)
-        (cd arch/$archDir/include && cp -a generated/asm/* $includeDir/asm/ || true)
-        (cd arch/$archDir/include/asm/mach-generic && cp -a * $includeDir/ || true)
-            # include files for special arm architectures 
-            if [ "$archDir" == "arm" ]; then
-                cp -a --parents arch/arm/mach-*/include $out/lib/modules/$version/build
-            fi
-        fi
-    fi
-
-    if test -n "$postInstall"; then
-        eval "$postInstall";
-    fi
-}
-
-
-genericBuild
diff --git a/pkgs/os-specific/linux/kernel/common-config.nix b/pkgs/os-specific/linux/kernel/common-config.nix
index 01a605aac30..7a6ba94eb9f 100644
--- a/pkgs/os-specific/linux/kernel/common-config.nix
+++ b/pkgs/os-specific/linux/kernel/common-config.nix
@@ -1,4 +1,4 @@
-{ stdenv, version, kernelPlatform, extraConfig }:
+{ stdenv, version, kernelPlatform, extraConfig, features }:
 
 with stdenv.lib;
 
@@ -16,7 +16,9 @@ with stdenv.lib;
   DEBUG_DEVRES n
   DEBUG_NX_TEST n
   DEBUG_STACK_USAGE n
-  DEBUG_STACKOVERFLOW n
+  ${optionalString (!(features.grsecurity or true)) ''
+    DEBUG_STACKOVERFLOW n
+  ''}
   RCU_TORTURE_TEST n
   SCHEDSTATS n
   DETECT_HUNG_TASK y
@@ -63,7 +65,9 @@ with stdenv.lib;
 
   # Networking options.
   IP_PNP n
+  ${optionalString (versionOlder version "3.13") ''
   IPV6_PRIVACY y
+  ''}
   NETFILTER_ADVANCED y
   IP_VS_PROTO_TCP y
   IP_VS_PROTO_UDP y
@@ -74,17 +78,17 @@ with stdenv.lib;
   CLS_U32_MARK y
 
   # Wireless networking.
-  CFG80211_WEXT y # Without it, ipw2200 drivers don't build
-  IPW2100_MONITOR y # support promiscuous mode
-  IPW2200_MONITOR y # support promiscuous mode
-  HOSTAP_FIRMWARE y # Support downloading firmware images with Host AP driver
-  HOSTAP_FIRMWARE_NVRAM y
-  ATH9K_PCI y # Detect Atheros AR9xxx cards on PCI(e) bus
-  ATH9K_AHB y # Ditto, AHB bus
+  CFG80211_WEXT? y # Without it, ipw2200 drivers don't build
+  IPW2100_MONITOR? y # support promiscuous mode
+  IPW2200_MONITOR? y # support promiscuous mode
+  HOSTAP_FIRMWARE? y # Support downloading firmware images with Host AP driver
+  HOSTAP_FIRMWARE_NVRAM? y
+  ATH9K_PCI? y # Detect Atheros AR9xxx cards on PCI(e) bus
+  ATH9K_AHB? y # Ditto, AHB bus
   ${optionalString (versionAtLeast version "3.2") ''
-    B43_PHY_HT y
+    B43_PHY_HT? y
   ''}
-  BCMA_HOST_PCI y
+  BCMA_HOST_PCI? y
 
   # Enable various FB devices.
   FB y
@@ -106,12 +110,13 @@ with stdenv.lib;
   # Enable KMS for devices whose X.org driver supports it.
   DRM_I915_KMS y
   ${optionalString (versionOlder version "3.9") ''
-    DRM_RADEON_KMS y
+    DRM_RADEON_KMS? y
   ''}
   # Hybrid graphics support
   VGA_SWITCHEROO y
 
   # Sound.
+  SND_DYNAMIC_MINORS y
   SND_AC97_POWER_SAVE y # AC97 Power-Saving Mode
   SND_HDA_INPUT_BEEP y # Support digital beep via input layer
   SND_USB_CAIAQ_INPUT y
@@ -136,22 +141,31 @@ with stdenv.lib;
   # ACLs for all filesystems that support them.
   EXT2_FS_XATTR y
   EXT2_FS_POSIX_ACL y
-  EXT2_FS_SECURITY y # Ext2 Security Labels
+  EXT2_FS_SECURITY y
   EXT2_FS_XIP y # Ext2 execute in place support
+  EXT3_FS_POSIX_ACL y
+  EXT3_FS_SECURITY y
   EXT4_FS_POSIX_ACL y
   EXT4_FS_SECURITY y
-  REISERFS_FS_XATTR y
-  REISERFS_FS_POSIX_ACL y
-  REISERFS_FS_SECURITY y
-  JFS_POSIX_ACL y
-  JFS_SECURITY y
-  XFS_QUOTA y
-  XFS_POSIX_ACL y
-  XFS_RT y # XFS Realtime subvolume support
-  OCFS2_DEBUG_MASKLOG n
+  REISERFS_FS_XATTR? y
+  REISERFS_FS_POSIX_ACL? y
+  REISERFS_FS_SECURITY? y
+  JFS_POSIX_ACL? y
+  JFS_SECURITY? y
+  XFS_QUOTA? y
+  XFS_POSIX_ACL? y
+  XFS_RT? y # XFS Realtime subvolume support
+  OCFS2_DEBUG_MASKLOG? n
   BTRFS_FS_POSIX_ACL y
   UBIFS_FS_XATTR? y
-  UBIFS_FS_ADVANCED_COMPR y
+  UBIFS_FS_ADVANCED_COMPR? y
+  ${optionalString (versionAtLeast version "3.6") ''
+    NFS_SWAP y
+  ''}
+  ${optionalString (versionAtLeast version "3.11") ''
+    NFS_V4_1 y  # NFSv4.1 client support
+    NFS_V4_2 y
+  ''}
   NFSD_V2_ACL y
   NFSD_V3 y
   NFSD_V3_ACL y
@@ -164,29 +178,37 @@ with stdenv.lib;
   # Security related features.
   STRICT_DEVMEM y # Filter access to /dev/mem
   SECURITY_SELINUX_BOOTPARAM_VALUE 0 # Disable SELinux by default
-  DEVKMEM n # Disable /dev/kmem
-  CC_STACKPROTECTOR y # Detect buffer overflows on the stack
+  DEVKMEM? n # Disable /dev/kmem
+  ${if versionOlder version "3.14" then ''
+    CC_STACKPROTECTOR? y # Detect buffer overflows on the stack
+  '' else ''
+    CC_STACKPROTECTOR_REGULAR? y
+  ''}
   ${optionalString (versionAtLeast version "3.12") ''
     USER_NS y # Support for user namespaces
   ''}
 
+  # AppArmor support
+  SECURITY_APPARMOR y
+  DEFAULT_SECURITY_APPARMOR y
+
   # Misc. options.
   8139TOO_8129 y
   8139TOO_PIO n # PIO is slower
   AIC79XX_DEBUG_ENABLE n
   AIC7XXX_DEBUG_ENABLE n
   AIC94XX_DEBUG n
-  ${optionalString (versionAtLeast version "3.3") ''
+  ${optionalString (versionAtLeast version "3.3" && versionOlder version "3.13") ''
     AUDIT_LOGINUID_IMMUTABLE y
   ''}
-  B43_PCMCIA y
+  B43_PCMCIA? y
   BLK_DEV_CMD640_ENHANCED y # CMD640 enhanced support
   BLK_DEV_IDEACPI y # IDE ACPI support
   BLK_DEV_INTEGRITY y
   BSD_PROCESS_ACCT_V3 y
-  BT_HCIUART_BCSP y
-  BT_HCIUART_H4 y # UART (H4) protocol support
-  BT_HCIUART_LL y
+  BT_HCIUART_BCSP? y
+  BT_HCIUART_H4? y # UART (H4) protocol support
+  BT_HCIUART_LL? y
   BT_RFCOMM_TTY? y # RFCOMM TTY support
   CRASH_DUMP? n
   ${optionalString (versionOlder version "3.1") ''
@@ -200,10 +222,10 @@ with stdenv.lib;
   FUSION y # Fusion MPT device support
   IDE_GD_ATAPI y # ATAPI floppy support
   IRDA_ULTRA y # Ultra (connectionless) protocol
-  JOYSTICK_IFORCE_232 y # I-Force Serial joysticks and wheels
-  JOYSTICK_IFORCE_USB y # I-Force USB joysticks and wheels
-  JOYSTICK_XPAD_FF y # X-Box gamepad rumble support
-  JOYSTICK_XPAD_LEDS y # LED Support for Xbox360 controller 'BigX' LED
+  JOYSTICK_IFORCE_232? y # I-Force Serial joysticks and wheels
+  JOYSTICK_IFORCE_USB? y # I-Force USB joysticks and wheels
+  JOYSTICK_XPAD_FF? y # X-Box gamepad rumble support
+  JOYSTICK_XPAD_LEDS? y # LED Support for Xbox360 controller 'BigX' LED
   LDM_PARTITION y # Windows Logical Disk Manager (Dynamic Disk) support
   LEDS_TRIGGER_IDE_DISK y # LED IDE Disk Trigger
   LOGIRUMBLEPAD2_FF y # Logitech Rumblepad 2 force feedback
@@ -225,7 +247,7 @@ with stdenv.lib;
   SLIP_COMPRESSED y # CSLIP compressed headers
   SLIP_SMART y
   THERMAL_HWMON y # Hardware monitoring support
-  USB_DEBUG n
+  USB_DEBUG? n
   USB_EHCI_ROOT_HUB_TT y # Root Hub Transaction Translators
   USB_EHCI_TT_NEWSCHED y # Improved transaction translator scheduling
   X86_CHECK_BIOS_CORRUPTION y
@@ -269,17 +291,17 @@ with stdenv.lib;
   ''}
 
   # Virtualisation.
-  PARAVIRT y
+  PARAVIRT? y
   ${if versionAtLeast version "3.10" then ''
-    HYPERVISOR_GUEST y
+    HYPERVISOR_GUEST? y
   '' else ''
-    PARAVIRT_GUEST y
+    PARAVIRT_GUEST? y
   ''}
-  KVM_GUEST y
+  KVM_GUEST? y
   ${optionalString (versionOlder version "3.7") ''
-    KVM_CLOCK y
+    KVM_CLOCK? y
   ''}
-  XEN y
+  XEN? y
   XEN_DOM0? y
   KSM y
   ${optionalString (!stdenv.is64bit) ''
@@ -302,8 +324,19 @@ with stdenv.lib;
   ''}
 
   # Enable the 9P cache to speed up NixOS VM tests.
-  9P_FSCACHE y
-  9P_FS_POSIX_ACL y
+  9P_FSCACHE? y
+  9P_FS_POSIX_ACL? y
+
+  # Enable transparent support for huge pages.
+  TRANSPARENT_HUGEPAGE? y
+  TRANSPARENT_HUGEPAGE_ALWAYS? n
+  TRANSPARENT_HUGEPAGE_MADVISE? y
+
+  # zram support (e.g for in-memory compressed swap)
+  ${optionalString (versionAtLeast version "3.4") ''
+    ZSMALLOC y
+  ''}
+  ZRAM m
 
   ${kernelPlatform.kernelExtraConfig or ""}
   ${extraConfig}
diff --git a/pkgs/os-specific/linux/kernel/generate-config.pl b/pkgs/os-specific/linux/kernel/generate-config.pl
index 78663098fb3..20abe1015c3 100644
--- a/pkgs/os-specific/linux/kernel/generate-config.pl
+++ b/pkgs/os-specific/linux/kernel/generate-config.pl
@@ -11,6 +11,9 @@
 
 use strict;
 use IPC::Open2;
+use Cwd;
+
+my $wd = getcwd;
 
 my $debug = $ENV{'DEBUG'};
 my $autoModules = $ENV{'AUTO_MODULES'};
@@ -36,7 +39,7 @@ close ANSWERS;
 sub runConfig {
 
     # Run `make config'.
-    my $pid = open2(\*IN, \*OUT, "make config SHELL=bash ARCH=$ENV{ARCH}");
+    my $pid = open2(\*IN, \*OUT, "make -C $ENV{SRC} O=$wd config SHELL=bash ARCH=$ENV{ARCH}");
 
     # Parse the output, look for questions and then send an
     # appropriate answer.
diff --git a/pkgs/os-specific/linux/kernel/generic.nix b/pkgs/os-specific/linux/kernel/generic.nix
index 1ade2473627..08611e44856 100644
--- a/pkgs/os-specific/linux/kernel/generic.nix
+++ b/pkgs/os-specific/linux/kernel/generic.nix
@@ -1,4 +1,4 @@
-{ stdenv, fetchurl, perl, mktemp, kmod, bc
+{ stdenv, perl, buildLinux
 
 , # The kernel source tarball.
   src
@@ -23,26 +23,10 @@
   # symbolic name and `patch' is the actual patch.  The patch may
   # optionally be compressed with gzip or bzip2.
   kernelPatches ? []
-
-, # Allows you to set your own kernel version suffix (e.g.,
-  # "-my-kernel").
-  localVersion ? ""
-
-, preConfigure ? ""
 , extraMeta ? {}
-, ubootChooser ? null
-, postInstall ? ""
-
-, # After the builder did a 'make all' (kernel + modules)
-  # we force building the target asked: bzImage/zImage/uImage/...
-  postBuild ? "make $makeFlags $kernelTarget; make $makeFlags -C scripts unifdef"
-
 , ...
 }:
 
-assert stdenv.system == "i686-linux" || stdenv.system == "x86_64-linux"
-  || stdenv.isArm || stdenv.system == "mips64el-linux";
-
 assert stdenv.platform.name == "sheevaplug" -> stdenv.platform.uboot != null;
 
 let
@@ -55,93 +39,96 @@ let
         map ({extraConfig ? "", ...}: extraConfig) kernelPatches;
     in lib.concatStringsSep "\n" ([baseConfig] ++ configFromPatches);
 
-  configWithPlatform = kernelPlatform:
-    import ./common-config.nix { inherit stdenv version kernelPlatform extraConfig; };
+  configfile = stdenv.mkDerivation {
+    name = "linux-config-${version}";
 
-  config = configWithPlatform stdenv.platform;
-  configCross = configWithPlatform stdenv.cross.platform;
+    generateConfig = ./generate-config.pl;
 
-in
+    kernelConfig = kernelConfigFun config;
 
-stdenv.mkDerivation {
-  name = "linux-${version}";
+    ignoreConfigErrors = stdenv.platform.name != "pc";
 
-  enableParallelBuilding = true;
+    nativeBuildInputs = [ perl ];
 
-  passthru = {
-    inherit version modDirVersion kernelPatches;
-    # Combine the `features' attribute sets of all the kernel patches.
-    features = lib.fold (x: y: (x.features or {}) // y) features kernelPatches;
-  };
+    platformName = stdenv.platform.name;
+    kernelBaseConfig = stdenv.platform.kernelBaseConfig;
+    kernelTarget = stdenv.platform.kernelTarget;
+    autoModules = stdenv.platform.kernelAutoModules;
+    arch = stdenv.platform.kernelArch;
+
+    crossAttrs = let
+        cp = stdenv.cross.platform;
+      in {
+        arch = cp.kernelArch;
+        platformName = cp.name;
+        kernelBaseConfig = cp.kernelBaseConfig;
+        kernelTarget = cp.kernelTarget;
+        autoModules = cp.kernelAutoModules;
+
+        # Just ignore all options that don't apply (We are lazy).
+        ignoreConfigErrors = true;
 
-  builder = ./builder.sh;
+        kernelConfig = kernelConfigFun configCross;
 
-  generateConfig = ./generate-config.pl;
+        inherit (kernel.crossDrv) src patches preUnpack;
+      };
 
-  inherit preConfigure src kmod localVersion postInstall postBuild;
+    prePatch = kernel.prePatch + ''
+      # Patch kconfig to print "###" after every question so that
+      # generate-config.pl from the generic builder can answer them.
+      sed -e '/fflush(stdout);/i\printf("###");' -i scripts/kconfig/conf.c
+    '';
 
-  patches = map (p: p.patch) kernelPatches;
+    inherit (kernel) src patches preUnpack;
 
-  kernelConfig = kernelConfigFun config;
+    buildPhase = ''
+      cd $buildRoot
 
-  # For UML and non-PC, just ignore all options that don't apply (We are lazy).
-  ignoreConfigErrors = stdenv.platform.name != "pc";
+      # Get a basic config file for later refinement with $generateConfig.
+      make -C ../$sourceRoot O=$PWD $kernelBaseConfig ARCH=$arch
 
-  nativeBuildInputs = [ perl mktemp bc ];
+      # Create the config file.
+      echo "generating kernel configuration..."
+      echo "$kernelConfig" > kernel-config
+      DEBUG=1 ARCH=$arch KERNEL_CONFIG=kernel-config AUTO_MODULES=$autoModules \
+           SRC=../$sourceRoot perl -w $generateConfig
+    '';
 
-  buildInputs = lib.optional (stdenv.platform.uboot != null)
-    (ubootChooser stdenv.platform.uboot);
+    installPhase = "mv .config $out";
 
-  platformName = stdenv.platform.name;
-  kernelBaseConfig = stdenv.platform.kernelBaseConfig;
-  kernelTarget = stdenv.platform.kernelTarget;
-  autoModules = stdenv.platform.kernelAutoModules;
+    enableParallelBuilding = true;
+  };
+
+  kernel = buildLinux {
+    inherit version modDirVersion src kernelPatches;
 
-  # Should we trust platform.kernelArch? We can only do
-  # that once we differentiate i686/x86_64 in platforms.
-  arch =
-    if stdenv.system == "i686-linux" then "i386" else
-    if stdenv.system == "x86_64-linux" then "x86_64" else
-    if stdenv.isArm then "arm" else
-    if stdenv.system == "mips64el-linux" then "mips" else
-    abort "Platform ${stdenv.system} is not supported.";
+    configfile = configfile.nativeDrv or configfile;
 
-  crossAttrs = let
-      cp = stdenv.cross.platform;
-    in
-      assert cp.name == "sheevaplug" -> cp.uboot != null;
-    {
-      arch = cp.kernelArch;
-      platformName = cp.name;
-      kernelBaseConfig = cp.kernelBaseConfig;
-      kernelTarget = cp.kernelTarget;
-      autoModules = cp.kernelAutoModules;
+    crossConfigfile = configfile.crossDrv or configfile;
 
-      # Just ignore all options that don't apply (We are lazy).
-      ignoreConfigErrors = true;
+    config = { CONFIG_MODULES = "y"; CONFIG_FW_LOADER = "m"; };
+
+    crossConfig = { CONFIG_MODULES = "y"; CONFIG_FW_LOADER = "m"; };
+  };
 
-      kernelConfig = kernelConfigFun configCross;
+  passthru = {
+    # Combine the `features' attribute sets of all the kernel patches.
+    features = lib.fold (x: y: (x.features or {}) // y) features kernelPatches;
 
-      # The substitution of crossAttrs happens *after* the stdenv cross adapter sets
-      # the parameters for the usual stdenv. Thus, we need to specify
-      # the ".crossDrv" in the buildInputs here.
-      buildInputs = lib.optional (cp.uboot != null) (ubootChooser cp.uboot).crossDrv;
+    meta = kernel.meta // extraMeta;
+
+    passthru = kernel.passthru // (removeAttrs passthru [ "passthru" "meta" ]);
+  };
+
+  configWithPlatform = kernelPlatform: import ./common-config.nix
+    { inherit stdenv version kernelPlatform extraConfig;
+      features = passthru.features; # Ensure we know of all extra patches, etc.
     };
 
-  meta = {
-    description =
-      "The Linux kernel" +
-      (if kernelPatches == [] then "" else
-        " (with patches: "
-        + lib.concatStrings (lib.intersperse ", " (map (x: x.name) kernelPatches))
-        + ")");
-    license = "GPLv2";
-    homepage = http://www.kernel.org/;
-    maintainers = [
-      lib.maintainers.eelco
-      lib.maintainers.chaoflow
-    ];
-    platforms = lib.platforms.linux;
-  } // extraMeta;
-}
+  config = configWithPlatform stdenv.platform;
+  configCross = configWithPlatform stdenv.cross.platform;
+
+  nativeDrv = lib.addPassthru kernel.nativeDrv passthru;
 
+  crossDrv = lib.addPassthru kernel.crossDrv passthru;
+in if kernel ? crossDrv then nativeDrv // { inherit nativeDrv crossDrv; } else lib.addPassthru kernel passthru
diff --git a/pkgs/os-specific/linux/kernel/grsec-path.patch b/pkgs/os-specific/linux/kernel/grsec-path.patch
new file mode 100644
index 00000000000..6f59cf8d80b
--- /dev/null
+++ b/pkgs/os-specific/linux/kernel/grsec-path.patch
@@ -0,0 +1,17 @@
+diff --git a/kernel/kmod.c b/kernel/kmod.c
+index 67f7981..03f127d 100644
+--- a/kernel/kmod.c
++++ b/kernel/kmod.c
+@@ -246,9 +246,9 @@ static int ____call_usermodehelper(void *data)
+ 	   out the path to be used prior to this point and are now operating
+ 	   on that copy
+ 	*/
+-	if ((strncmp(sub_info->path, "/sbin/", 6) && strncmp(sub_info->path, "/usr/lib/", 9) &&
+-	     strncmp(sub_info->path, "/lib/", 5) && strncmp(sub_info->path, "/lib64/", 7) &&
+-	     strcmp(sub_info->path, "/usr/share/apport/apport")) || strstr(sub_info->path, "..")) {
++	if ((strncmp(sub_info->path, "/sbin/", 6) && strncmp(sub_info->path, "/nix/store/", 11) &&
++	     strncmp(sub_info->path, "/run/current-system/systemd/lib/", 32)) ||
++	     strstr(sub_info->path, "..")) {
+ 		printk(KERN_ALERT "grsec: denied exec of usermode helper binary %.950s located outside of /sbin and system library paths\n", sub_info->path);
+ 		retval = -EPERM;
+ 		goto fail;
diff --git a/pkgs/os-specific/linux/kernel/linux-3.0.nix b/pkgs/os-specific/linux/kernel/linux-3.0.nix
deleted file mode 100644
index 30b70035dfa..00000000000
--- a/pkgs/os-specific/linux/kernel/linux-3.0.nix
+++ /dev/null
@@ -1,12 +0,0 @@
-{ stdenv, fetchurl, ... } @ args:
-
-import ./generic.nix (args // rec {
-  version = "3.0.99";
-
-  src = fetchurl {
-    url = "mirror://kernel/linux/kernel/v3.x/linux-${version}.tar.xz";
-    sha256 = "1p31gq9kzwfks980y6rb2mjyagj8lrh6y156a550v7mk0bd4fzdi";
-  };
-
-  features.iwlwifi = true;
-})
diff --git a/pkgs/os-specific/linux/kernel/linux-3.10.nix b/pkgs/os-specific/linux/kernel/linux-3.10.nix
index 65660619857..8fa684e407c 100644
--- a/pkgs/os-specific/linux/kernel/linux-3.10.nix
+++ b/pkgs/os-specific/linux/kernel/linux-3.10.nix
@@ -1,11 +1,12 @@
 { stdenv, fetchurl, ... } @ args:
 
 import ./generic.nix (args // rec {
-  version = "3.10.15";
+  version = "3.10.53";
+  extraMeta.branch = "3.10";
 
   src = fetchurl {
     url = "mirror://kernel/linux/kernel/v3.x/linux-${version}.tar.xz";
-    sha256 = "07wjh58sylbbw9hwxd5xvbz3dxd05iar8ahzk90lki38m5157ffk";
+    sha256 = "1sxa6ppgpy9fgj4lyj8d53y309v6r5nmifbrcf5pqs6l944frhq6";
   };
 
   features.iwlwifi = true;
diff --git a/pkgs/os-specific/linux/kernel/linux-3.12.nix b/pkgs/os-specific/linux/kernel/linux-3.12.nix
index f0929af1d29..291e43a98e5 100644
--- a/pkgs/os-specific/linux/kernel/linux-3.12.nix
+++ b/pkgs/os-specific/linux/kernel/linux-3.12.nix
@@ -1,11 +1,12 @@
 { stdenv, fetchurl, ... } @ args:
 
 import ./generic.nix (args // rec {
-  version = "3.12-rc3";
+  version = "3.12.26";
+  extraMeta.branch = "3.12";
 
   src = fetchurl {
-    url = "https://www.kernel.org/pub/linux/kernel/v3.0/testing/linux-${version}.tar.xz";
-    sha256 = "1rayb0f4n81yp9ghcws0v36dpqyl9ks3naf37p2qy7jvrwagmj28";
+    url = "mirror://kernel/linux/kernel/v3.x/linux-${version}.tar.xz";
+    sha256 = "1gp6brk2ix30g8dznd5yv1fq7yx82295va6cn7lwv6jj9w287s6c";
   };
 
   features.iwlwifi = true;
diff --git a/pkgs/os-specific/linux/kernel/linux-3.11.nix b/pkgs/os-specific/linux/kernel/linux-3.14.nix
index 6531895d8a7..74d83345ec1 100644
--- a/pkgs/os-specific/linux/kernel/linux-3.11.nix
+++ b/pkgs/os-specific/linux/kernel/linux-3.14.nix
@@ -1,11 +1,12 @@
 { stdenv, fetchurl, ... } @ args:
 
 import ./generic.nix (args // rec {
-  version = "3.11.6";
+  version = "3.14.17";
+  extraMeta.branch = "3.14";
 
   src = fetchurl {
     url = "mirror://kernel/linux/kernel/v3.x/linux-${version}.tar.xz";
-    sha256 = "0klbyx6qy3ifwrwh5w7yzk6m6jd32flkk73z95bih3ihmbnbzlvs";
+    sha256 = "1dl9skwd1xvkdm9gblidcawkck6x5slb41gbx0i8jxby2k6w6i5n";
   };
 
   features.iwlwifi = true;
@@ -13,4 +14,4 @@ import ./generic.nix (args // rec {
   features.needsCifsUtils = true;
   features.canDisableNetfilterConntrackHelpers = true;
   features.netfilterRPFilter = true;
-})
+} // (args.argsOverride or {}))
diff --git a/pkgs/os-specific/linux/kernel/linux-3.15.nix b/pkgs/os-specific/linux/kernel/linux-3.15.nix
new file mode 100644
index 00000000000..cb2463ebfdc
--- /dev/null
+++ b/pkgs/os-specific/linux/kernel/linux-3.15.nix
@@ -0,0 +1,17 @@
+{ stdenv, fetchurl, ... } @ args:
+
+import ./generic.nix (args // rec {
+  version = "3.15.10";
+  extraMeta.branch = "3.15";
+
+  src = fetchurl {
+    url = "mirror://kernel/linux/kernel/v3.x/linux-${version}.tar.xz";
+    sha256 = "1x057a1pfr4rqzmjdb3x1bwwl6gzr6im8dg8f6anwz9fnps6vv5d";
+  };
+
+  features.iwlwifi = true;
+  features.efiBootStub = true;
+  features.needsCifsUtils = true;
+  features.canDisableNetfilterConntrackHelpers = true;
+  features.netfilterRPFilter = true;
+} // (args.argsOverride or {}))
diff --git a/pkgs/os-specific/linux/kernel/linux-3.9.nix b/pkgs/os-specific/linux/kernel/linux-3.16.nix
index 51bcf35b3fe..be2e68ab81e 100644
--- a/pkgs/os-specific/linux/kernel/linux-3.9.nix
+++ b/pkgs/os-specific/linux/kernel/linux-3.16.nix
@@ -1,11 +1,12 @@
 { stdenv, fetchurl, ... } @ args:
 
 import ./generic.nix (args // rec {
-  version = "3.9.11";
+  version = "3.16.1";
+  extraMeta.branch = "3.16";
 
   src = fetchurl {
     url = "mirror://kernel/linux/kernel/v3.x/linux-${version}.tar.xz";
-    sha256 = "0d5j7kg1ifzwipicbi4g26plzbzn1rlvgj1hs4zip6sxj8ifbffl";
+    sha256 = "0wbxqlmk7w9047ir51dsz6vi7ww0hpycgrb43mk2a189xaldsdxy";
   };
 
   features.iwlwifi = true;
@@ -13,4 +14,4 @@ import ./generic.nix (args // rec {
   features.needsCifsUtils = true;
   features.canDisableNetfilterConntrackHelpers = true;
   features.netfilterRPFilter = true;
-})
+} // (args.argsOverride or {}))
diff --git a/pkgs/os-specific/linux/kernel/linux-3.2.nix b/pkgs/os-specific/linux/kernel/linux-3.2.nix
index ae065499c65..13205e048ca 100644
--- a/pkgs/os-specific/linux/kernel/linux-3.2.nix
+++ b/pkgs/os-specific/linux/kernel/linux-3.2.nix
@@ -1,12 +1,27 @@
 { stdenv, fetchurl, ... } @ args:
 
 import ./generic.nix (args // rec {
-  version = "3.2.52";
+  version = "3.2.62";
+  extraMeta.branch = "3.2";
 
   src = fetchurl {
     url = "mirror://kernel/linux/kernel/v3.x/linux-${version}.tar.xz";
-    sha256 = "1wpr5xs6vg0xjlzrlbkv7bjvv34psw57crkdh4lybghi4rgrmkzl";
+    sha256 = "1yrmar14p5y9xaj9df388xwjmwz8fnsxnid6rkxxk7dni5di8nqf";
   };
 
-  features.iwlwifi = true;
-})
+  # We don't provide these patches if grsecurity is enabled, because
+  # the grsec 3.2 -stable patchset already includes them.
+  kernelPatches = args.kernelPatches ++ (
+    stdenv.lib.optionals (!(args.features.grsecurity or false))
+      [ { name = "0001-AppArmor-compatibility-patch-for-v5-network-controll";
+          patch = ./apparmor-patches/3.2/0001-AppArmor-compatibility-patch-for-v5-network-controll.patch;
+        }
+        { name = "0002-AppArmor-compatibility-patch-for-v5-interface";
+          patch = ./apparmor-patches/3.2/0002-AppArmor-compatibility-patch-for-v5-interface.patch;
+        }
+        { name = "0003-AppArmor-Allow-dfa-backward-compatibility-with-broke";
+          patch = ./apparmor-patches/3.2/0003-AppArmor-Allow-dfa-backward-compatibility-with-broke.patch;
+        }]);
+
+  features.iwlwifi  = true;
+} // (args.argsOverride or {}))
diff --git a/pkgs/os-specific/linux/kernel/linux-3.4.nix b/pkgs/os-specific/linux/kernel/linux-3.4.nix
index 47393b0ae74..30bb873501b 100644
--- a/pkgs/os-specific/linux/kernel/linux-3.4.nix
+++ b/pkgs/os-specific/linux/kernel/linux-3.4.nix
@@ -1,13 +1,25 @@
 { stdenv, fetchurl, ... } @ args:
 
 import ./generic.nix (args // rec {
-  version = "3.4.67";
+  version = "3.4.103";
+  extraMeta.branch = "3.4";
 
   src = fetchurl {
     url = "mirror://kernel/linux/kernel/v3.x/linux-${version}.tar.xz";
-    sha256 = "1ndzlwhxvlm4lr86240h3ysxhmdkgdcp0n6qhid5nwrmxf5fpb1d";
+    sha256 = "1ldga9l7dydwv5zvl3xgk8833cjv73yasyy2qmgimkbs03s8q4ig";
   };
 
+  kernelPatches = args.kernelPatches ++
+    [ { name = "0001-UBUNTU-SAUCE-AppArmor-Add-profile-introspection-file";
+        patch = ./apparmor-patches/3.4/0001-UBUNTU-SAUCE-AppArmor-Add-profile-introspection-file.patch;
+      }
+      { name = "0002-UBUNTU-SAUCE-AppArmor-basic-networking-rules";
+        patch = ./apparmor-patches/3.4/0002-UBUNTU-SAUCE-AppArmor-basic-networking-rules.patch;
+      }
+      { name = "0003-UBUNTU-SAUCE-apparmor-Add-the-ability-to-mediate-mou";
+        patch = ./apparmor-patches/3.4/0003-UBUNTU-SAUCE-apparmor-Add-the-ability-to-mediate-mou.patch;
+      }];
+
   features.iwlwifi = true;
   features.efiBootStub = true;
   features.needsCifsUtils = true;
diff --git a/pkgs/os-specific/linux/kernel/linux-rpi-3.6.nix b/pkgs/os-specific/linux/kernel/linux-rpi-3.6.nix
index fdf2f139c33..6d28c376078 100644
--- a/pkgs/os-specific/linux/kernel/linux-rpi-3.6.nix
+++ b/pkgs/os-specific/linux/kernel/linux-rpi-3.6.nix
@@ -15,5 +15,5 @@ in import ./generic.nix (args // rec {
 
   features.iwlwifi = true;
 
-  extraMeta.platforms = [];
+  extraMeta.hydraPlatforms = [];
 })
diff --git a/pkgs/os-specific/linux/kernel/linux-testing.nix b/pkgs/os-specific/linux/kernel/linux-testing.nix
new file mode 100644
index 00000000000..f44f3d32792
--- /dev/null
+++ b/pkgs/os-specific/linux/kernel/linux-testing.nix
@@ -0,0 +1,23 @@
+{ stdenv, fetchurl, ... } @ args:
+
+import ./generic.nix (args // rec {
+  # Reason to add:  RTL8192EE
+  version = "3.16-rc3";
+  modDirVersion = "3.16.0-rc3";
+  extraMeta.branch = "3.16";
+
+  src = fetchurl {
+    url = "mirror://kernel/linux/kernel/v3.x/testing/linux-${version}.tar.xz";
+    sha256 = "17jgv1hnx2im68f8721x11yfg8mpas7lsxg0j00qxv2fc6km2glm";
+  };
+
+  features.iwlwifi = true;
+  features.efiBootStub = true;
+  features.needsCifsUtils = true;
+  features.canDisableNetfilterConntrackHelpers = true;
+  features.netfilterRPFilter = true;
+
+  # Should the testing kernels ever be built on Hydra?
+  extraMeta.hydraPlatforms = [];
+
+} // (args.argsOverride or {}))
diff --git a/pkgs/os-specific/linux/kernel/manual-config.nix b/pkgs/os-specific/linux/kernel/manual-config.nix
index 29eb170287a..6d9baed7f2d 100644
--- a/pkgs/os-specific/linux/kernel/manual-config.nix
+++ b/pkgs/os-specific/linux/kernel/manual-config.nix
@@ -1,45 +1,16 @@
-{ stdenv, runCommand, nettools, bc, perl, kmod, writeTextFile }:
-
-with stdenv.lib;
+{ stdenv, runCommand, nettools, bc, perl, kmod, writeTextFile, ubootChooser }:
 
 let
-
-  # Function to parse the config file into a nix expression
-  readConfig = configFile:
-    let
-      configAttrs = import "${runCommand "config.nix" {} ''
-        echo "{" > "$out"
-        while IFS='=' read key val; do
-          [ "x''${key#CONFIG_}" != "x$key" ] || continue
-          no_firstquote="''${val#\"}";
-          echo '  "'"$key"'" = "'"''${no_firstquote%\"}"'";' >> "$out"
-        done < "${configFile}"
-        echo "}" >> $out
-      ''}";
-
-      config = configAttrs // rec {
-        attrName = attr: "CONFIG_" + attr;
-
-        isSet = attr: hasAttr (attrName attr) config;
-
-        getValue = attr: if isSet attr then getAttr (attrName attr) config else null;
-
-        isYes = attr: (isSet attr) && ((getValue attr) == "y");
-
-        isNo = attr: (isSet attr) && ((getValue attr) == "n");
-
-        isModule = attr: (isSet attr) && ((getValue attr) == "m");
-
-        isEnabled = attr: (isModule attr) || (isYes attr);
-
-        isDisabled = attr: (!(isSet attr)) || (isNo attr);
-      };
-    in
-      config;
-
-in
-
-{
+  readConfig = configfile: import (runCommand "config.nix" {} ''
+    echo "{" > "$out"
+    while IFS='=' read key val; do
+      [ "x''${key#CONFIG_}" != "x$key" ] || continue
+      no_firstquote="''${val#\"}";
+      echo '  "'"$key"'" = "'"''${no_firstquote%\"}"'";' >> "$out"
+    done < "${configfile}"
+    echo "}" >> $out
+  '').outPath;
+in {
   # The kernel version
   version,
   # The version of the kernel module directory
@@ -48,127 +19,220 @@ in
   src,
   # Any patches
   kernelPatches ? [],
-  # The kernel .config file
+  # Patches for native compiling only
+  nativeKernelPatches ? [],
+  # Patches for cross compiling only
+  crossKernelPatches ? [],
+  # The native kernel .config file
   configfile,
+  # The cross kernel .config file
+  crossConfigfile ? configfile,
   # Manually specified nixexpr representing the config
   # If unspecified, this will be autodetected from the .config
-  config ? optionalAttrs allowImportFromDerivation (readConfig configfile),
+  config ? stdenv.lib.optionalAttrs allowImportFromDerivation (readConfig configfile),
+  # Cross-compiling config
+  crossConfig ? if allowImportFromDerivation then (readConfig crossConfigfile) else config,
   # Whether to utilize the controversial import-from-derivation feature to parse the config
   allowImportFromDerivation ? false
 }:
 
 let
-  installkernel = name: writeTextFile { name = "installkernel"; executable=true; text = ''
-    #!/bin/sh
-    mkdir $4
-    cp -av $2 $4/${name}
-    cp -av $3 $4
-  '';};
-
-  isModular = config.isYes "MODULES";
+  inherit (stdenv.lib)
+    hasAttr getAttr optional optionalString optionalAttrs maintainers platforms;
 
-  installsFirmware = (config.isEnabled "FW_LOADER") &&
-    (isModular || (config.isDisabled "FIRMWARE_IN_KERNEL"));
+  installkernel = writeTextFile { name = "installkernel"; executable=true; text = ''
+    #!${stdenv.shell} -e
+    mkdir -p $4
+    cp -av $2 $4
+    cp -av $3 $4
+  ''; };
 
   commonMakeFlags = [
     "O=$(buildRoot)"
-    "INSTALL_PATH=$(out)"
-  ] ++ (optional isModular "INSTALL_MOD_PATH=$(out)")
-  ++ optional installsFirmware "INSTALL_FW_PATH=$(out)/lib/firmware";
+  ];
 
-  sourceRoot = stdenv.mkDerivation {
-    name = "linux-${version}-source";
+  drvAttrs = config_: platform: kernelPatches: configfile:
+    let
+      config = let attrName = attr: "CONFIG_" + attr; in {
+        isSet = attr: hasAttr (attrName attr) config;
 
-    inherit src;
+        getValue = attr: if config.isSet attr then getAttr (attrName attr) config else null;
 
-    patches = map (p: p.patch) kernelPatches;
+        isYes = attr: (config.getValue attr) == "y";
 
-    phases = [ "unpackPhase" "patchPhase" "installPhase" ]; 
+        isNo = attr: (config.getValue attr) == "n";
 
-    prePatch = ''
-      for mf in $(find -name Makefile -o -name Makefile.include -o -name install.sh); do
-          echo "stripping FHS paths in \`$mf'..."
-          sed -i "$mf" -e 's|/usr/bin/||g ; s|/bin/||g ; s|/sbin/||g'
-      done
-      sed -i Makefile -e 's|= depmod|= ${kmod}/sbin/depmod|'
-    '';
+        isModule = attr: (config.getValue attr) == "m";
 
-    installPhase = ''
-      cd ..
-      mv $sourceRoot $out
-    '';
-  };
-in
-
-stdenv.mkDerivation {
-  name = "linux-${version}";
+        isEnabled = attr: (config.isModule attr) || (config.isYes attr);
 
-  enableParallelBuilding = true;
+        isDisabled = attr: (!(config.isSet attr)) || (config.isNo attr);
+      } // config_;
 
-  outputs = if isModular then [ "out" "dev" ] else null;
+      isModular = config.isYes "MODULES";
 
-  passthru = {
-    inherit version modDirVersion config kernelPatches src;
-  };
+      installsFirmware = (config.isEnabled "FW_LOADER") &&
+        (isModular || (config.isDisabled "FIRMWARE_IN_KERNEL"));
+    in (optionalAttrs isModular { outputs = [ "out" "dev" ]; }) // {
+      passthru = {
+        inherit version modDirVersion config kernelPatches;
+      };
 
-  inherit sourceRoot;
+      inherit src;
+
+      preUnpack = ''
+        mkdir build
+        export buildRoot="$(pwd)/build"
+      '';
+
+      patches = map (p: p.patch) kernelPatches;
+
+      prePatch = ''
+        for mf in $(find -name Makefile -o -name Makefile.include -o -name install.sh); do
+            echo "stripping FHS paths in \`$mf'..."
+            sed -i "$mf" -e 's|/usr/bin/||g ; s|/bin/||g ; s|/sbin/||g'
+        done
+        sed -i Makefile -e 's|= depmod|= ${kmod}/sbin/depmod|'
+      '';
+
+      configurePhase = ''
+        runHook preConfigure
+        ln -sv ${configfile} $buildRoot/.config
+        make $makeFlags "''${makeFlagsArray[@]}" oldconfig
+        runHook postConfigure
+
+        buildFlagsArray+=("KBUILD_BUILD_TIMESTAMP=Thu Jan 1 00:00:01 UTC 1970")
+      '';
+
+      buildFlags = [
+        "KBUILD_BUILD_VERSION=1-NixOS"
+        platform.kernelTarget
+      ] ++ optional isModular "modules";
+
+      installFlags = [
+        "INSTALLKERNEL=${installkernel}"
+        "INSTALL_PATH=$(out)"
+      ] ++ (optional isModular "INSTALL_MOD_PATH=$(out)")
+      ++ optional installsFirmware "INSTALL_FW_PATH=$(out)/lib/firmware";
+
+      # Some image types need special install targets (e.g. uImage is installed with make uinstall)
+      installTargets = [ (if platform.kernelTarget == "uImage" then "uinstall" else "install") ];
+
+      postInstall = optionalString installsFirmware ''
+        mkdir -p $out/lib/firmware
+      '' + (if isModular then ''
+        make modules_install $makeFlags "''${makeFlagsArray[@]}" \
+          $installFlags "''${installFlagsArray[@]}"
+        unlink $out/lib/modules/${modDirVersion}/build
+        unlink $out/lib/modules/${modDirVersion}/source
+
+        mkdir -p $dev/lib/modules/${modDirVersion}
+        cd ..
+        mv $sourceRoot $dev/lib/modules/${modDirVersion}/source
+        cd $dev/lib/modules/${modDirVersion}/source
+
+        mv $buildRoot/.config $buildRoot/Module.symvers $TMPDIR
+        rm -fR $buildRoot
+        mkdir $buildRoot
+        mv $TMPDIR/.config $TMPDIR/Module.symvers $buildRoot
+        make modules_prepare $makeFlags "''${makeFlagsArray[@]}"
+        mv $buildRoot $dev/lib/modules/${modDirVersion}/build
+
+        # !!! No documentation on how much of the source tree must be kept
+        # If/when kernel builds fail due to missing files, you can add
+        # them here. Note that we may see packages requiring headers
+        # from drivers/ in the future; it adds 50M to keep all of its
+        # headers on 3.10 though.
+
+        chmod +w -R ../source
+        arch=`cd $dev/lib/modules/${modDirVersion}/build/arch; ls`
+
+        # Remove unusued arches
+        mv arch/$arch .
+        rm -fR arch
+        mkdir arch
+        mv $arch arch
+
+        # Remove all driver-specific code (50M of which is headers)
+        rm -fR drivers
+
+        # Keep all headers
+        find .  -type f -name '*.h' -print0 | xargs -0 chmod -w
+
+        # Keep root and arch-specific Makefiles
+        chmod -w Makefile
+        chmod -w arch/$arch/Makefile*
+
+        # Keep whole scripts dir
+        chmod -w -R scripts
+
+        # Delete everything not kept
+        find . -type f -perm -u=w -print0 | xargs -0 rm
+
+        # Delete empty directories
+        find -empty -type d -delete
+
+        # Remove reference to kmod
+        sed -i Makefile -e 's|= ${kmod}/sbin/depmod|= depmod|'
+      '' else optionalString installsFirmware ''
+        make firmware_install $makeFlags "''${makeFlagsArray[@]}" \
+          $installFlags "''${installFlagsArray[@]}"
+      '');
+
+      # !!! This leaves references to gcc in $dev
+      # that we might be able to avoid
+      postFixup = if isModular then ''
+        if [ -z "$dontStrip" ]; then
+            find $out -name "*.ko" -print0 | xargs -0 -r ''${crossConfig+$crossConfig-}strip -S
+        fi
+        # !!! Should this be part of stdenv? Also patchELF should take an argument...
+        prefix=$dev
+        patchELF
+        prefix=$out
+      '' else null;
+
+      meta = {
+        description =
+          "The Linux kernel" +
+          (if kernelPatches == [] then "" else
+            " (with patches: "
+            + stdenv.lib.concatStrings (stdenv.lib.intersperse ", " (map (x: x.name) kernelPatches))
+            + ")");
+        license = stdenv.lib.licenses.gpl2;
+        homepage = http://www.kernel.org/;
+        repositories.git = https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux-stable.git;
+        maintainers = [
+          maintainers.shlevy
+          maintainers.thoughtpolice
+        ];
+        platforms = platforms.linux;
+      };
+    };
+in
 
-  unpackPhase = ''
-    mkdir build
-    export buildRoot="$(pwd)/build"
-    cd ${sourceRoot}
-  '';
+stdenv.mkDerivation ((drvAttrs config stdenv.platform (kernelPatches ++ nativeKernelPatches) configfile) // {
+  name = "linux-${version}";
 
-  configurePhase = ''
-    runHook preConfigure
-    ln -sv ${configfile} $buildRoot/.config
-    make $makeFlags "''${makeFlagsArray[@]}" oldconfig
-    runHook postConfigure
-  '';
+  enableParallelBuilding = true;
 
-  nativeBuildInputs = [ perl bc nettools ];
+  nativeBuildInputs = [ perl bc nettools ] ++ optional (stdenv.platform.uboot != null)
+    (ubootChooser stdenv.platform.uboot);
 
   makeFlags = commonMakeFlags ++ [
-   "INSTALLKERNEL=${installkernel stdenv.platform.kernelTarget}"
+    "ARCH=${stdenv.platform.kernelArch}"
   ];
 
-  crossAttrs = {
-    makeFlags = commonMakeFlags ++ [
-     "INSTALLKERNEL=${installkernel stdenv.cross.platform.kernelTarget}"
-    ];
-  };
-
-  postInstall = optionalString installsFirmware ''
-    mkdir -p $out/lib/firmware
-  '' + (if isModular then ''
-    make modules_install $makeFlags "''${makeFlagsArray[@]}" \
-      $installFlags "''${installFlagsArray[@]}"
-    rm -f $out/lib/modules/${modDirVersion}/build
-    mkdir -p $dev/lib/modules/${modDirVersion}
-    mv $out/lib/modules/${modDirVersion}/source $dev/lib/modules/${modDirVersion}/source
-    mv $buildRoot $dev/lib/modules/${modDirVersion}/build
-  '' else optionalString installsFirmware ''
-    make firmware_install $makeFlags "''${makeFlagsArray[@]}" \
-      $installFlags "''${installFlagsArray[@]}"
-  '');
-
-  postFixup = if isModular then ''
-    if [ -z "$dontStrip" ]; then
-        find $out -name "*.ko" -print0 | xargs -0 -r strip -S
-        # Remove all references to the source directory to avoid unneeded
-        # runtime dependencies
-        find $out -name "*.ko" -print0 | xargs -0 -r sed -i \
-          "s|${sourceRoot}|$NIX_STORE/eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee-${sourceRoot.name}|g"
-    fi
-  '' else null;
-
-  meta = {
-    description = "The Linux kernel";
-    license = "GPLv2";
-    homepage = http://www.kernel.org/;
-    maintainers = [
-      maintainers.shlevy
-    ];
-    platforms = lib.platforms.linux;
+  crossAttrs = let cp = stdenv.cross.platform; in
+    (drvAttrs crossConfig cp (kernelPatches ++ crossKernelPatches) crossConfigfile) // {
+      makeFlags = commonMakeFlags ++ [
+        "ARCH=${cp.kernelArch}"
+        "CROSS_COMPILE=$(crossConfig)-"
+      ];
+
+      # !!! uboot has messed up cross-compiling, nativeDrv builds arm tools on x86,
+      # crossDrv builds x86 tools on x86 (but arm uboot). If this is fixed, uboot
+      # can just go into buildInputs (but not nativeBuildInputs since cp.uboot
+      # may be different from stdenv.platform.uboot)
+      buildInputs = optional (cp.uboot != null) (ubootChooser cp.uboot).crossDrv;
   };
-}
+})
diff --git a/pkgs/os-specific/linux/kernel/patches.nix b/pkgs/os-specific/linux/kernel/patches.nix
index 613f40c6fc9..cfe006fbe4b 100644
--- a/pkgs/os-specific/linux/kernel/patches.nix
+++ b/pkgs/os-specific/linux/kernel/patches.nix
@@ -3,7 +3,7 @@
 let
 
   makeTuxonicePatch = { version, kernelVersion, sha256,
-    url ? "http://tuxonice.net/files/tuxonice-${version}-for-${kernelVersion}.patch.bz2" }:
+    url ? "http://tuxonice.nigelcunningham.com.au/downloads/all/tuxonice-for-linux-${kernelVersion}-${version}.patch.bz2" }:
     { name = "tuxonice-${kernelVersion}";
       patch = stdenv.mkDerivation {
         name = "tuxonice-${version}-for-${kernelVersion}.patch";
@@ -18,98 +18,20 @@ let
       };
     };
 
-  makeAufs3StandalonePatch = {version, rev, sha256}:
-
-    stdenv.mkDerivation {
-      name = "aufs3-standalone-${version}.patch";
-
-      src = fetchgit {
-        url = git://aufs.git.sourceforge.net/gitroot/aufs/aufs3-standalone.git;
-        inherit sha256 rev;
+  grsecPatch = { grversion ? "3.0", kversion, revision, branch, sha256 }:
+    { name = "grsecurity-${grversion}-${kversion}";
+      inherit grversion kversion revision;
+      patch = fetchurl {
+        url = "http://grsecurity.net/${branch}/grsecurity-${grversion}-${kversion}-${revision}.patch";
+        inherit sha256;
       };
-
-      phases = [ "unpackPhase" "installPhase" ];
-
-      # Instructions from http://aufs.git.sourceforge.net/git/gitweb.cgi?p=aufs/aufs3-standalone.git;a=blob;f=Documentation/filesystems/aufs/README;h=b8cf077635b323d1b454266366f05f476bbd09cb;hb=1067b9d8d64d23c70d905c9cd3c90a669e39c4d4
-      installPhase = ''
-        cat aufs3-base.patch aufs3-proc_map.patch aufs3-standalone.patch > $out
-      '';
+      features.grsecurity = true;
     };
 
-  makeAppArmorPatch = {apparmor, version}:
-    stdenv.mkDerivation {
-      name = "apparmor-${version}.patch";
-      phases = ["installPhase"];
-      installPhase = ''
-        cat ${apparmor}/kernel-patches/${version}/* > $out
-      '';
-    };
 in
 
 rec {
 
-  apparmor_3_2 = rec {
-    version = "3.2";
-    name = "apparmor-${version}";
-    patch = makeAppArmorPatch { inherit apparmor version; };
-    features.apparmor = true;
-  };
-
-  apparmor_3_4 = rec {
-    version = "3.4";
-    name = "apparmor-${version}";
-    patch = makeAppArmorPatch { inherit apparmor version; };
-    features.apparmor = true;
-  };
-
-  sec_perm_2_6_24 =
-    { name = "sec_perm-2.6.24";
-      patch = ./sec_perm-2.6.24.patch;
-      features.secPermPatch = true;
-    };
-
-  aufs3_0 = rec {
-    name = "aufs3.0";
-    version = "3.0.20121210";
-    utilRev = "91af15f977d12e02165759620005f6ce1a4d7602";
-    utilHash = "dda4df89828dcf0e4012d88b4aa3eda8c30af69d6530ff5fedc2411de872c996";
-    patch = makeAufs3StandalonePatch {
-      inherit version;
-      rev = "0627c706d69778f5c74be982f28c746153b8cdf7";
-      sha256 = "7008ff64f5adc2b3a30fcbb090bcbfaac61b778af38493b6144fc7d768a6514d";
-    };
-    features.aufsBase = true;
-    features.aufs3 = true;
-  };
-
-  aufs3_2 = rec {
-    name = "aufs3.2";
-    version = "3.2.20121210";
-    utilRev = "91af15f977d12e02165759620005f6ce1a4d7602";
-    utilHash = "dda4df89828dcf0e4012d88b4aa3eda8c30af69d6530ff5fedc2411de872c996";
-    patch = makeAufs3StandalonePatch {
-      inherit version;
-      rev = "0bf50c3b82f98e2ddc4c9ba0657f28ebfa8d15cb";
-      sha256 = "bc4b65cb77c62744db251da98488fdf4962f14a144c045cea6cbbbd42718ff89";
-    };
-    features.aufsBase = true;
-    features.aufs3 = true;
-  };
-
-  aufs3_4 = rec {
-    name = "aufs3.4";
-    version = "3.4.20121210";
-    utilRev = "91af15f977d12e02165759620005f6ce1a4d7602";
-    utilHash = "dda4df89828dcf0e4012d88b4aa3eda8c30af69d6530ff5fedc2411de872c996";
-    patch = makeAufs3StandalonePatch {
-      inherit version;
-      rev = "2faacd9baffb37df3b9062cc554353eebe68df1e";
-      sha256 = "3ecf97468f5e85970d9fd2bfc61e38c7f5ae2c6dde0045d5a17de085c411d452";
-    };
-    features.aufsBase = true;
-    features.aufs3 = true;
-  };
-
   no_xsave =
     { name = "no-xsave";
       patch = ./no-xsave.patch;
@@ -131,14 +53,28 @@ rec {
       patch = ./mips-ext3-n32.patch;
     };
 
-  grsecurity_2_9_1_3_2_52 =
-    { name = "grsecurity-2.9.1-3.2.52";
-      patch = fetchurl {
-        url = http://grsecurity.net/stable/grsecurity-2.9.1-3.2.52-201310271550.patch;
-        sha256 = "08y4y323y2lfvdj67gmg3ca8gaf3snhr3pyrmgvj877avaz0475m";
-      };
-      # The grsec kernel patch seems to include the apparmor patches as of 2.9.1-3.2.52
-      features.apparmor = true;
+  tuxonice_3_10 = makeTuxonicePatch {
+    version = "2013-11-07";
+    kernelVersion = "3.10.18";
+    sha256 = "00b1rqgd4yr206dxp4mcymr56ymbjcjfa4m82pxw73khj032qw3j";
+  };
+
+  grsecurity_stable = grsecPatch
+    { kversion  = "3.14.10";
+      revision  = "201407012152";
+      branch    = "stable";
+      sha256    = "1119044lzkr9wpr1gpl1g0bz67c2xpdd9bkddllij7ja24jv8sx1";
     };
 
+  grsecurity_unstable = grsecPatch
+    { kversion  = "3.15.3";
+      revision  = "201407012153";
+      branch    = "test";
+      sha256    = "0bccayakprc77530crxfr9v2hbs6hlcf290pj1ywlh1p861ljgbm";
+    };
+
+  grsec_fix_path =
+    { name = "grsec-fix-path";
+      patch = ./grsec-path.patch;
+    };
 }
diff --git a/pkgs/os-specific/linux/kernel/perf.diff b/pkgs/os-specific/linux/kernel/perf.diff
new file mode 100644
index 00000000000..88d0381784f
--- /dev/null
+++ b/pkgs/os-specific/linux/kernel/perf.diff
@@ -0,0 +1,18 @@
+--- perf/config/utilities.mak.orig	2014-01-25 14:55:32.573320370 +0000
++++ perf/config/utilities.mak	2014-01-25 15:13:34.174337760 +0000
+@@ -186,9 +186,14 @@
+ endif
+ TRY_CC_MSG=echo "    CHK $(3)" 1>&2;
+ 
++define newline
++
++
++endef
++
+ try-cc = $(shell sh -c						  \
+ 	'TMP="$(OUTPUT)$(TMPOUT).$$$$";				  \
+ 	 $(TRY_CC_MSG)						  \
+-	 echo "$(1)" |						  \
++	 echo -e "$(subst $(newline),\\n,$(1))" | tee _test.c |   \
+ 	 $(CC) -x c - $(2) -o "$$TMP" $(TRY_CC_OUTPUT) && echo y; \
+ 	 rm -f "$$TMP"')
diff --git a/pkgs/os-specific/linux/kernel/perf.nix b/pkgs/os-specific/linux/kernel/perf.nix
index 04924f013a4..8b8f7e1e78d 100644
--- a/pkgs/os-specific/linux/kernel/perf.nix
+++ b/pkgs/os-specific/linux/kernel/perf.nix
@@ -1,17 +1,21 @@
-{ stdenv, kernelDev, elfutils, python, perl, newt, slang, asciidoc, xmlto
+{ lib, stdenv, kernel, elfutils, python, perl, newt, slang, asciidoc, xmlto
 , docbook_xsl, docbook_xml_dtd_45, libxslt, flex, bison, pkgconfig
 , withGtk ? false, gtk ? null }:
 
+with lib;
+
 assert withGtk -> gtk != null;
+assert versionAtLeast kernel.version "3.12";
 
 stdenv.mkDerivation {
-  name = "perf-linux-${kernelDev.version}";
+  name = "perf-linux-${kernel.version}";
 
-  inherit (kernelDev) src patches;
+  inherit (kernel) src patches;
 
   preConfigure = ''
     cd tools/perf
     sed -i s,/usr/include/elfutils,$elfutils/include/elfutils, Makefile
+    ${optionalString (versionOlder kernel.version "3.13") "patch -p1 < ${./perf.diff}"}
     [ -f bash_completion ] && sed -i 's,^have perf,_have perf,' bash_completion
     export makeFlags="DESTDIR=$out $makeFlags"
   '';
@@ -31,6 +35,7 @@ stdenv.mkDerivation {
     propagatedBuildInputs = [ elfutils.crossDrv newt.crossDrv ];
     makeFlags = "CROSS_COMPILE=${stdenv.cross.config}-";
     elfutils = elfutils.crossDrv;
+    inherit (kernel.crossDrv) src patches;
   };
 
   meta = {
diff --git a/pkgs/os-specific/linux/kernel/sec_perm-2.6.24.patch b/pkgs/os-specific/linux/kernel/sec_perm-2.6.24.patch
deleted file mode 100644
index de9b29949c3..00000000000
--- a/pkgs/os-specific/linux/kernel/sec_perm-2.6.24.patch
+++ /dev/null
@@ -1,16 +0,0 @@
-Index: linux-2.6.24-rc3/security/security.c
-===================================================================
-RCS file: /ext1/sysadm/transparent/repository/linux-2.6.24-rc3/security/security.c,v
-retrieving revision 1.1
-retrieving revision 1.2
-diff -u -p -r1.1 -r1.2
---- linux-2.6.24-rc3/security/security.c	21 Nov 2007 13:03:11 -0000	1.1
-+++ linux-2.6.24-rc3/security/security.c	21 Nov 2007 13:07:55 -0000	1.2
-@@ -409,6 +409,7 @@ int security_inode_permission(struct ino
- 		return 0;
- 	return security_ops->inode_permission(inode, mask, nd);
- }
-+EXPORT_SYMBOL(security_inode_permission);
- 
- int security_inode_setattr(struct dentry *dentry, struct iattr *attr)
- {
diff --git a/pkgs/os-specific/linux/keyutils/default.nix b/pkgs/os-specific/linux/keyutils/default.nix
index 43c580c2528..d1eb38df6da 100644
--- a/pkgs/os-specific/linux/keyutils/default.nix
+++ b/pkgs/os-specific/linux/keyutils/default.nix
@@ -1,25 +1,28 @@
-{stdenv, fetchurl}:
+{ stdenv, fetchurl, gnumake, file }:
 
 stdenv.mkDerivation rec {
-  name = "keyutils-1.2";
-  
+  name = "keyutils-1.5.9";
+
   src = fetchurl {
-    url = http://people.redhat.com/dhowells/keyutils/keyutils-1.2.tar.bz2;
-    sha256 = "0gcv47crbaw6crgn02j1w75mknhnwgkhmfcmwq2qi9iwiwprnv9h";
+    url = "http://people.redhat.com/dhowells/keyutils/${name}.tar.bz2";
+    sha256 = "1bl3w03ygxhc0hz69klfdlwqn33jvzxl1zfl2jmnb2v85iawb8jd";
   };
 
+  buildInputs = [ file ];
+
   patchPhase = ''
-    sed -i -e "s, /etc, $out/etc," \
-        -e "s, /bin, $out/bin," \
-        -e "s, /sbin, $out/sbin," \
-        -e "s, /lib, $out/lib," \
-        -e "s,/usr,$out," \
+    sed -i -e "s, /usr/bin/make, ${gnumake}/bin/make," \
+        -e "s, /usr, ," \
+        -e "s,\$(LNS) \$(LIBDIR)/\$(SONAME),\$(LNS) \$(SONAME)," \
         Makefile
   '';
-  
-  meta = {
+
+  installPhase = "make install DESTDIR=$out";
+
+  meta = with stdenv.lib; {
     homepage = http://people.redhat.com/dhowells/keyutils/;
     description = "Tools used to control the Linux kernel key management system";
-    license = "GPLv2+";
+    license = licenses.gpl2Plus;
+    platforms = platforms.linux;
   };
 }
diff --git a/pkgs/os-specific/linux/klibc/default.nix b/pkgs/os-specific/linux/klibc/default.nix
index 97bdd9ebacb..df44cb68d8b 100644
--- a/pkgs/os-specific/linux/klibc/default.nix
+++ b/pkgs/os-specific/linux/klibc/default.nix
@@ -1,74 +1,48 @@
-{ stdenv, fetchurl, perl, bison, mktemp, linuxHeaders, linuxHeadersCross, kernelDev ? null }:
-
-assert stdenv.isLinux;
+{ stdenv, fetchurl, kernelHeaders, kernel, perl }:
 
 let
-  version = "1.5.24";
-  baseMakeFlags = ["V=1" "prefix=$out" "SHLIBDIR=$out/lib"];
+  version = "2.0.3";
+
+  commonMakeFlags = [
+    "prefix=$(out)"
+    "SHLIBDIR=$(out)/lib"
+  ];
 in
 
 stdenv.mkDerivation {
-  name = "klibc-${version}${stdenv.lib.optionalString (kernelDev != null) "-${kernelDev.version}"}";
+  name = "klibc-${version}-${kernel.version}";
 
   src = fetchurl {
-    url = "mirror://kernel/linux/libs/klibc/1.5/klibc-${version}.tar.bz2";
-    sha256 = "18lm32dlj9k2ky9wwk274zmc3jndgrb41b6qm82g3lza6wlw3yki";
+    url = "mirror://kernel/linux/libs/klibc/2.0/klibc-${version}.tar.xz";
+    sha256 = "02035f2b230020de569d40605485121e0fe481ed33a93bdb8bf8c6ee2695fffa";
   };
 
-  # Trick to make this build on nix. It expects to have the kernel sources
-  # instead of only the linux kernel headers.
-  # So it cannot run the 'make headers_install' it wants to run.
-  # We don't install the headers, so klibc will not be useful as libc, but
-  # usually in nixpkgs we only use the userspace tools comming with klibc.
-  prePatch = stdenv.lib.optionalString (kernelDev == null) ''
-    sed -i -e /headers_install/d scripts/Kbuild.install
-  '';
-  
-  makeFlags = baseMakeFlags;
+  patches = [ ./no-reinstall-kernel-headers.patch ];
 
-  inherit linuxHeaders;
+  nativeBuildInputs = [ perl ];
 
-  crossAttrs = {
-    makeFlags = baseMakeFlags ++ [ "CROSS_COMPILE=${stdenv.cross.config}-"
-        "KLIBCARCH=${stdenv.cross.arch}" ];
+  makeFlags = commonMakeFlags ++ [
+    "KLIBCARCH=${stdenv.platform.kernelArch}"
+    "KLIBCKERNELSRC=${kernelHeaders}"
+  ] ++ stdenv.lib.optional (stdenv.platform.kernelArch == "arm") "CONFIG_AEABI=y";
 
-    patchPhase = ''
-      sed -i 's/-fno-pic -mno-abicalls/& -mabi=32/' usr/klibc/arch/mips/MCONFIG
-      sed -i /KLIBCKERNELSRC/d scripts/Kbuild.install
-      # Wrong check for __mips64 in klibc
-      sed -i s/__mips64__/__mips64/ usr/include/fcntl.h
-    '';
-
-    linuxHeaders = linuxHeadersCross;
+  crossAttrs = {
+    makeFlags = commonMakeFlags ++ [
+      "KLIBCARCH=${stdenv.cross.platform.kernelArch}"
+      "KLIBCKERNELSRC=${kernelHeaders.crossDrv}"
+      "CROSS_COMPILE=${stdenv.cross.config}-"
+    ] ++ stdenv.lib.optional (stdenv.cross.platform.kernelArch == "arm") "CONFIG_AEABI=y";
   };
-  
-  # The AEABI option concerns only arm systems, and does not affect the build for
-  # other systems.
-  preBuild = ''
-    sed -i /CONFIG_AEABI/d defconfig
-    echo "CONFIG_AEABI=y" >> defconfig
-    makeFlags=$(eval "echo $makeFlags")
 
-  '' + (if kernelDev == null then ''
-    mkdir linux
-    cp -prsd $linuxHeaders/include linux/
-    chmod -R u+w linux/include/
-  '' else ''
-    tar xvf ${kernelDev.src}
-    mv linux* linux
-    cd linux
-    ln -sv ${kernelDev}/config .config
-    make prepare
-    cd ..
-  '');
-  
   # Install static binaries as well.
   postInstall = ''
     dir=$out/lib/klibc/bin.static
     mkdir $dir
     cp $(find $(find . -name static) -type f ! -name "*.g" -a ! -name ".*") $dir/
     cp usr/dash/sh $dir/
+
+    for file in ${kernelHeaders}/include/*; do
+      ln -sv $file $out/lib/klibc/include
+    done
   '';
-  
-  nativeBuildInputs = [ perl bison mktemp ];
 }
diff --git a/pkgs/os-specific/linux/klibc/no-reinstall-kernel-headers.patch b/pkgs/os-specific/linux/klibc/no-reinstall-kernel-headers.patch
new file mode 100644
index 00000000000..d3e55fc8731
--- /dev/null
+++ b/pkgs/os-specific/linux/klibc/no-reinstall-kernel-headers.patch
@@ -0,0 +1,11 @@
+diff -Naur klibc-2.0.3-orig/scripts/Kbuild.install klibc-2.0.3/scripts/Kbuild.install
+--- klibc-2.0.3-orig/scripts/Kbuild.install	2013-12-03 13:53:46.000000000 -0500
++++ klibc-2.0.3/scripts/Kbuild.install	2014-01-04 18:17:09.342609021 -0500
+@@ -95,7 +95,6 @@
+ 	$(Q)mkdir -p $(INSTALLROOT)$(INSTALLDIR)/$(KCROSS)include
+ 	$(Q)mkdir -p $(INSTALLROOT)$(INSTALLDIR)/$(KCROSS)lib
+ 	$(Q)mkdir -p $(INSTALLROOT)$(INSTALLDIR)/$(KCROSS)bin
+-	$(Q)$(MAKE) -C $(KLIBCKERNELSRC) ARCH=$(KLIBCARCH) INSTALL_HDR_PATH=$(INSTALLROOT)$(INSTALLDIR)/$(KCROSS) headers_install
+ 	$(Q)cp -rf usr/include/. $(INSTALLROOT)$(INSTALLDIR)/$(KCROSS)include/.
+ 	$(Q)chmod -R a+rX $(INSTALLROOT)$(INSTALLDIR)/$(KCROSS)include
+ 	$(Q)$(install-data) $(srctree)/klcc/klcc.1 $(INSTALLROOT)$(mandir)/man1/$(KCROSS)klcc.1
diff --git a/pkgs/os-specific/linux/kmod-blacklist-ubuntu/default.nix b/pkgs/os-specific/linux/kmod-blacklist-ubuntu/default.nix
new file mode 100644
index 00000000000..682c36401de
--- /dev/null
+++ b/pkgs/os-specific/linux/kmod-blacklist-ubuntu/default.nix
@@ -0,0 +1,32 @@
+{ stdenv, fetchurl, gnugrep, findutils }:
+let
+  version = "3ubuntu1"; # Saucy
+in
+stdenv.mkDerivation {
+  name = "kmod-blacklist-${version}";
+
+  src = fetchurl {
+    url = "http://archive.ubuntu.com/ubuntu/pool/main/k/kmod/kmod_9-${version}.debian.tar.gz";
+    sha256 = "0h6h0zw2490iqj9xa2sz4309jyfmcc50jdvkhxa1nw90npxglp67";
+  };
+
+  installPhase = ''
+    mkdir "$out"
+    for f in modprobe.d/*.conf; do
+      echo "''\n''\n## file: "`basename "$f"`"''\n''\n" >> "$out"/modprobe.conf
+      cat "$f" >> "$out"/modprobe.conf
+    done
+
+    substituteInPlace "$out"/modprobe.conf \
+      --replace /sbin/lsmod /run/booted-system/sw/bin/lsmod \
+      --replace /sbin/rmmod /run/booted-system/sw/sbin/rmmod \
+      --replace /sbin/modprobe /run/booted-system/sw/sbin/modprobe \
+      --replace " grep " " ${gnugrep}/bin/grep " \
+      --replace " xargs " " ${findutils}/bin/xargs "
+  '';
+
+  meta = {
+    homepage = http://packages.ubuntu.com/source/saucy/kmod;
+    description = "Linux kernel module blacklists from Ubuntu";
+  };
+}
diff --git a/pkgs/os-specific/linux/kmod/default.nix b/pkgs/os-specific/linux/kmod/default.nix
index 96d756bc7d2..380b4a35f1c 100644
--- a/pkgs/os-specific/linux/kmod/default.nix
+++ b/pkgs/os-specific/linux/kmod/default.nix
@@ -1,11 +1,11 @@
 { stdenv, fetchurl, xz, zlib, pkgconfig, libxslt }:
 
 stdenv.mkDerivation rec {
-  name = "kmod-12";
+  name = "kmod-17";
 
   src = fetchurl {
     url = "mirror://kernel/linux/utils/kernel/kmod/${name}.tar.xz";
-    sha256 = "c6189dd8c5a1e8d9224e8506bd188c0cd5dfa119fd6b7e5869b3640cbe8bf92f";
+    sha256 = "1yid3a9b64a60ybj66fk2ysrq5klnl0ijl4g624cl16y8404g9rv";
   };
 
   # Disable xz/zlib support to prevent needing them in the initrd.
diff --git a/pkgs/os-specific/linux/kmod/module-dir.patch b/pkgs/os-specific/linux/kmod/module-dir.patch
index 95d08da4580..0c4ab4bd4c4 100644
--- a/pkgs/os-specific/linux/kmod/module-dir.patch
+++ b/pkgs/os-specific/linux/kmod/module-dir.patch
@@ -1,7 +1,7 @@
-diff -Naur kmod-7-orig/libkmod/libkmod.c kmod-7/libkmod/libkmod.c
---- kmod-7-orig/libkmod/libkmod.c	2012-03-15 08:19:16.750010226 -0400
-+++ kmod-7/libkmod/libkmod.c	2012-04-04 15:21:29.532074313 -0400
-@@ -200,7 +200,7 @@
+diff -ru -x '*~' kmod-17-orig/libkmod/libkmod.c kmod-17/libkmod/libkmod.c
+--- kmod-17-orig/libkmod/libkmod.c	2014-04-01 12:40:37.161940089 +0200
++++ kmod-17/libkmod/libkmod.c	2014-04-17 13:47:15.871441987 +0200
+@@ -201,7 +201,7 @@
  static char *get_kernel_release(const char *dirname)
  {
  	struct utsname u;
@@ -10,7 +10,7 @@ diff -Naur kmod-7-orig/libkmod/libkmod.c kmod-7/libkmod/libkmod.c
  
  	if (dirname != NULL)
  		return path_make_absolute_cwd(dirname);
-@@ -208,7 +208,10 @@
+@@ -209,7 +209,10 @@
  	if (uname(&u) < 0)
  		return NULL;
  
@@ -22,3 +22,39 @@ diff -Naur kmod-7-orig/libkmod/libkmod.c kmod-7/libkmod/libkmod.c
  		return NULL;
  
  	return p;
+diff -ru -x '*~' kmod-17-orig/tools/static-nodes.c kmod-17/tools/static-nodes.c
+--- kmod-17-orig/tools/static-nodes.c	2013-12-17 22:05:42.159047316 +0100
++++ kmod-17/tools/static-nodes.c	2014-04-17 13:51:17.945974320 +0200
+@@ -159,6 +159,7 @@
+ 	FILE *in = NULL, *out = NULL;
+ 	const struct static_nodes_format *format = &static_nodes_format_human;
+ 	int r, ret = EXIT_SUCCESS;
++	char *dirname_prefix;
+ 
+ 	for (;;) {
+ 		int c, idx = 0, valid;
+@@ -211,16 +212,19 @@
+ 		goto finish;
+ 	}
+ 
+-	snprintf(modules, sizeof(modules), "/lib/modules/%s/modules.devname", kernel.release);
++	if ((dirname_prefix = getenv("MODULE_DIR")) == NULL)
++		dirname_prefix = "/lib/modules";
++
++	snprintf(modules, sizeof(modules), "%s/%s/modules.devname", dirname_prefix, kernel.release);
+ 	in = fopen(modules, "re");
+ 	if (in == NULL) {
+ 		if (errno == ENOENT) {
+-			fprintf(stderr, "Warning: /lib/modules/%s/modules.devname not found - ignoring\n",
+-				kernel.release);
++			fprintf(stderr, "Warning: %s/%s/modules.devname not found - ignoring\n",
++				dirname_prefix, kernel.release);
+ 			ret = EXIT_SUCCESS;
+ 		} else {
+-			fprintf(stderr, "Error: could not open /lib/modules/%s/modules.devname - %m\n",
+-				kernel.release);
++			fprintf(stderr, "Error: could not open %s/%s/modules.devname - %m\n",
++				dirname_prefix, kernel.release);
+ 			ret = EXIT_FAILURE;
+ 		}
+ 		goto finish;
diff --git a/pkgs/os-specific/linux/kmscon/default.nix b/pkgs/os-specific/linux/kmscon/default.nix
new file mode 100644
index 00000000000..4f9b872ce1c
--- /dev/null
+++ b/pkgs/os-specific/linux/kmscon/default.nix
@@ -0,0 +1,50 @@
+{ stdenv
+, fetchurl
+, libtsm
+, systemd
+, libxkbcommon
+, libdrm
+, mesa
+, pango
+, pixman
+, pkgconfig
+, docbook_xsl
+, libxslt
+}:
+
+stdenv.mkDerivation rec {
+  name = "kmscon-8";
+
+  src = fetchurl {
+    url = "http://www.freedesktop.org/software/kmscon/releases/${name}.tar.xz";
+    sha256 = "0axfwrp3c8f4gb67ap2sqnkn75idpiw09s35wwn6kgagvhf1rc0a";
+  };
+
+  buildInputs = [
+    libtsm
+    systemd
+    libxkbcommon
+    libdrm
+    mesa
+    pango
+    pixman
+    pkgconfig
+    docbook_xsl
+    libxslt
+  ];
+
+  configureFlags = [
+    "--enable-multi-seat"
+    "--disable-debug"
+    "--enable-optimizations"
+    "--with-renderers=bbulk,gltex,pixman"
+  ];
+
+  meta = {
+    description = "KMS/DRM based System Console";
+    homepage = "http://www.freedesktop.org/wiki/Software/kmscon/";
+    license = stdenv.lib.licenses.mit;
+    maintainers = [ stdenv.lib.maintainers.shlevy ];
+    platforms = stdenv.lib.platforms.linux;
+  };
+}
diff --git a/pkgs/os-specific/linux/ktap/default.nix b/pkgs/os-specific/linux/ktap/default.nix
new file mode 100644
index 00000000000..a82804cb837
--- /dev/null
+++ b/pkgs/os-specific/linux/ktap/default.nix
@@ -0,0 +1,32 @@
+{ stdenv, fetchgit, kernel, useFFI ? false }:
+
+let
+  ffiArgs = stdenv.lib.optionalString useFFI "FFI=1";
+in
+stdenv.mkDerivation rec {
+  name = "ktap-${version}";
+  version = "0.5-e7a38ef0";
+  src = fetchgit {
+    url    = "https://github.com/ktap/ktap.git";
+    rev    = "e7a38ef06bec9a651c9e8bdb3ad66a104210d475";
+    sha256 = "07acf20e1926d3afd89b13855154b8cc792c57261e7d3cae2da70cb08844f9c8";
+  };
+
+  buildPhase = ''
+    make ${ffiArgs} KERNEL_SRC=${kernel.dev}/lib/modules/${kernel.modDirVersion}/build
+  '';
+
+  installPhase = ''
+    mkdir -p $out/sbin
+    cp ktap $out/sbin
+    make modules_install KERNEL_SRC=${kernel.dev}/lib/modules/${kernel.modDirVersion}/build INSTALL_MOD_PATH=$out
+  '';
+
+  meta = {
+    description = "A lightweight script-based dynamic tracing tool for Linux.";
+    homepage    = "http://www.ktap.org";
+    license     = stdenv.lib.licenses.gpl2;
+    platforms   = stdenv.lib.platforms.linux;
+    maintainers = [ stdenv.lib.maintainers.thoughtpolice ];
+  };
+}
diff --git a/pkgs/os-specific/linux/latencytop/default.nix b/pkgs/os-specific/linux/latencytop/default.nix
index eb776dcb86d..163ac189050 100644
--- a/pkgs/os-specific/linux/latencytop/default.nix
+++ b/pkgs/os-specific/linux/latencytop/default.nix
@@ -17,7 +17,7 @@ stdenv.mkDerivation rec {
   meta = {
     homepage = http://latencytop.org;
     description = "Tool to show kernel reports on latencies (LATENCYTOP option)";
-    license = "GPLv2";
+    license = stdenv.lib.licenses.gpl2;
     maintainers = [ stdenv.lib.maintainers.viric ];
     platforms = stdenv.lib.platforms.linux;
   };
diff --git a/pkgs/os-specific/linux/ldm/default.nix b/pkgs/os-specific/linux/ldm/default.nix
new file mode 100644
index 00000000000..c5e94ed81e9
--- /dev/null
+++ b/pkgs/os-specific/linux/ldm/default.nix
@@ -0,0 +1,42 @@
+{ stdenv, fetchgit, udev, utillinux, mountPath ? "/media/" }:
+
+assert mountPath != "";
+
+let
+  version = "0.5";
+  git = https://github.com/LemonBoy/ldm.git;
+in
+stdenv.mkDerivation rec {
+  name = "ldm-${version}";
+
+  # There is a stable release, but we'll use the lvm branch, which
+  # contains important fixes for LVM setups.
+  src = fetchgit {
+    url = meta.repositories.git;
+    rev = "refs/tags/v${version}";
+    sha256 = "0kkby3a0xgh1lmkbzpsi4am2rqjv3ccgdpic99aw1c76y0ca837y";
+  };
+
+  buildInputs = [ udev utillinux ];
+
+  preBuild = ''
+    substituteInPlace ldm.c \
+      --replace "/mnt/" "${mountPath}"
+  '';
+
+  buildPhase = "make ldm";
+
+  installPhase = ''
+    mkdir -p $out/bin
+    cp -v ldm $out/bin
+  '';
+
+  meta = {
+    description = "A lightweight device mounter, with libudev as only dependency";
+    license = stdenv.lib.licenses.mit;
+
+    platforms = stdenv.lib.platforms.linux;
+    maintainers = [ stdenv.lib.maintainers.the-kenny ];
+    repositories.git = git;
+  };
+}
diff --git a/pkgs/os-specific/linux/libaio/default.nix b/pkgs/os-specific/linux/libaio/default.nix
index 57137400b2f..bf30530e9ad 100644
--- a/pkgs/os-specific/linux/libaio/default.nix
+++ b/pkgs/os-specific/linux/libaio/default.nix
@@ -1,11 +1,12 @@
-{ stdenv, fetchurl }:
+{ stdenv, fetchgit }:
 
 stdenv.mkDerivation rec {
   name = "libaio-0.3.109";
 
-  src = fetchurl {
-    url = "mirror://kernel/linux/libs/aio/${name}.tar.bz2";
-    sha256 = "15772ki2wckf2mj4gm1vhrsmpd6rq20983nhlkfghjfblghgrkmm";
+  src = fetchgit {
+    url = https://git.fedorahosted.org/git/libaio.git;
+    rev = "refs/tags/${name}";
+    sha256 = "1wbziq0hqvnbckpxrz1cgr8dlw3mifs4xpy3qhnagbrrsmrq2rhi";
   };
 
   makeFlags = "prefix=$(out)";
diff --git a/pkgs/os-specific/linux/libatasmart/default.nix b/pkgs/os-specific/linux/libatasmart/default.nix
index 86dffde4b55..7fe0a2be10f 100644
--- a/pkgs/os-specific/linux/libatasmart/default.nix
+++ b/pkgs/os-specific/linux/libatasmart/default.nix
@@ -1,11 +1,11 @@
 { stdenv, fetchurl, pkgconfig, udev }:
 
 stdenv.mkDerivation rec {
-  name = "libatasmart-0.17";
+  name = "libatasmart-0.19";
 
   src = fetchurl {
-    url = "http://0pointer.de/public/${name}.tar.gz";
-    sha256 = "1zazxnqsirlv9gkzij6z31b21gv2nv7gkpja0wpxwb7kfh9a2qid";
+    url = "http://0pointer.de/public/${name}.tar.xz";
+    sha256 = "138gvgdwk6h4ljrjsr09pxk1nrki4b155hqdzyr8mlk3bwsfmw31";
   };
 
   buildInputs = [ pkgconfig udev ];
diff --git a/pkgs/os-specific/linux/libcap-ng/default.nix b/pkgs/os-specific/linux/libcap-ng/default.nix
index bbeb2851ea3..3670f06e543 100644
--- a/pkgs/os-specific/linux/libcap-ng/default.nix
+++ b/pkgs/os-specific/linux/libcap-ng/default.nix
@@ -17,6 +17,6 @@ stdenv.mkDerivation rec {
     description = "Library for working with POSIX capabilities";
     homepage = http://people.redhat.com/sgrubb/libcap-ng/;
     platforms = stdenv.lib.platforms.linux;
-    license = "LGPLv2.1";
+    license = stdenv.lib.licenses.lgpl21;
   };
 }
diff --git a/pkgs/os-specific/linux/libnl/3.2.19.nix b/pkgs/os-specific/linux/libnl/3.2.19.nix
new file mode 100644
index 00000000000..ea508c088e7
--- /dev/null
+++ b/pkgs/os-specific/linux/libnl/3.2.19.nix
@@ -0,0 +1,20 @@
+
+{stdenv, fetchurl, bison, flex}:
+
+stdenv.mkDerivation rec {
+  name = "libnl-3.2.19";
+
+  src = fetchurl {
+    url = "${meta.homepage}files/${name}.tar.gz";
+    sha256 = "12q97cw680hg4rylyd8j3d7azwwia4ndsv3kybd1ajp8hjni39ip";
+  };
+
+  buildInputs = [ bison flex ];
+
+  meta = {
+    homepage = "http://www.infradead.org/~tgr/libnl/";
+    description = "Linux NetLink interface library";
+    maintainers = [ stdenv.lib.maintainers.urkud ];
+    platforms = stdenv.lib.platforms.linux;
+  };
+}
diff --git a/pkgs/os-specific/linux/libnl/default.nix b/pkgs/os-specific/linux/libnl/default.nix
index 6fe31c63178..093a00ed9a5 100644
--- a/pkgs/os-specific/linux/libnl/default.nix
+++ b/pkgs/os-specific/linux/libnl/default.nix
@@ -1,11 +1,11 @@
 {stdenv, fetchurl, bison, flex}:
 
 stdenv.mkDerivation rec {
-  name = "libnl-3.2.13";
+  name = "libnl-3.2.23";
 
   src = fetchurl {
     url = "${meta.homepage}files/${name}.tar.gz";
-    sha256 = "1ydw42lsd572qwrfgws97n76hyvjdpanwrxm03lysnhfxkna1ssd";
+    sha256 = "1czj2bpb799bih6ighqwbvv9pvbpcw7vmccv9cwavfwcmalwvhlc";
   };
 
   buildInputs = [ bison flex ];
diff --git a/pkgs/os-specific/linux/libselinux/default.nix b/pkgs/os-specific/linux/libselinux/default.nix
index 01935e76632..746f49b519d 100644
--- a/pkgs/os-specific/linux/libselinux/default.nix
+++ b/pkgs/os-specific/linux/libselinux/default.nix
@@ -8,38 +8,30 @@ with stdenv.lib;
 
 stdenv.mkDerivation rec {
   name = "libselinux-${version}";
-  version = "2.1.12";
+  version = "2.3";
   inherit (libsepol) se_release se_url;
 
   src = fetchurl {
     url = "${se_url}/${se_release}/libselinux-${version}.tar.gz";
-    sha256 = "17navgvljgq35bljzcdwjdj3khajc27s15binr51xkp0h29qgbcd";
+    sha256 = "1ckpiv6m5c07rp5vawlhv02w5rq8kc0n95fh2ckq2jnqxi1hn7hb";
   };
 
-  patch_src = fetchurl {
-    url = "http://dev.gentoo.org/~swift/patches/libselinux/patchbundle-${name}-r2.tar.gz";
-    sha256 = "08zaas8iwyf4w9ll1ylyv4gril1nfarckd5h1l53563sxzyf7dqh";
-  };
-
-  patches = [ ./fPIC.patch ]; # libsemanage seems to need -fPIC everywhere
-
   buildInputs = [ pkgconfig libsepol pcre ]
              ++ optionals enablePython [ swig python ];
 
-  prePatch = ''
-    tar xvf ${patch_src}
-    for p in gentoo-patches/*.patch; do
-      patch -p1 < "$p"
-    done
-  '';
-
   postPatch = optionalString enablePython ''
     sed -i -e 's|\$(LIBDIR)/libsepol.a|${libsepol}/lib/libsepol.a|' src/Makefile
   '';
 
-  installFlags = [ "PREFIX=$(out)" "DESTDIR=$(out)" "LIBSEPOLDIR=${libsepol}" ];
+  installFlags = [ "PREFIX=$(out)" "DESTDIR=$(out)" ];
   installTargets = [ "install" ] ++ optional enablePython "install-pywrap";
 
+  # TODO: Figure out why the build incorrectly links libselinux.so
+  postInstall = ''
+    rm $out/lib/libselinux.so
+    ln -s libselinux.so.1 $out/lib/libselinux.so
+  '';
+
   meta = {
     inherit (libsepol.meta) homepage platforms maintainers;
   };
diff --git a/pkgs/os-specific/linux/libsemanage/default.nix b/pkgs/os-specific/linux/libsemanage/default.nix
index 28908189cf3..599da9e4b3c 100644
--- a/pkgs/os-specific/linux/libsemanage/default.nix
+++ b/pkgs/os-specific/linux/libsemanage/default.nix
@@ -1,13 +1,13 @@
-{ stdenv, fetchurl, libsepol, libselinux, ustr, bzip2, bison, flex }:
+{ stdenv, fetchurl, libsepol, libselinux, ustr, bzip2, bison, flex, audit }:
 stdenv.mkDerivation rec {
 
   name = "libsemanage-${version}";
-  version = "2.1.9";
+  version = "2.3";
   inherit (libsepol) se_release se_url;
 
   src = fetchurl {
     url = "${se_url}/${se_release}/libsemanage-${version}.tar.gz";
-    sha256 = "1k1my3n1pj30c5887spykcdk1brgxfpxmrz6frxjyhaijxzx20bg";
+    sha256 = "0jrf66df80mvjhrsbxcnb60j69pg4dh2pydy8vj8dhhiwqsrxq03";
   };
 
   makeFlags = "PREFIX=$(out) DESTDIR=$(out)";
@@ -15,7 +15,7 @@ stdenv.mkDerivation rec {
   NIX_CFLAGS_COMPILE = "-fstack-protector-all";
   NIX_CFLAGS_LINK = "-lsepol";
 
-  buildInputs = [ libsepol libselinux ustr bzip2 bison flex ];
+  buildInputs = [ libsepol libselinux ustr bzip2 bison flex audit ];
 
   meta = with stdenv.lib; {
     inherit (libsepol.meta) homepage platforms maintainers;
diff --git a/pkgs/os-specific/linux/libsepol/default.nix b/pkgs/os-specific/linux/libsepol/default.nix
index d41d1cbe752..c469fe93493 100644
--- a/pkgs/os-specific/linux/libsepol/default.nix
+++ b/pkgs/os-specific/linux/libsepol/default.nix
@@ -2,23 +2,29 @@
 
 stdenv.mkDerivation rec {
   name = "libsepol-${version}";
-  version = "2.1.8";
-  se_release = "20120924";
+  version = "2.3";
+  se_release = "20140506";
   se_url = "${meta.homepage}/releases";
 
   src = fetchurl {
     url = "${se_url}/${se_release}/libsepol-${version}.tar.gz";
-    sha256 = "1w38q3lmha5m9aps9w844i51yw4b8q1vhpng2kdywn2n8cpdvvk3";
+    sha256 = "13z6xakc2qqyhlvnc5h53jy7lqmh5b5cnpfn51lmvfdpqd18d3fc";
   };
 
   preBuild = '' makeFlags="$makeFlags PREFIX=$out DESTDIR=$out" '';
 
-  passthru = { inherit se_release se_url meta; };
+  # TODO: Figure out why the build incorrectly links libsepol.so
+  postInstall = ''
+    rm $out/lib/libsepol.so
+    ln -s libsepol.so.1 $out/lib/libsepol.so
+  '';
+
+  passthru = { inherit se_release se_url; };
 
   meta = with stdenv.lib; {
     homepage = http://userspace.selinuxproject.org;
     platforms = platforms.linux;
     maintainers = [ maintainers.phreedom ];
-    license = "GPLv2";
+    license = stdenv.lib.licenses.gpl2;
   };
 }
diff --git a/pkgs/os-specific/linux/libvolume_id/default.nix b/pkgs/os-specific/linux/libvolume_id/default.nix
index 3deaa7097c4..0a52df0bee7 100644
--- a/pkgs/os-specific/linux/libvolume_id/default.nix
+++ b/pkgs/os-specific/linux/libvolume_id/default.nix
@@ -1,11 +1,11 @@
 {stdenv, fetchurl}:
    
 stdenv.mkDerivation {
-  name = "libvolume_id-0.81.0";
+  name = "libvolume_id-0.81.1";
    
   src = fetchurl {
-    url = http://www.marcuscom.com/downloads/libvolume_id-0.81.0.tar.bz2;
-    sha256 = "1dpmp1kb40kb1jxj6flpi37wy789wf91dm4bax6jspd1jdc6hsrg";
+    url = http://www.marcuscom.com/downloads/libvolume_id-0.81.1.tar.bz2;
+    sha256 = "029z04vdxxsl8gycm9whcljhv6dy4b12ybsxdb99jr251gl1ifs5";
   };
 
   preBuild = "
diff --git a/pkgs/os-specific/linux/lm-sensors/default.nix b/pkgs/os-specific/linux/lm-sensors/default.nix
index 354027dbd71..388ec857b4a 100644
--- a/pkgs/os-specific/linux/lm-sensors/default.nix
+++ b/pkgs/os-specific/linux/lm-sensors/default.nix
@@ -1,13 +1,13 @@
 { stdenv, fetchurl, bison, flex, which, perl }:
 
-let version = "3.3.4"; in
+let version = "3.3.5"; in
 
 stdenv.mkDerivation rec {
   name = "lm-sensors-${version}";
   
   src = fetchurl {
     url = "http://dl.lm-sensors.org/lm-sensors/releases/lm_sensors-${version}.tar.bz2";
-    sha256 = "0vd7dgpcri7cbvgl5fwvja53lqz829vkbbp17x7b5r2xrc88cq5l";
+    sha256 = "1ksgrynxgrq590nb2fwxrl1gwzisjkqlyg3ljfd1al0ibrk6mbjx";
   };
 
   buildInputs = [ bison flex which perl ];
diff --git a/pkgs/os-specific/linux/lockdep/default.nix b/pkgs/os-specific/linux/lockdep/default.nix
new file mode 100644
index 00000000000..1554715a613
--- /dev/null
+++ b/pkgs/os-specific/linux/lockdep/default.nix
@@ -0,0 +1,29 @@
+{ stdenv, fetchurl }:
+
+stdenv.mkDerivation rec {
+  name    = "lockdep-${version}";
+  version = "3.16.1";
+
+  src = fetchurl {
+    url = "mirror://kernel/linux/kernel/v3.x/linux-${version}.tar.xz";
+    sha256 = "0wbxqlmk7w9047ir51dsz6vi7ww0hpycgrb43mk2a189xaldsdxy";
+  };
+
+  preConfigure = "cd tools/lib/lockdep";
+  installPhase = ''
+    mkdir -p $out/bin $out/lib $out/include
+
+    cp -R include/liblockdep $out/include
+    make install DESTDIR=$out prefix=""
+
+    substituteInPlace $out/bin/lockdep --replace "./liblockdep.so" "$out/lib/liblockdep.so.$version"
+  '';
+
+  meta = {
+    description = "userspace locking validation tool built on the Linux kernel";
+    homepage    = "https://kernel.org/";
+    license     = stdenv.lib.licenses.gpl2;
+    platforms   = stdenv.lib.platforms.linux;
+    maintainers = [ stdenv.lib.maintainers.thoughtpolice ];
+  };
+}
diff --git a/pkgs/os-specific/linux/lsiutil/default.nix b/pkgs/os-specific/linux/lsiutil/default.nix
index 700455d5f8b..93cab433c9c 100644
--- a/pkgs/os-specific/linux/lsiutil/default.nix
+++ b/pkgs/os-specific/linux/lsiutil/default.nix
@@ -35,6 +35,6 @@ stdenv.mkDerivation rec {
   meta = {
     homepage = http://www.lsi.com/;
     description = "LSI Logic Fusion MPT command line management tool";
-    license = "unfree";
+    license = stdenv.lib.licenses.unfree;
   };
 }
diff --git a/pkgs/os-specific/linux/lsscsi/default.nix b/pkgs/os-specific/linux/lsscsi/default.nix
index 886f6c799a4..70e82662b41 100644
--- a/pkgs/os-specific/linux/lsscsi/default.nix
+++ b/pkgs/os-specific/linux/lsscsi/default.nix
@@ -3,11 +3,11 @@
 assert stdenv.isLinux;
 
 stdenv.mkDerivation {
-  name = "lsscsi-0.24";
+  name = "lsscsi-0.27";
 
   src = fetchurl {
-    url = "http://sg.danny.cz/scsi/lsscsi-0.24.tgz";
-    sha256 = "0c718w80vi9a0w48q8xmlnbyqzxfd8lax5dcbqg8gvg4l2zaba2c";
+    url = "http://sg.danny.cz/scsi/lsscsi-0.27.tgz";
+    sha256 = "1d6rl2jwpd6zlqymmp9z4ri5j43d44db2s71j0v0rzs1nbvm90kb";
   };
 
   preConfigure = ''
diff --git a/pkgs/os-specific/linux/lttng-modules/default.nix b/pkgs/os-specific/linux/lttng-modules/default.nix
index e58d61e426b..8e20bf1e3d3 100644
--- a/pkgs/os-specific/linux/lttng-modules/default.nix
+++ b/pkgs/os-specific/linux/lttng-modules/default.nix
@@ -1,18 +1,18 @@
-{ stdenv, fetchurl, kernelDev }:
+{ stdenv, fetchurl, kernel }:
 
 stdenv.mkDerivation rec {
-  pname = "lttng-modules-2.3.0";
-  name = "${pname}-${kernelDev.version}";
+  pname = "lttng-modules-2.4.1";
+  name = "${pname}-${kernel.version}";
 
   src = fetchurl {
     url = "https://lttng.org/files/lttng-modules/${pname}.tar.bz2";
-    sha256 = "0l9fbmpsjvm5pbrc6axy8chdp21j4b8fm0hmjhpk658ll0iixmpb";
+    sha256 = "1qn1qm8lwqw9ri9wfkf6k3d58gl9rwffmpbpkwx21v1fw95zi92k";
   };
 
   patches = [ ./lttng-fix-build-error-on-linux-3.2.patch ];
 
   preConfigure = ''
-    export KERNELDIR="${kernelDev}/lib/modules/${kernelDev.modDirVersion}/build"
+    export KERNELDIR="${kernel.dev}/lib/modules/${kernel.modDirVersion}/build"
     export INSTALL_MOD_PATH="$out"
   '';
 
@@ -23,9 +23,7 @@ stdenv.mkDerivation rec {
   meta = with stdenv.lib; {
     description = "Linux kernel modules for LTTng tracing";
     homepage = http://lttng.org/;
-    # TODO: Add "mit" to the license list once the license attr set vs string
-    # decision has been made. (Having "mit" there breaks hydra evaluation.)
-    license = with licenses; [ lgpl21 gpl2 ];
+    # TODO license = with licenses; [ lgpl21 gpl2 mit ];
     platforms = platforms.linux;
     maintainers = [ maintainers.bjornfor ];
   };
diff --git a/pkgs/os-specific/linux/lvm2/default.nix b/pkgs/os-specific/linux/lvm2/default.nix
index 53127e4458c..9e2b0c90079 100644
--- a/pkgs/os-specific/linux/lvm2/default.nix
+++ b/pkgs/os-specific/linux/lvm2/default.nix
@@ -1,7 +1,7 @@
 { stdenv, fetchurl, pkgconfig, udev, utillinux, coreutils }:
 
 let
-  v = "2.02.100";
+  v = "2.02.106";
 in
 
 stdenv.mkDerivation {
@@ -9,7 +9,7 @@ stdenv.mkDerivation {
 
   src = fetchurl {
     url = "ftp://sources.redhat.com/pub/lvm2/releases/LVM2.${v}.tgz";
-    md5 = "9629cf5728544d7e637cafde1f73d777";
+    sha256 = "0nr833bl0q4zq52drjxmmpf7bs6kqxwa5kahwwxm9411khkxz0vc";
   };
 
   configureFlags =
@@ -29,6 +29,8 @@ stdenv.mkDerivation {
       sed -i /DEFAULT_PROFILE_DIR/d conf/Makefile.in
     '';
 
+  enableParallelBuilding = true;
+
   #patches = [ ./purity.patch ];
 
   # To prevent make install from failing.
diff --git a/pkgs/os-specific/linux/lxc/default.nix b/pkgs/os-specific/linux/lxc/default.nix
index 5a9b3587870..12305687c29 100644
--- a/pkgs/os-specific/linux/lxc/default.nix
+++ b/pkgs/os-specific/linux/lxc/default.nix
@@ -3,21 +3,25 @@
 }:
 
 stdenv.mkDerivation rec {
-  name = "lxc-1.0.0.alpha1-92-g8111adf";
+  name = "lxc-1.0.3";
 
   src = fetchurl {
     url = "http://github.com/lxc/lxc/archive/${name}.tar.gz";
-    sha256 = "05hjrn79wyjnm4ynf8y0j7pk2hwfrzp4dzwynxq4z2wxlc1ficd5";
+    sha256 = "04k45jgj2i501yhm467s1a1yk7h7q0fjhspys158w1a2m1hari4z";
   };
 
   buildInputs = [ libcap apparmor perl docbook2x gnutls autoreconfHook pkgconfig ];
 
   patches = [ ./install-localstatedir-in-store.patch ./support-db2x.patch ];
 
-  preConfigure = "export XML_CATALOG_FILES=${docbook_xml_dtd_45}/xml/dtd/docbook/catalog.xml";
+  preConfigure = ''
+    export XML_CATALOG_FILES=${docbook_xml_dtd_45}/xml/dtd/docbook/catalog.xml
+    substituteInPlace doc/rootfs/Makefile.am --replace '@LXCROOTFSMOUNT@' '$out/lib/lxc/rootfs'
+  '';
 
   configureFlags = [
     "--localstatedir=/var"
+    "--with-rootfs-path=/var/lib/lxc/rootfs"
     "--enable-doc"
     "--enable-tests"
     "--enable-apparmor"
diff --git a/pkgs/os-specific/linux/mcelog/default.nix b/pkgs/os-specific/linux/mcelog/default.nix
index b60b6134fdd..463722d2c96 100644
--- a/pkgs/os-specific/linux/mcelog/default.nix
+++ b/pkgs/os-specific/linux/mcelog/default.nix
@@ -10,7 +10,7 @@
 let
 
   rev = "7fa99818367a6d17014b36d6f918ad848cbe7ce2";
-  version = "1.0pre-${rev}"; 
+  version = "1.0pre-${stdenv.lib.strings.substring 0 7 rev}"; 
   sha256 = "15eea3acd76190c7922c71028b31963221a2eefd8afa713879e191a26bc22ae7";
 
 in stdenv.mkDerivation {
@@ -26,7 +26,7 @@ in stdenv.mkDerivation {
   makeFlags = "prefix=$(out) etcprefix=$(out) DOCDIR=$(out)/share/doc";
 
   preInstall = ''
-    ensureDir $out/share/doc
+    mkdir -p $out/share/doc
   '';
 
   meta = {
diff --git a/pkgs/os-specific/linux/mdadm/default.nix b/pkgs/os-specific/linux/mdadm/default.nix
index 1653c018ce1..48e1c178490 100644
--- a/pkgs/os-specific/linux/mdadm/default.nix
+++ b/pkgs/os-specific/linux/mdadm/default.nix
@@ -1,16 +1,13 @@
 { stdenv, fetchurl, groff }:
 
 stdenv.mkDerivation rec {
-  name = "mdadm-3.1.2";
+  name = "mdadm-3.3";
 
   src = fetchurl {
     url = "mirror://kernel/linux/utils/raid/mdadm/${name}.tar.bz2";
-    sha256 = "0s2d2a01j8cizxqvbgd0sn5bpa1j46q8976078b3jq1q7i1ir0zz";
+    sha256 = "0igdqflihiq1dp5qlypzw0xfl44f4n3bckl7r2x2wfgkplcfa1ww";
   };
 
-  # Enable incremental activation of swraid arrays from udev.
-  patches = [ ./udev.patch ];
-
   nativeBuildInputs = [ groff ];
 
   preConfigure = "sed -e 's@/lib/udev@\${out}/lib/udev@' -e 's@ -Werror @ @' -i Makefile";
@@ -19,7 +16,7 @@ stdenv.mkDerivation rec {
   # /dev/.mdadm/map as a fallback).
   preBuild =
     ''
-      makeFlagsArray=(INSTALL=install BINDIR=$out/sbin MANDIR=$out/share/man VAR_RUN=/var/run/mdadm ALT_RUN=/dev/.mdadm)
+      makeFlagsArray=(INSTALL=install BINDIR=$out/sbin MANDIR=$out/share/man RUN_DIR=/dev/.mdadm)
       if [[ -n "$crossConfig" ]]; then
         makeFlagsArray+=(CROSS_COMPILE=$crossConfig-)
       fi
diff --git a/pkgs/os-specific/linux/mdadm/udev.patch b/pkgs/os-specific/linux/mdadm/udev.patch
deleted file mode 100644
index 5eb35f0c584..00000000000
--- a/pkgs/os-specific/linux/mdadm/udev.patch
+++ /dev/null
@@ -1,20 +0,0 @@
-diff --exclude '*~' -rc mdadm-3.1.2-orig/udev-md-raid.rules mdadm-3.1.2/udev-md-raid.rules
-*** mdadm-3.1.2-orig/udev-md-raid.rules	2010-02-22 21:14:58.000000000 +0100
---- mdadm-3.1.2/udev-md-raid.rules	2010-05-16 20:45:22.000000000 +0200
-***************
-*** 5,11 ****
-  ACTION=="change", GOTO="md_no_incr"
-  
-  # import data from a raid member and activate it
-! #ENV{ID_FS_TYPE}=="linux_raid_member", IMPORT{program}="/sbin/mdadm --examine --export $tempnode", RUN+="/sbin/mdadm --incremental $env{DEVNAME}"
-  # import data from a raid set
-  LABEL="md_no_incr"
-  KERNEL!="md*", GOTO="md_end"
---- 5,11 ----
-  ACTION=="change", GOTO="md_no_incr"
-  
-  # import data from a raid member and activate it
-! ENV{ID_FS_TYPE}=="linux_raid_member", IMPORT{program}="/sbin/mdadm --examine --export $tempnode", RUN+="/sbin/mdadm --incremental $env{DEVNAME}"
-  # import data from a raid set
-  LABEL="md_no_incr"
-  KERNEL!="md*", GOTO="md_end"
diff --git a/pkgs/os-specific/linux/microcode/converter.nix b/pkgs/os-specific/linux/microcode/converter.nix
index 49babc6ca57..da4d9677217 100644
--- a/pkgs/os-specific/linux/microcode/converter.nix
+++ b/pkgs/os-specific/linux/microcode/converter.nix
@@ -18,7 +18,7 @@ stdenv.mkDerivation {
   '';
 
   installPhase = ''
-    ensureDir "$out/bin"
+    mkdir -p "$out/bin"
     cp intel-microcode2ucode "$out/bin/"
   '';
 
diff --git a/pkgs/os-specific/linux/microcode/intel.nix b/pkgs/os-specific/linux/microcode/intel.nix
index d96a4943625..b72194548e0 100644
--- a/pkgs/os-specific/linux/microcode/intel.nix
+++ b/pkgs/os-specific/linux/microcode/intel.nix
@@ -1,13 +1,13 @@
 { stdenv, fetchurl, microcode2ucode }:
 
-let version = "20130906"; in
+let version = "20140624"; in
 
 stdenv.mkDerivation {
   name = "microcode-intel-${version}";
 
   src = fetchurl {
-    url = "http://downloadmirror.intel.com/23166/eng/microcode-${version}.tgz";
-    sha256 = "11k327icvijadq2zkgkc3sqwzraip9cviqm25566g09523ds0svv";
+    url = "http://downloadmirror.intel.com/23984/eng/microcode-${version}.tgz";
+    sha256 = "0dza0bdlx7q88yhnynvfgkrhgf7ycrq6mlp6hwnpp2j3h33jlrml";
   };
 
   buildInputs = [ microcode2ucode ];
diff --git a/pkgs/os-specific/linux/musl/default.nix b/pkgs/os-specific/linux/musl/default.nix
new file mode 100644
index 00000000000..97407c887ce
--- /dev/null
+++ b/pkgs/os-specific/linux/musl/default.nix
@@ -0,0 +1,24 @@
+{ stdenv, fetchurl }:
+
+stdenv.mkDerivation rec {
+  name    = "musl-${version}";
+  version = "1.1.4";
+
+  src = fetchurl {
+    url    = "http://www.musl-libc.org/releases/${name}.tar.gz";
+    sha256 = "1kgmi17zpzgjhywmmqxazj8qsx8cf9siwa65jqd2i6rs7jnnb335";
+  };
+
+  enableParallelBuilding = true;
+  configurePhase = ''
+    ./configure --enable-shared --enable-static --prefix=$out --syslibdir=$out/lib
+  '';
+
+  meta = {
+    description = "An efficient, small, quality libc implementation";
+    homepage    = "http://www.musl-libc.org";
+    license     = stdenv.lib.licenses.mit;
+    platforms   = stdenv.lib.platforms.linux;
+    maintainers = [ stdenv.lib.maintainers.thoughtpolice ];
+  };
+}
diff --git a/pkgs/os-specific/linux/ndiswrapper/default.nix b/pkgs/os-specific/linux/ndiswrapper/default.nix
index e2db1a4106b..f95de433564 100644
--- a/pkgs/os-specific/linux/ndiswrapper/default.nix
+++ b/pkgs/os-specific/linux/ndiswrapper/default.nix
@@ -1,14 +1,17 @@
-{ stdenv, fetchurl, kernelDev, perl }:
+{ stdenv, fetchurl, kernel, perl, kmod }:
 
 stdenv.mkDerivation {
-  name = "ndiswrapper-1.56-${kernelDev.version}";
+  name = "ndiswrapper-1.59-${kernel.version}";
+
+  patches = [ ./no-sbin.patch ];
 
   # need at least .config and include 
-  kernel = kernelDev;
+  kernel = kernel.dev;
 
   buildPhase = "
     echo make KBUILD=$(echo \$kernel/lib/modules/*/build);
     echo -n $kernel/lib/modules/*/build > kbuild_path
+    export PATH=${kmod}/sbin:$PATH
     make KBUILD=$(echo \$kernel/lib/modules/*/build);
   ";
 
@@ -23,14 +26,11 @@ stdenv.mkDerivation {
 
   # should we use unstable? 
   src = fetchurl {
-    url = mirror://sourceforge/ndiswrapper/ndiswrapper-1.56.tar.gz;
-    sha256 = "10yqg1a08v6z1qm1qr1v4rbhl35c90gzrazapr09vp372hky8f57";
+    url = mirror://sourceforge/ndiswrapper/ndiswrapper-1.59.tar.gz;
+    sha256 = "1g6lynccyg4m7gd7vhy44pypsn8ifmibq6rqgvc672pwngzx79b6";
   };
 
-  buildInputs = [ kernelDev perl ];
-
-  # this is a patch against svn head, not stable version
-  patches = [./prefix.patch];
+  buildInputs = [ perl ];
 
   meta = { 
     description = "Ndis driver wrapper for the Linux kernel";
diff --git a/pkgs/os-specific/linux/ndiswrapper/no-sbin.patch b/pkgs/os-specific/linux/ndiswrapper/no-sbin.patch
new file mode 100644
index 00000000000..cfc048d772b
--- /dev/null
+++ b/pkgs/os-specific/linux/ndiswrapper/no-sbin.patch
@@ -0,0 +1,12 @@
+diff -Naur ndiswrapper-1.59-orig/driver/Makefile ndiswrapper-1.59/driver/Makefile
+--- ndiswrapper-1.59-orig/driver/Makefile	2013-11-28 14:42:35.000000000 -0500
++++ ndiswrapper-1.59/driver/Makefile	2014-01-04 18:31:43.242377375 -0500
+@@ -191,7 +191,7 @@
+ 	rm -rf .tmp_versions
+ 
+ install: config_check $(MODULE)
+-	@/sbin/modinfo $(MODULE) | grep -q "^vermagic: *$(KVERS) " || \
++	@modinfo $(MODULE) | grep -q "^vermagic: *$(KVERS) " || \
+ 		{ echo "$(MODULE)" is not for Linux $(KVERS); exit 1; }
+ 	mkdir -p -m 755 $(DESTDIR)$(INST_DIR)
+ 	install -m 0644 $(MODULE) $(DESTDIR)$(INST_DIR)
diff --git a/pkgs/os-specific/linux/ndiswrapper/prefix.patch b/pkgs/os-specific/linux/ndiswrapper/prefix.patch
deleted file mode 100644
index ec77f4cae79..00000000000
--- a/pkgs/os-specific/linux/ndiswrapper/prefix.patch
+++ /dev/null
@@ -1,66 +0,0 @@
-diff -r -u ndiswrapper-1.53/driver/loader.c ndiswrapper-1.53/driver/loader.c
---- ndiswrapper-1.53/driver/loader.c	2008-05-28 06:54:08.000000000 +0400
-+++ ndiswrapper-1.53/driver/loader.c	2008-06-15 17:05:07.000000000 +0400
-@@ -100,7 +100,7 @@
- 			EXIT1(return NULL);
- 		}
- 		INIT_COMPLETION(loader_complete);
--		ret = call_usermodehelper("/sbin/loadndisdriver", argv, env, 1);
-+		ret = call_usermodehelper(USERMOD_HELPER, argv, env, 1);
- 		if (ret) {
- 			up(&loader_mutex);
- 			ERROR("couldn't load driver %s; check system log "
-@@ -262,7 +262,7 @@
- 			EXIT1(return NULL);
- 		}
- 		INIT_COMPLETION(loader_complete);
--		ret = call_usermodehelper("/sbin/loadndisdriver", argv, env, 1);
-+		ret = call_usermodehelper(USERMOD_HELPER, argv, env, 1);
- 		if (ret) {
- 			up(&loader_mutex);
- 			ERROR("couldn't load file %s/%s; check system log "
-@@ -698,7 +698,7 @@
- 			EXIT1(return NULL);
- 		}
- 		INIT_COMPLETION(loader_complete);
--		ret = call_usermodehelper("/sbin/loadndisdriver", argv, env, 1);
-+		ret = call_usermodehelper(USERMOD_HELPER, argv, env, 1);
- 		if (ret) {
- 			up(&loader_mutex);
- 			TRACE1("couldn't load device %04x:%04x; check system "
-diff -r -u ndiswrapper-1.53/driver/Makefile ndiswrapper-1.53/driver/Makefile
---- ndiswrapper-1.53/driver/Makefile	2008-05-28 06:54:08.000000000 +0400
-+++ ndiswrapper-1.53/driver/Makefile	2008-06-15 17:03:31.000000000 +0400
-@@ -95,6 +95,10 @@
- EXTRA_CFLAGS += -DWRAP_PREEMPT
- endif
- 
-+ifdef DIST_DESTDIR
-+EXTRA_CFLAGS += -DPREFIX=\"$(DIST_DESTDIR)\"
-+endif
-+
- OBJS = crt.o hal.o iw_ndis.o loader.o ndis.o ntoskernel.o ntoskernel_io.o \
- 	pe_linker.o pnp.o proc.o rtl.o wrapmem.o wrapndis.o wrapper.o
- 
-diff -r -u ndiswrapper-1.53/driver/ndiswrapper.h ndiswrapper-1.53/driver/ndiswrapper.h
---- ndiswrapper-1.53/driver/ndiswrapper.h	2008-05-28 06:54:08.000000000 +0400
-+++ ndiswrapper-1.53/driver/ndiswrapper.h	2008-06-15 17:06:37.000000000 +0400
-@@ -19,8 +19,17 @@
- #define DRIVER_VERSION "1.53"
- #define UTILS_VERSION "1.9"
- 
-+#ifndef PREFIX
-+#define PREFIX
-+#endif
-+
- #define DRIVER_NAME "ndiswrapper"
--#define DRIVER_CONFIG_DIR "/etc/ndiswrapper"
-+
-+#ifndef DRIVER_CONFIG_DIR
-+#  define DRIVER_CONFIG_DIR PREFIX "/etc/ndiswrapper"
-+#endif
-+
-+#define USERMOD_HELPER PREFIX "/sbin/loadndisdriver"
- 
- #define SSID_MAX_WPA_IE_LEN 40
- #define NDIS_ESSID_MAX_SIZE 32
diff --git a/pkgs/os-specific/linux/net-tools/default.nix b/pkgs/os-specific/linux/net-tools/default.nix
index 9386b50969f..76f4661ecfc 100644
--- a/pkgs/os-specific/linux/net-tools/default.nix
+++ b/pkgs/os-specific/linux/net-tools/default.nix
@@ -18,7 +18,7 @@ stdenv.mkDerivation rec {
   meta = {
     homepage = http://www.tazenda.demon.co.uk/phil/net-tools/;
     description = "A set of tools for controlling the network subsystem in Linux";
-    license = "GPLv2+";
+    license = stdenv.lib.licenses.gpl2Plus;
     platforms = stdenv.lib.platforms.linux;
   };
 }
diff --git a/pkgs/os-specific/linux/netatop/default.nix b/pkgs/os-specific/linux/netatop/default.nix
index 9a34c503f6d..c77faa6a9e7 100644
--- a/pkgs/os-specific/linux/netatop/default.nix
+++ b/pkgs/os-specific/linux/netatop/default.nix
@@ -1,7 +1,7 @@
-{ stdenv, fetchurl, kernelDev, zlib }:
+{ stdenv, fetchurl, kernel, zlib }:
 
 stdenv.mkDerivation {
-  name = "netatop-${kernelDev.version}-0.3";
+  name = "netatop-${kernel.version}-0.3";
 
   src = fetchurl {
     url = http://www.atoptool.nl/download/netatop-0.3.tar.gz;
@@ -12,9 +12,9 @@ stdenv.mkDerivation {
 
   preConfigure = ''
     patchShebangs mkversion
-    sed -i -e 's,^KERNDIR.*,KERNDIR=${kernelDev}/lib/modules/${kernelDev.modDirVersion}/build,' \
+    sed -i -e 's,^KERNDIR.*,KERNDIR=${kernel.dev}/lib/modules/${kernel.modDirVersion}/build,' \
         */Makefile
-    sed -i -e 's,/lib/modules.*extra,'$out'/lib/modules/${kernelDev.modDirVersion}/extra,' \
+    sed -i -e 's,/lib/modules.*extra,'$out'/lib/modules/${kernel.modDirVersion}/extra,' \
         -e s,/usr,$out, \
         -e /init.d/d \
         -e /depmod/d \
@@ -22,14 +22,14 @@ stdenv.mkDerivation {
   '';
 
   preInstall = ''
-    ensureDir $out/bin $out/sbin $out/share/man/man{4,8}
-    ensureDir $out/lib/modules/${kernelDev.modDirVersion}/extra
+    mkdir -p $out/bin $out/sbin $out/share/man/man{4,8}
+    mkdir -p $out/lib/modules/${kernel.modDirVersion}/extra
   '';
       
   meta = {
     description = "Network monitoring module for atop";
     homepage = http://www.atoptool.nl/downloadnetatop.php;
-    license = "GPL2";
+    license = stdenv.lib.licenses.gpl2;
     platforms = stdenv.lib.platforms.linux;
     maintainers = with stdenv.lib.maintainers; [viric];
   };
diff --git a/pkgs/os-specific/linux/nfs-utils/default.nix b/pkgs/os-specific/linux/nfs-utils/default.nix
index 42bacd41be0..bb85acf4dcb 100644
--- a/pkgs/os-specific/linux/nfs-utils/default.nix
+++ b/pkgs/os-specific/linux/nfs-utils/default.nix
@@ -54,7 +54,7 @@ stdenv.mkDerivation rec {
     '';
 
     homepage = http://nfs.sourceforge.net/;
-    license = "GPLv2";
+    license = stdenv.lib.licenses.gpl2;
 
     platforms = stdenv.lib.platforms.linux;
     maintainers = [ stdenv.lib.maintainers.ludo ];
diff --git a/pkgs/os-specific/linux/nvidia-x11/builder-legacy.sh b/pkgs/os-specific/linux/nvidia-x11/builder-legacy.sh
index 6062566cbfb..7d39dd31189 100755
--- a/pkgs/os-specific/linux/nvidia-x11/builder-legacy.sh
+++ b/pkgs/os-specific/linux/nvidia-x11/builder-legacy.sh
@@ -29,11 +29,10 @@ buildPhase() {
 
         # Create the module.
         kernelVersion=$(cd $kernel/lib/modules && ls)
-        sysSrc=$(echo $kernel/lib/modules/$kernelVersion/build/)
+        sysSource=$(echo $kernel/lib/modules/$kernelVersion/source)
+        sysOut=$(echo $kernel/lib/modules/$kernelVersion/build)
         unset src # used by the nv makefile
-        # Hack necessary to compile on 2.6.28.
-        export NIX_CFLAGS_COMPILE="$NIX_CFLAGS_COMPILE -I$sysSrc/include/asm/mach-default"
-        make SYSSRC=$sysSrc module
+        make SYSSRC=$sysSource SYSOUT=$sysOut module
         cd ../../..
     fi
 }
diff --git a/pkgs/os-specific/linux/nvidia-x11/builder-legacy304.sh b/pkgs/os-specific/linux/nvidia-x11/builder-legacy304.sh
index bb8beab29c5..7771fb988f5 100755
--- a/pkgs/os-specific/linux/nvidia-x11/builder-legacy304.sh
+++ b/pkgs/os-specific/linux/nvidia-x11/builder-legacy304.sh
@@ -14,11 +14,10 @@ buildPhase() {
         echo "Building linux driver against kernel: $kernel";
         cd kernel
         kernelVersion=$(cd $kernel/lib/modules && ls)
-        sysSrc=$(echo $kernel/lib/modules/$kernelVersion/build/)
+        sysSrc=$(echo $kernel/lib/modules/$kernelVersion/source)
+        sysOut=$(echo $kernel/lib/modules/$kernelVersion/build)
         unset src # used by the nv makefile
-        # Hack necessary to compile on 2.6.28.
-        export NIX_CFLAGS_COMPILE="$NIX_CFLAGS_COMPILE -I$sysSrc/include/asm/mach-default -I$sysSrc/include/generated"
-        make SYSSRC=$sysSrc module
+        make SYSSRC=$sysSrc SYSOUT=$sysOut module
         cd ..
     fi
 }
diff --git a/pkgs/os-specific/linux/nvidia-x11/builder.sh b/pkgs/os-specific/linux/nvidia-x11/builder.sh
index 28e2bd5642c..4291116f4ef 100755
--- a/pkgs/os-specific/linux/nvidia-x11/builder.sh
+++ b/pkgs/os-specific/linux/nvidia-x11/builder.sh
@@ -16,11 +16,13 @@ buildPhase() {
         echo "Building linux driver against kernel: $kernel";
         cd kernel
         kernelVersion=$(cd $kernel/lib/modules && ls)
-        sysSrc=$(echo $kernel/lib/modules/$kernelVersion/build/)
+        sysSrc=$(echo $kernel/lib/modules/$kernelVersion/source)
+        sysOut=$(echo $kernel/lib/modules/$kernelVersion/build)
         unset src # used by the nv makefile
-        # Hack necessary to compile on 2.6.28.
-        export NIX_CFLAGS_COMPILE="$NIX_CFLAGS_COMPILE -I$sysSrc/include/asm/mach-default -I$sysSrc/include/generated"
-        make SYSSRC=$sysSrc module
+        make SYSSRC=$sysSrc SYSOUT=$sysOut module
+        cd uvm
+        make SYSSRC=$sysSrc SYSOUT=$sysOut module
+        cd ..
         cd ..
     fi
 }
@@ -28,35 +30,11 @@ buildPhase() {
 
 installPhase() {
 
-    # Install libGL and friends.
-    mkdir -p $out/lib/vendors
-
-    for f in \
-      libcuda libGL libnvcuvid libnvidia-cfg libnvidia-compiler \
-      libnvidia-encode libnvidia-glcore libnvidia-ml libnvidia-opencl \
-      libnvidia-tls libOpenCL libnvidia-tls libvdpau_nvidia
-    do
-      cp -prd $f.* $out/lib/
-      ln -snf $f.so.$versionNumber $out/lib/$f.so
-      ln -snf $f.so.$versionNumber $out/lib/$f.so.1
-    done
-
-    cp -p nvidia.icd $out/lib/vendors/
-    cp -prd tls $out/lib/
-    cp -prd libOpenCL.so.1.0.0 $out/lib/
-    ln -snf libOpenCL.so.1.0.0 $out/lib/libOpenCL.so
-    ln -snf libOpenCL.so.1.0.0 $out/lib/libOpenCL.so.1
-
-    patchelf --set-rpath $out/lib:$glPath $out/lib/libGL.so.*.*
-    patchelf --set-rpath $out/lib:$glPath $out/lib/libvdpau_nvidia.so.*.*
-    patchelf --set-rpath $cudaPath $out/lib/libcuda.so.*.*
-    patchelf --set-rpath $openclPath $out/lib/libnvidia-opencl.so.*.*
-
     if test -z "$libsOnly"; then
-
         # Install the kernel module.
         mkdir -p $out/lib/modules/$kernelVersion/misc
         cp kernel/nvidia.ko $out/lib/modules/$kernelVersion/misc
+        cp kernel/uvm/nvidia-uvm.ko $out/lib/modules/$kernelVersion/misc
 
         # Install the X driver.
         mkdir -p $out/lib/xorg/modules
@@ -66,18 +44,15 @@ installPhase() {
         mkdir -p $out/lib/xorg/modules/extensions
         cp -p libglx.so.* $out/lib/xorg/modules/extensions
 
-        ln -snf libnvidia-wfb.so.$versionNumber $out/lib/xorg/modules/libnvidia-wfb.so.1
-        ln -snf libglx.so.$versionNumber $out/lib/xorg/modules/extensions/libglx.so
-
-        patchelf --set-rpath $out/lib $out/lib/xorg/modules/extensions/libglx.so.*.*
+        #patchelf --set-rpath $out/lib $out/lib/xorg/modules/extensions/libglx.so.*.*
 
         # Install the programs.
         mkdir -p $out/bin
 
-        for i in nvidia-settings nvidia-smi nvidia-xconfig; do
-	    cp $i $out/bin/$i
-	    patchelf --interpreter "$(cat $NIX_GCC/nix-support/dynamic-linker)" \
-	        --set-rpath $out/lib:$programPath:$glPath $out/bin/$i
+        for i in nvidia-settings nvidia-smi; do
+            cp $i $out/bin/$i
+            patchelf --interpreter "$(cat $NIX_GCC/nix-support/dynamic-linker)" \
+                --set-rpath $out/lib:$programPath:$glPath $out/bin/$i
         done
 
         # Header files etc.
@@ -86,6 +61,7 @@ installPhase() {
 
         mkdir -p $out/share/man/man1
         cp -p *.1.gz $out/share/man/man1
+        rm $out/share/man/man1/nvidia-xconfig.1.gz
 
         mkdir -p $out/share/applications
         cp -p *.desktop $out/share/applications
@@ -97,7 +73,34 @@ installPhase() {
         substituteInPlace $out/share/applications/nvidia-settings.desktop \
             --replace '__UTILS_PATH__' $out/bin \
             --replace '__PIXMAP_PATH__' $out/share/pixmaps
+
+        # Test a bit.
+        $out/bin/nvidia-settings --version
     fi
+
+
+    # Install libGL and friends.
+    mkdir -p "$out/lib/vendors"
+    cp -p nvidia.icd $out/lib/vendors/
+
+    cp -prd *.so.* tls "$out/lib/"
+    rm "$out"/lib/lib{glx,nvidia-wfb}.so.* # handled separately
+
+    for libname in `find "$out/lib/" -name '*.so.*'`
+    do
+      # I'm lazy to differentiate needed libs per-library, as the closure is the same.
+      # Unfortunately --shrink-rpath would strip too much.
+      patchelf --set-rpath "$out/lib:$allLibPath" "$libname"
+
+      libname_short=`echo -n "$libname" | sed 's/so\..*/so/'`
+      ln -srnf "$libname" "$libname_short"
+      ln -srnf "$libname" "$libname_short.1"
+    done
+
+    #patchelf --set-rpath $out/lib:$glPath $out/lib/libGL.so.*.*
+    #patchelf --set-rpath $out/lib:$glPath $out/lib/libvdpau_nvidia.so.*.*
+    #patchelf --set-rpath $cudaPath $out/lib/libcuda.so.*.*
+    #patchelf --set-rpath $openclPath $out/lib/libnvidia-opencl.so.*.*
 }
 
 
diff --git a/pkgs/os-specific/linux/nvidia-x11/default.nix b/pkgs/os-specific/linux/nvidia-x11/default.nix
index 35595a7b8f4..c89846db72c 100644
--- a/pkgs/os-specific/linux/nvidia-x11/default.nix
+++ b/pkgs/os-specific/linux/nvidia-x11/default.nix
@@ -1,4 +1,4 @@
-{ stdenv, fetchurl, kernelDev ? null, xlibs, zlib, perl
+{ stdenv, fetchurl, kernel ? null, xlibs, zlib, perl
 , gtk, atk, pango, glib, gdk_pixbuf
 , # Whether to build the libraries only (i.e. not the kernel module or
   # nvidia-settings).  Used to support 32-bit binaries on 64-bit
@@ -8,55 +8,54 @@
 
 with stdenv.lib;
 
+assert (!libsOnly) -> kernel != null;
+
 let
 
-  versionNumber = "319.60";
+  versionNumber = "340.32";
 
+  inherit (stdenv.lib) makeLibraryPath;
 in
 
 stdenv.mkDerivation {
-  name = "nvidia-x11-${versionNumber}${optionalString (!libsOnly) "-${kernelDev.version}"}";
+  name = "nvidia-x11-${versionNumber}${optionalString (!libsOnly) "-${kernel.version}"}";
 
   builder = ./builder.sh;
 
-  patches =
-    [ ./version-test.patch ]
-    ++ optional (!libsOnly && versionAtLeast kernelDev.version "3.11") ./nvidia-drivers-linux-3.11-incremental.patch
-    ;
-
   src =
     if stdenv.system == "i686-linux" then
       fetchurl {
         url = "http://us.download.nvidia.com/XFree86/Linux-x86/${versionNumber}/NVIDIA-Linux-x86-${versionNumber}.run";
-        sha256 = "0kjidkwd2b5aik74663mxk3ffq4a3fmaybq2aq1lcbfhvvh49j6j";
+        sha256 = "1xcm8czz4bmnlzkl3al58flw6jmbrg1y77cxjjdjqcsvbk1qj10x";
       }
     else if stdenv.system == "x86_64-linux" then
       fetchurl {
         url = "http://us.download.nvidia.com/XFree86/Linux-x86_64/${versionNumber}/NVIDIA-Linux-x86_64-${versionNumber}-no-compat32.run";
-        sha256 = "0fhrxcfsw2jaycnz9gr04c9w585wydx8kpm6rjjbw19wkf8hlq3z";
+        sha256 = "1nfrpx73817y1z0wkqqh02xjg65r0f05h9801mqm8ki2gxqv9vq0";
       }
     else throw "nvidia-x11 does not support platform ${stdenv.system}";
 
   inherit versionNumber libsOnly;
 
-  kernel = if libsOnly then null else kernelDev;
+  kernel = if libsOnly then null else kernel.dev;
 
   dontStrip = true;
 
-  glPath = stdenv.lib.makeLibraryPath [xlibs.libXext xlibs.libX11 xlibs.libXrandr];
-
-  cudaPath = stdenv.lib.makeLibraryPath [zlib stdenv.gcc.gcc];
-
-  openclPath = stdenv.lib.makeLibraryPath [zlib];
+  glPath      = makeLibraryPath [xlibs.libXext xlibs.libX11 xlibs.libXrandr];
+  cudaPath    = makeLibraryPath [zlib stdenv.gcc.gcc];
+  openclPath  = makeLibraryPath [zlib];
+  allLibPath  = makeLibraryPath [xlibs.libXext xlibs.libX11 xlibs.libXrandr zlib stdenv.gcc.gcc];
 
-  programPath = optionalString (!libsOnly) (stdenv.lib.makeLibraryPath
+  programPath = optionalString (!libsOnly) (makeLibraryPath
     [ gtk atk pango glib gdk_pixbuf xlibs.libXv ] );
 
   buildInputs = [ perl ];
 
-  meta = {
+  meta = with stdenv.lib.meta; {
     homepage = http://www.nvidia.com/object/unix.html;
     description = "X.org driver and kernel module for NVIDIA graphics cards";
-    license = stdenv.lib.licenses.unfreeRedistributable;
+    license = licenses.unfreeRedistributable;
+    platforms = platforms.linux;
+    maintainers = [ maintainers.vcunat ];
   };
 }
diff --git a/pkgs/os-specific/linux/nvidia-x11/legacy173.nix b/pkgs/os-specific/linux/nvidia-x11/legacy173.nix
index a03e3d4ca7e..0014a5d2ee5 100644
--- a/pkgs/os-specific/linux/nvidia-x11/legacy173.nix
+++ b/pkgs/os-specific/linux/nvidia-x11/legacy173.nix
@@ -1,13 +1,13 @@
-{stdenv, fetchurl, kernelDev, xlibs, zlib, gtk, atk, pango, glib, gdk_pixbuf}:
+{stdenv, fetchurl, kernel, xlibs, zlib, gtk, atk, pango, glib, gdk_pixbuf}:
 
 let 
 
-  versionNumber = "173.14.36";
+  versionNumber = "173.14.39";
 
 in
 
 stdenv.mkDerivation {
-  name = "nvidia-x11-${versionNumber}-${kernelDev.version}";
+  name = "nvidia-x11-${versionNumber}-${kernel.version}";
   
   builder = ./builder-legacy.sh;
   
@@ -15,16 +15,16 @@ stdenv.mkDerivation {
     if stdenv.system == "i686-linux" then
       fetchurl {
         url = "http://us.download.nvidia.com/XFree86/Linux-x86/${versionNumber}/NVIDIA-Linux-x86-${versionNumber}-pkg0.run";
-        sha256 = "19wnikms9wradf1kmaywnp7hykrdm4xqz2ka7az66s3ma096y95c";
+        sha256 = "08xb7s7cxmj4zv4i3645kjhlhhwxiq6km9ixmsw3vv91f7rkb6d0";
       }
     else if stdenv.system == "x86_64-linux" then
       fetchurl {
         url = "http://us.download.nvidia.com/XFree86/Linux-x86_64/${versionNumber}/NVIDIA-Linux-x86_64-${versionNumber}-pkg0.run";
-        sha256 = "1xf1w6qvqw0a3vd807hp3cgqmzm1wkpz2by52p0qgpjqld421k2s";
+        sha256 = "1p2ls0xj81l8v4n6dbjj3p5wlw1iyhgzyvqcv4h5fdxhhs2cb3md";
       }
     else throw "nvidia-x11 does not support platform ${stdenv.system}";
 
-  kernel = kernelDev;
+  kernel = kernel.dev;
 
   inherit versionNumber;
 
@@ -39,6 +39,6 @@ stdenv.mkDerivation {
   meta = {
     homepage = http://www.nvidia.com/object/unix.html;
     description = "X.org driver and kernel module for Legacy NVIDIA graphics cards";
-    license = "unfree";
+    license = stdenv.lib.licenses.unfree;
   };
 }
diff --git a/pkgs/os-specific/linux/nvidia-x11/legacy304.nix b/pkgs/os-specific/linux/nvidia-x11/legacy304.nix
index e2739b291d4..9acaee797f0 100644
--- a/pkgs/os-specific/linux/nvidia-x11/legacy304.nix
+++ b/pkgs/os-specific/linux/nvidia-x11/legacy304.nix
@@ -1,4 +1,4 @@
-{ stdenv, fetchurl, kernelDev ? null, xlibs, zlib, perl
+{ stdenv, fetchurl, kernel ? null, xlibs, zlib, perl
 , gtk, atk, pango, glib, gdk_pixbuf
 , # Whether to build the libraries only (i.e. not the kernel module or
   # nvidia-settings).  Used to support 32-bit binaries on 64-bit
@@ -8,10 +8,10 @@
 
 with stdenv.lib;
 
-let versionNumber = "304.84"; in
+let versionNumber = "304.123"; in
 
 stdenv.mkDerivation {
-  name = "nvidia-x11-${versionNumber}${optionalString (!libsOnly) "-${kernelDev.version}"}";
+  name = "nvidia-x11-${versionNumber}${optionalString (!libsOnly) "-${kernel.version}"}";
 
   builder = ./builder-legacy304.sh;
 
@@ -19,18 +19,18 @@ stdenv.mkDerivation {
     if stdenv.system == "i686-linux" then
       fetchurl {
         url = "http://us.download.nvidia.com/XFree86/Linux-x86/${versionNumber}/NVIDIA-Linux-x86-${versionNumber}.run";
-        sha256 = "14hfx3rhf3vf3x3klkhz5qkjrg51r22nqqdzffilcwkxdjfg10j1";
+        sha256 = "09gljwxw14img7hw0xdxd24cvpvlymdxssmxa9gikdrw2w04j0ym";
       }
     else if stdenv.system == "x86_64-linux" then
       fetchurl {
         url = "http://us.download.nvidia.com/XFree86/Linux-x86_64/${versionNumber}/NVIDIA-Linux-x86_64-${versionNumber}-no-compat32.run";
-        sha256 = "1ixxkykl78g874g537apvxalggp3kw0mm5q69rl99jlw6jibbm80";
+        sha256 = "0vxw4gp78g06h5inwkhl989p9mq0m8rqipz9a67rdc4s364r243s";
       }
     else throw "nvidia-x11 does not support platform ${stdenv.system}";
 
   inherit versionNumber libsOnly;
 
-  kernel = if libsOnly then null else kernelDev;
+  kernel = if libsOnly then null else kernel.dev;
 
   dontStrip = true;
 
@@ -46,6 +46,6 @@ stdenv.mkDerivation {
   meta = {
     homepage = http://www.nvidia.com/object/unix.html;
     description = "X.org driver and kernel module for NVIDIA graphics cards";
-    license = "unfree";
+    license = stdenv.lib.licenses.unfree;
   };
 }
diff --git a/pkgs/os-specific/linux/nvidia-x11/legacy96.nix b/pkgs/os-specific/linux/nvidia-x11/legacy96.nix
deleted file mode 100644
index 32fc3632b05..00000000000
--- a/pkgs/os-specific/linux/nvidia-x11/legacy96.nix
+++ /dev/null
@@ -1,44 +0,0 @@
-{stdenv, fetchurl, kernelDev, xlibs, zlib, gtk, atk, pango, glib}:
-
-let 
-
-  versionNumber = "96.43.23";
-
-in
-
-stdenv.mkDerivation {
-  name = "nvidia-x11-${versionNumber}-${kernelDev.version}";
-  
-  builder = ./builder-legacy.sh;
-  
-  src =
-    if stdenv.system == "i686-linux" then
-      fetchurl {
-        url = "http://us.download.nvidia.com/XFree86/Linux-x86/${versionNumber}/NVIDIA-Linux-x86-${versionNumber}-pkg0.run";
-        sha256 = "0hi10h26l51mknr57zsdg0zaxcqdz1lp3hsz0hi1c1vkpbsavrji";
-      }
-    else if stdenv.system == "x86_64-linux" then
-      fetchurl {
-        url = "http://us.download.nvidia.com/XFree86/Linux-x86_64/${versionNumber}/NVIDIA-Linux-x86_64-${versionNumber}-pkg0.run";
-        sha256 = "09vynha40rsxpklj1m0qjfg853ckdpi9g87h06irikh405x57kzp";
-      }
-    else throw "nvidia-x11 does not support platform ${stdenv.system}";
-
-  kernel = kernelDev;
-
-  inherit versionNumber;
-
-  dontStrip = true;
-
-  glPath = stdenv.lib.makeLibraryPath [xlibs.libXext xlibs.libX11 xlibs.libXrandr];
-
-  cudaPath = stdenv.lib.makeLibraryPath [zlib stdenv.gcc.gcc];
-
-  programPath = stdenv.lib.makeLibraryPath [ gtk atk pango glib xlibs.libXv ];
-
-  meta = {
-    homepage = http://www.nvidia.com/object/unix.html;
-    description = "X.org driver and kernel module for Legacy NVIDIA graphics cards";
-    license = "unfree";
-  };
-}
diff --git a/pkgs/os-specific/linux/nvidia-x11/nvidia-drivers-linux-3.11-incremental.patch b/pkgs/os-specific/linux/nvidia-x11/nvidia-drivers-linux-3.11-incremental.patch
deleted file mode 100644
index bb6fad932e3..00000000000
--- a/pkgs/os-specific/linux/nvidia-x11/nvidia-drivers-linux-3.11-incremental.patch
+++ /dev/null
@@ -1,25 +0,0 @@
-From 8a8647ad942c8ac5161e1335f7f3e9dbb34dbf9e Mon Sep 17 00:00:00 2001
-From: Lukas Elsner <open@mindrunner.de>
-Date: Wed, 17 Jul 2013 01:16:04 +0200
-Subject: [PATCH] replace num_physpages with totalram_pages
-
----
- kernel/nv-linux.h | 2 +-
- 1 file changed, 1 insertion(+), 1 deletion(-)
-
-diff --git a/kernel/nv-linux.h b/kernel/nv-linux.h
-index 4e5ed89..46c51ec 100644
---- a/kernel/nv-linux.h
-+++ b/kernel/nv-linux.h
-@@ -957,7 +957,7 @@ static inline int nv_execute_on_all_cpus(void (*func)(void *info), void *info)
- #endif
- 
- #if !defined(NV_VMWARE)
--#define NV_NUM_PHYSPAGES                num_physpages
-+#define NV_NUM_PHYSPAGES                totalram_pages
- #define NV_GET_CURRENT_PROCESS()        current->tgid
- #define NV_IN_ATOMIC()                  in_atomic()
- #define NV_LOCAL_BH_DISABLE()           local_bh_disable()
--- 
-1.8.3.2
-
diff --git a/pkgs/os-specific/linux/nvidia-x11/version-test.patch b/pkgs/os-specific/linux/nvidia-x11/version-test.patch
deleted file mode 100644
index 9b6908ee5c0..00000000000
--- a/pkgs/os-specific/linux/nvidia-x11/version-test.patch
+++ /dev/null
@@ -1,19 +0,0 @@
-diff -Naur NVIDIA-Linux-x86_64-310.32-no-compat32/kernel/conftest.sh NVIDIA-patched/kernel/conftest.sh
---- NVIDIA-Linux-x86_64-310.32-no-compat32/kernel/conftest.sh	2013-01-14 18:11:17.000000000 -0430
-+++ NVIDIA-patched/kernel/conftest.sh	2013-02-05 14:44:50.757999124 -0430
-@@ -1699,11 +1699,13 @@
-                 # kernel older than 2.6.6, that's all we require to
-                 # build the module.
-                 #
-+                VERSION=$(grep "^VERSION =" $MAKEFILE | cut -d " " -f 3)
-                 PATCHLEVEL=$(grep "^PATCHLEVEL =" $MAKEFILE | cut -d " " -f 3)
-                 SUBLEVEL=$(grep "^SUBLEVEL =" $MAKEFILE | cut -d " " -f 3)
- 
--                if [ -n "$PATCHLEVEL" -a $PATCHLEVEL -ge 6 \
--                        -a -n "$SUBLEVEL" -a $SUBLEVEL -le 5 ]; then
-+                if [ -n "$VERSION" -a -n "$PATCHLEVEL" -a -n "$SUBLEVEL" \
-+                     -a "$VERSION" -ge 3 -o "$VERSION" -eq 2 -a "$PATCHLEVEL" -ge 7 \
-+                     -o "$PATCHLEVEL" -eq 6 -a "$SUBLEVEL" -ge 6 ]; then 
-                     SELECTED_MAKEFILE=Makefile.kbuild
-                     RET=0
-                 fi
diff --git a/pkgs/os-specific/linux/nvidiabl/default.nix b/pkgs/os-specific/linux/nvidiabl/default.nix
new file mode 100644
index 00000000000..6260134bf11
--- /dev/null
+++ b/pkgs/os-specific/linux/nvidiabl/default.nix
@@ -0,0 +1,25 @@
+{ stdenv, fetchurl, kernel }:
+
+stdenv.mkDerivation {
+  name = "nvidiabl-0.85-${kernel.version}";
+
+  src = fetchurl {
+    url = "https://github.com/guillaumezin/nvidiabl/archive/v0.85.tar.gz";
+    sha256 = "1c7ar39wc8jpqh67sw03lwnyp0m9l6dad469ybqrgcywdiwxspwj";
+  };
+
+  preConfigure = ''
+    sed -i 's|/sbin/depmod|#/sbin/depmod|' Makefile
+  '';
+
+  makeFlags = [
+    "KDIR=${kernel.dev}/lib/modules/${kernel.modDirVersion}/build"
+    "DESTDIR=$(out)"
+  ];
+
+  meta = {
+    description = "Linux driver for setting the backlight brightness on laptops using NVIDIA GPU";
+    homepage = https://github.com/guillaumezin/nvidiabl;
+    license = stdenv.lib.licenses.gpl2;
+  };
+}
diff --git a/pkgs/os-specific/linux/open-iscsi/default.nix b/pkgs/os-specific/linux/open-iscsi/default.nix
index 60e0e4d189c..88ab08e6c3d 100644
--- a/pkgs/os-specific/linux/open-iscsi/default.nix
+++ b/pkgs/os-specific/linux/open-iscsi/default.nix
@@ -1,14 +1,15 @@
-{ stdenv, fetchurl, kernelDev}:
-
-stdenv.mkDerivation rec {
-  name = "open-iscsi-2.0-871-${kernelDev.version}";
+{ stdenv, fetchurl, kernel}:
+let
+  pname = "open-iscsi-2.0-871";
+in stdenv.mkDerivation {
+  name = "${pname}-${kernel.version}";
   
   src = fetchurl {
-    url = "http://www.open-iscsi.org/bits/${name}.tar.gz";
+    url = "http://www.open-iscsi.org/bits/${pname}.tar.gz";
     sha256 = "1jvx1agybaj4czhz41bz37as076spicsmlh5pjksvwl2mr38gsmw";
   };
   
-  KSRC = "${kernelDev}/lib/modules/*/build";
+  KSRC = "${kernel.dev}/lib/modules/*/build";
   DESTDIR = "$(out)";
   
   preConfigure = ''
@@ -19,7 +20,8 @@ stdenv.mkDerivation rec {
   
   meta = {
     description = "A high performance, transport independent, multi-platform implementation of RFC3720";
-    license = "GPLv2+";
+    license = stdenv.lib.licenses.gpl2Plus;
     homepage = http://www.open-iscsi.org;
+    broken = true;
   };
 }
diff --git a/pkgs/os-specific/linux/otpw/default.nix b/pkgs/os-specific/linux/otpw/default.nix
index fe5f938b75b..27d0510a657 100644
--- a/pkgs/os-specific/linux/otpw/default.nix
+++ b/pkgs/os-specific/linux/otpw/default.nix
@@ -15,7 +15,7 @@ stdenv.mkDerivation rec {
   '';
 
   installPhase = ''
-    ensureDir $out/bin $out/lib/security $out/share/man/man{1,8}
+    mkdir -p $out/bin $out/lib/security $out/share/man/man{1,8}
     cp pam_*.so $out/lib/security
     cp otpw-gen $out/bin
     cp *.1 $out/share/man/man1
@@ -27,6 +27,6 @@ stdenv.mkDerivation rec {
   meta = {
     homepage = http://www.cl.cam.ac.uk/~mgk25/otpw.html;
     description = "A one-time password login package";
-    license = "GPLv2+";
+    license = stdenv.lib.licenses.gpl2Plus;
   };
 }
diff --git a/pkgs/os-specific/linux/pam/CVE-2014-2583.patch b/pkgs/os-specific/linux/pam/CVE-2014-2583.patch
new file mode 100644
index 00000000000..25b1f7549fa
--- /dev/null
+++ b/pkgs/os-specific/linux/pam/CVE-2014-2583.patch
@@ -0,0 +1,49 @@
+From 9dcead87e6d7f66d34e7a56d11a30daca367dffb Mon Sep 17 00:00:00 2001
+From: "Dmitry V. Levin" <ldv@altlinux.org>
+Date: Wed, 26 Mar 2014 22:17:23 +0000
+Subject: pam_timestamp: fix potential directory traversal issue (ticket #27)
+
+pam_timestamp uses values of PAM_RUSER and PAM_TTY as components of
+the timestamp pathname it creates, so extra care should be taken to
+avoid potential directory traversal issues.
+
+* modules/pam_timestamp/pam_timestamp.c (check_tty): Treat
+"." and ".." tty values as invalid.
+(get_ruser): Treat "." and ".." ruser values, as well as any ruser
+value containing '/', as invalid.
+
+Fixes CVE-2014-2583.
+
+Reported-by: Sebastian Krahmer <krahmer@suse.de>
+
+diff --git a/modules/pam_timestamp/pam_timestamp.c b/modules/pam_timestamp/pam_timestamp.c
+index 5193733..b3f08b1 100644
+--- a/modules/pam_timestamp/pam_timestamp.c
++++ b/modules/pam_timestamp/pam_timestamp.c
+@@ -158,7 +158,7 @@ check_tty(const char *tty)
+ 		tty = strrchr(tty, '/') + 1;
+ 	}
+ 	/* Make sure the tty wasn't actually a directory (no basename). */
+-	if (strlen(tty) == 0) {
++	if (!strlen(tty) || !strcmp(tty, ".") || !strcmp(tty, "..")) {
+ 		return NULL;
+ 	}
+ 	return tty;
+@@ -243,6 +243,17 @@ get_ruser(pam_handle_t *pamh, char *ruserbuf, size_t ruserbuflen)
+ 		if (pwd != NULL) {
+ 			ruser = pwd->pw_name;
+ 		}
++	} else {
++		/*
++		 * This ruser is used by format_timestamp_name as a component
++		 * of constructed timestamp pathname, so ".", "..", and '/'
++		 * are disallowed to avoid potential path traversal issues.
++		 */
++		if (!strcmp(ruser, ".") ||
++		    !strcmp(ruser, "..") ||
++		    strchr(ruser, '/')) {
++			ruser = NULL;
++		}
+ 	}
+ 	if (ruser == NULL || strlen(ruser) >= ruserbuflen) {
+ 		*ruserbuf = '\0';
diff --git a/pkgs/os-specific/linux/pam/default.nix b/pkgs/os-specific/linux/pam/default.nix
index 5545b5c16d6..8423ea6f123 100644
--- a/pkgs/os-specific/linux/pam/default.nix
+++ b/pkgs/os-specific/linux/pam/default.nix
@@ -1,13 +1,15 @@
 { stdenv, fetchurl, flex, cracklib }:
 
 stdenv.mkDerivation rec {
-  name = "linux-pam-1.1.6";
+  name = "linux-pam-1.1.8";
 
   src = fetchurl {
-    url = https://fedorahosted.org/releases/l/i/linux-pam/Linux-PAM-1.1.6.tar.bz2;
-    sha256 = "1hlz2kqvbjisvwyicdincq7nz897b9rrafyzccwzqiqg53b8gf5s";
+    url = http://www.linux-pam.org/library/Linux-PAM-1.1.8.tar.bz2;
+    sha256 = "0m8ygb40l1c13nsd4hkj1yh4p1ldawhhg8pyjqj9w5kd4cxg5cf4";
   };
 
+  patches = [ ./CVE-2014-2583.patch ];
+
   outputs = [ "out" "doc" "man" "modules" ];
 
   nativeBuildInputs = [ flex ];
diff --git a/pkgs/os-specific/linux/pam_krb5/default.nix b/pkgs/os-specific/linux/pam_krb5/default.nix
index 5f95811e0f6..ad60e63c263 100644
--- a/pkgs/os-specific/linux/pam_krb5/default.nix
+++ b/pkgs/os-specific/linux/pam_krb5/default.nix
@@ -19,5 +19,6 @@ stdenv.mkDerivation {
       pam_krb5 can optionally convert Kerberos 5 credentials to Kerberos IV
       credentials and/or use them to set up AFS tokens for a user's session.
     '';
+    maintainers = stdenv.lib.maintainers.mornfall;
   };
 }
diff --git a/pkgs/os-specific/linux/pam_usb/default.nix b/pkgs/os-specific/linux/pam_usb/default.nix
index b5672728b53..f5fdc567087 100644
--- a/pkgs/os-specific/linux/pam_usb/default.nix
+++ b/pkgs/os-specific/linux/pam_usb/default.nix
@@ -43,6 +43,6 @@ stdenv.mkDerivation rec {
   meta = {
     homepage = http://pamusb.org/;
     description = "Authentication using USB Flash Drives";
-    license = "GPLv2";
+    license = stdenv.lib.licenses.gpl2;
   };
 }
diff --git a/pkgs/os-specific/linux/pax-utils/default.nix b/pkgs/os-specific/linux/pax-utils/default.nix
new file mode 100644
index 00000000000..83f0dc1e82d
--- /dev/null
+++ b/pkgs/os-specific/linux/pax-utils/default.nix
@@ -0,0 +1,24 @@
+{ fetchurl, stdenv }:
+
+stdenv.mkDerivation rec {
+  name = "pax-utils-${version}";
+  version = "0.8.1";
+
+  src = fetchurl {
+    url = "http://dev.gentoo.org/~vapier/dist/${name}.tar.xz";
+    sha256 = "1fgm70s52x48dxjihs0rcwmpfsi2dxbjzcilxy9fzg0i39dz4kw4";
+  };
+
+  makeFlags = [
+    "DESTDIR=$(out)"
+    "PREFIX=$(out)"
+  ];
+
+  meta = with stdenv.lib; {
+    description = "A suite of tools for PaX/grsecurity";
+    homepage    = "http://dev.gentoo.org/~vapier/dist/";
+    license     = licenses.gpl2;
+    platforms   = platforms.linux;
+    maintainers = with maintainers; [ thoughtpolice wizeman ];
+  };
+}
diff --git a/pkgs/os-specific/linux/paxctl/default.nix b/pkgs/os-specific/linux/paxctl/default.nix
new file mode 100644
index 00000000000..8e70ddd8434
--- /dev/null
+++ b/pkgs/os-specific/linux/paxctl/default.nix
@@ -0,0 +1,28 @@
+{ fetchurl, stdenv }:
+
+stdenv.mkDerivation rec {
+  name = "paxctl-${version}";
+  version = "0.8";
+
+  src = fetchurl {
+    url = "http://pax.grsecurity.net/${name}.tar.gz";
+    sha256 = "107gmriq5icsk9yni5q949rnjapjkcs0823pw6zra6h1xml2f0mm";
+  };
+
+  preBuild = ''
+    sed "s|--owner 0 --group 0||g" -i Makefile
+  '';
+
+  makeFlags = [
+    "DESTDIR=$(out)"
+    "MANDIR=share/man/man1"
+  ];
+
+  meta = with stdenv.lib; {
+    description = "A tool for controlling PaX flags on a per binary basis";
+    homepage    = "https://pax.grsecurity.net";
+    license     = licenses.gpl2;
+    platforms   = platforms.linux;
+    maintainers = with maintainers; [ thoughtpolice wizeman ];
+  };
+}
diff --git a/pkgs/os-specific/linux/pcmciautils/default.nix b/pkgs/os-specific/linux/pcmciautils/default.nix
index b53c61c754a..787b72fde48 100644
--- a/pkgs/os-specific/linux/pcmciautils/default.nix
+++ b/pkgs/os-specific/linux/pcmciautils/default.nix
@@ -50,6 +50,6 @@ stdenv.mkDerivation rec {
       the PCMCIA subsystem to behave (almost) as every other
       hotpluggable bus system.
     ";
-    license = "GPL2";
+    license = stdenv.lib.licenses.gpl2;
   };
 }
diff --git a/pkgs/os-specific/linux/plymouth/default.nix b/pkgs/os-specific/linux/plymouth/default.nix
index bf3da195467..a04407ba5c2 100644
--- a/pkgs/os-specific/linux/plymouth/default.nix
+++ b/pkgs/os-specific/linux/plymouth/default.nix
@@ -1,56 +1,51 @@
-{ stdenv, fetchurl, cairo, gtk, libdrm, libpng, makeWrapper, pango, pkgconfig }:
+{ stdenv, fetchurl, autoconf, automake, cairo, docbook_xsl, gtk
+, libdrm, libpng , libtool, libxslt, makeWrapper, pango, pkgconfig
+, udev
+}:
 
 stdenv.mkDerivation rec {
   name = "plymouth-${version}";
-  version = "0.8.8";
+  version = "0.9.0";
 
   src = fetchurl {
     url = "http://www.freedesktop.org/software/plymouth/releases/${name}.tar.bz2";
-    sha256 = "16vm3llgci7h63jaclfskj1ii61d8psq7ny2mncml6m3sghs9b8v";
+    sha256 = "0kfdwv179brg390ma003pmdqfvqlbybqiyp9fxrxx0wa19sjxqnk";
   };
 
-  buildInputs = [ cairo gtk libdrm libpng makeWrapper pango pkgconfig ];
+  buildInputs = [
+    autoconf automake cairo docbook_xsl gtk libdrm libpng libtool
+    libxslt makeWrapper pango pkgconfig udev
+  ];
+
+  prePatch = ''
+    sed -e "s#\$(\$PKG_CONFIG --variable=systemdsystemunitdir systemd)#$out/etc/systemd/system#g" \
+      -i configure.ac
+  '';
 
   configurePhase = ''
-    export DESTDIR=$out
     ./configure \
+      --prefix=$out \
       -bindir=$out/bin \
       -sbindir=$out/sbin \
-      --prefix=$out \
       --exec-prefix=$out \
       --libdir=$out/lib \
       --libexecdir=$out/lib \
-      --enable-tracing \
-      --sysconfdir=/etc \
+      --sysconfdir=$out/etc \
       --localstatedir=/var \
+      --with-log-viewer \
       --without-system-root-install \
+      --without-rhgb-compat-link \
+      --enable-tracing \
+      --enable-systemd-integration \
+      --enable-pango \
       --enable-gtk
   '';
-#      --enable-systemd-integration
-#      -datadir=/share \
-#      --with-rhgb-compat-link \
-
-  preInstall = "mkdir -p $out/bin $out/sbin";
-
-  postInstall = ''
-    cd $out/$out
-    mv bin/* $out/bin
-    mv sbin/* $out/sbin
-
-    rmdir bin
-    rmdir sbin
-    mv * $out/
-    sed -e "s#> $output##" \
-      -e "s#> /dev/stderr##" \
-      -i $out/lib/plymouth/plymouth-populate-initrd
-    wrapProgram $out/lib/plymouth/plymouth-populate-initrd \
-      --set PATH $PATH:$out/bin:$out/sbin
-  '';
 
   meta = with stdenv.lib; {
     homepage = http://www.freedesktop.org/wiki/Software/Plymouth;
     description = "A graphical boot animation";
     license = licenses.gpl2;
     maintainers = [ maintainers.goibhniu ];
+    platforms = platforms.linux;
   };
 }
diff --git a/pkgs/os-specific/linux/pm-utils/default.nix b/pkgs/os-specific/linux/pm-utils/default.nix
index e3b6168be9b..4fb7fc8cb0b 100644
--- a/pkgs/os-specific/linux/pm-utils/default.nix
+++ b/pkgs/os-specific/linux/pm-utils/default.nix
@@ -49,7 +49,7 @@ stdenv.mkDerivation rec {
   meta = {
     homepage = http://pm-utils.freedesktop.org/wiki/;
     description = "A small collection of scripts that handle suspend and resume on behalf of HAL";
-    license = "GPLv2";
+    license = stdenv.lib.licenses.gpl2;
     platforms = stdenv.lib.platforms.linux;
   };
 }
diff --git a/pkgs/os-specific/linux/pmount/default.nix b/pkgs/os-specific/linux/pmount/default.nix
index 4d555f59c37..c1049d78f42 100644
--- a/pkgs/os-specific/linux/pmount/default.nix
+++ b/pkgs/os-specific/linux/pmount/default.nix
@@ -8,10 +8,11 @@
 assert stdenv.lib.hasSuffix "/" mediaDir;
 
 stdenv.mkDerivation rec {
-  name = "pmount-0.9.23";
+  name = "pmount-${version}";
+  version = "0.9.23";
 
   src = fetchurl {
-    url = "https://alioth.debian.org/frs/download.php/3310/${name}.tar.gz";
+    url = "mirror://debian/pool/main/p/pmount/pmount_${version}.orig.tar.bz2";
     sha256 = "db38fc290b710e8e9e9d442da2fb627d41e13b3ee80326c15cc2595ba00ea036";
   };
 
@@ -35,6 +36,7 @@ stdenv.mkDerivation rec {
   meta = {
     homepage = http://pmount.alioth.debian.org/;
     description = "Mount removable devices as normal user";
-    license = "GPLv2";
+    license = stdenv.lib.licenses.gpl2;
+    platforms = stdenv.lib.platforms.linux;
   };
 }
diff --git a/pkgs/os-specific/linux/pmtools/default.nix b/pkgs/os-specific/linux/pmtools/default.nix
index 13a6e87319e..7fa32ce4c94 100644
--- a/pkgs/os-specific/linux/pmtools/default.nix
+++ b/pkgs/os-specific/linux/pmtools/default.nix
@@ -17,7 +17,7 @@ stdenv.mkDerivation rec {
   meta = {
     homepage = http://www.lesswatts.org/projects/acpi/utilities.php;
     description = "Linux ACPI utilities";
-    license = "GPLv2";
+    license = stdenv.lib.licenses.gpl2;
 
     platforms = stdenv.lib.platforms.linux;
     maintainers = [ stdenv.lib.maintainers.simons ];
diff --git a/pkgs/os-specific/linux/policycoreutils/default.nix b/pkgs/os-specific/linux/policycoreutils/default.nix
index e49525a42bf..d312e25fc2e 100644
--- a/pkgs/os-specific/linux/policycoreutils/default.nix
+++ b/pkgs/os-specific/linux/policycoreutils/default.nix
@@ -1,23 +1,24 @@
 { stdenv, fetchurl, intltool, pcre, libcap_ng, libcgroup
-, libsepol, libselinux, libsemanage
+, libsepol, libselinux, libsemanage, setools
 , python, sepolgen }:
 stdenv.mkDerivation rec {
 
   name = "policycoreutils-${version}";
-  version = "2.1.13";
+  version = "2.3";
   inherit (libsepol) se_release se_url;
 
   src = fetchurl {
     url = "${se_url}/${se_release}/policycoreutils-${version}.tar.gz";
-    sha256 = "1145nbpwndmhma08vvj1j75bjd8xhjal0vjpazlrw78iyc30y11l";
+    sha256 = "1lpwxr5hw3dwhlp2p7y8jcr18mvfcrclwd8c2idz3lmmb3pglk46";
   };
 
   patchPhase = ''
     substituteInPlace po/Makefile --replace /usr/bin/install install
+    find . -type f -exec sed -i 's,/usr/bin/python,${python}/bin/python,' {} \;
   '';
 
   buildInputs = [ intltool pcre libcap_ng libcgroup
-    libsepol libselinux  libsemanage
+    libsepol libselinux libsemanage setools
     python sepolgen # ToDo? these are optional
   ];
 
@@ -25,6 +26,11 @@ stdenv.mkDerivation rec {
     mkdir -p "$out/lib" && cp -s "${libsepol}/lib/libsepol.a" "$out/lib"
   '';
 
+  # Creation of the system-config-selinux directory is broken
+  preInstall = ''
+    mkdir -p $out/share/system-config-selinux
+  '';
+
   NIX_CFLAGS_COMPILE = "-fstack-protector-all";
   NIX_LDFLAGS = "-lsepol -lpcre";
 
diff --git a/pkgs/os-specific/linux/pommed/default.nix b/pkgs/os-specific/linux/pommed/default.nix
index d6c06eca12f..b4b4569def4 100644
--- a/pkgs/os-specific/linux/pommed/default.nix
+++ b/pkgs/os-specific/linux/pommed/default.nix
@@ -74,7 +74,6 @@ stdenv.mkDerivation rec {
   meta = {
     description = "A tool to handle hotkeys on Apple laptop keyboards";
     homepage = http://www.technologeek.org/projects/pommed/index.html;
-    license = "gplv2";
-    maintainers = [ stdenv.lib.maintainers.shlevy ];
+    license = stdenv.lib.licenses.gpl2;
   };
 }
diff --git a/pkgs/os-specific/linux/powertop/default.nix b/pkgs/os-specific/linux/powertop/default.nix
index 4de8ad6db0f..630fe04e226 100644
--- a/pkgs/os-specific/linux/powertop/default.nix
+++ b/pkgs/os-specific/linux/powertop/default.nix
@@ -1,18 +1,18 @@
 { stdenv, fetchurl, gettext, libnl, ncurses, pciutils, pkgconfig, zlib }:
 
 stdenv.mkDerivation rec {
-  name = "powertop-2.2";
+  name = "powertop-2.6.1";
 
   src = fetchurl {
-    url = "https://01.org/powertop/sites/default/files/downloads/${name}.tar.gz";
-    sha256 = "0a5haxawcjrlwwxx4j5kd4ad05gjmcr13v8gswfwfxcn7fyf2f8k";
+    url = "https://01.org/sites/default/files/downloads/powertop/${name}.tar.gz";
+    sha256 = "1r103crmkdk617qrxqjzy2mlhaacbpg5q795546zwcxlbdnxwk03";
   };
 
   buildInputs = [ gettext libnl ncurses pciutils pkgconfig zlib ];
 
   meta = {
     description = "Analyze power consumption on Intel-based laptops";
-    license = "GPLv2";
+    license = stdenv.lib.licenses.gpl2;
     maintainers = [ stdenv.lib.maintainers.chaoflow ];
     platforms = stdenv.lib.platforms.linux;
   };
diff --git a/pkgs/os-specific/linux/procps-ng/default.nix b/pkgs/os-specific/linux/procps-ng/default.nix
index 6099505f1d6..cd8a8eaec13 100644
--- a/pkgs/os-specific/linux/procps-ng/default.nix
+++ b/pkgs/os-specific/linux/procps-ng/default.nix
@@ -1,11 +1,11 @@
 { stdenv, fetchurl, ncurses }:
 
 stdenv.mkDerivation {
-  name = "procps-ng-3.3.6";
+  name = "procps-3.3.9";
 
   src = fetchurl {
-    url = mirror://sourceforge/procps-ng/procps-ng-3.3.6.tar.xz;
-    sha256 = "0k0j3ilzfpw8n3y058ymgfmafdfqqqwpqm7nh7a35xlk6zgw96nh";
+    url = mirror://sourceforge/procps-ng/procps-ng-3.3.9.tar.xz;
+    sha256 = "0qw69v7wx8hilwylyk9455k3h1xg8sc13vxh0pvdss7rml7wpw00";
   };
 
   buildInputs = [ ncurses ];
diff --git a/pkgs/os-specific/linux/procps/watch.nix b/pkgs/os-specific/linux/procps/watch.nix
new file mode 100644
index 00000000000..2547e26def4
--- /dev/null
+++ b/pkgs/os-specific/linux/procps/watch.nix
@@ -0,0 +1,29 @@
+{ stdenv, fetchurl, ncurses }:
+
+stdenv.mkDerivation {
+  name = "watch-0.2.0";
+
+  src = fetchurl {
+    url = http://procps.sourceforge.net/procps-3.2.8.tar.gz;
+    sha256 = "0d8mki0q4yamnkk4533kx8mc0jd879573srxhg6r2fs3lkc6iv8i";
+  };
+
+  buildInputs = [ ncurses ];
+
+  makeFlags = "watch usrbin_execdir=$(out)/bin" +
+              (if stdenv.isDarwin then " PKG_LDFLAGS=" else "");
+
+  enableParallelBuilding = true;
+
+  crossAttrs = {
+    CC = stdenv.cross.config + "-gcc";
+  };
+
+  installPhase = "mkdir $out; mkdir -p $out/bin; cp -p watch $out/bin";
+
+  meta = {
+    homepage = http://sourceforge.net/projects/procps/;
+    description = "Utility for watch the output of a given command at intervals";
+    platforms = stdenv.lib.platforms.unix;
+  };
+}
diff --git a/pkgs/os-specific/linux/psmisc/0001-Typo-in-fuser-makes-M-on-all-the-time.patch b/pkgs/os-specific/linux/psmisc/0001-Typo-in-fuser-makes-M-on-all-the-time.patch
new file mode 100644
index 00000000000..2bb93955aea
--- /dev/null
+++ b/pkgs/os-specific/linux/psmisc/0001-Typo-in-fuser-makes-M-on-all-the-time.patch
@@ -0,0 +1,44 @@
+From 3638cc55b4d08851faba46635d737b24d016665b Mon Sep 17 00:00:00 2001
+From: Brad Jorsch <anomie@users.sourceforge.net>
+Date: Fri, 28 Feb 2014 21:55:02 +1100
+Subject: [PATCH] Typo in fuser makes -M on all the time
+
+Brad found that fuser had the -M option on all the time.
+A simple but significant typo caused this, thanks the the patch.
+
+Bug-Debian: http://bugs.debian.org/740275
+
+Signed-off-by: Craig Small <csmall@enc.com.au>
+---
+ ChangeLog   | 4 ++++
+ src/fuser.c | 2 +-
+ 2 files changed, 5 insertions(+), 1 deletion(-)
+
+diff --git a/ChangeLog b/ChangeLog
+index fd1cccf..e5f784c 100644
+--- a/ChangeLog
++++ b/ChangeLog
+@@ -1,3 +1,7 @@
++Changes in 22.22
++================
++	* Fixed typo in fuser which has -M on Debian #740275
++
+ Changes in 22.21
+ ================
+ 	* Missing comma in fuser(1) added Debian #702391
+diff --git a/src/fuser.c b/src/fuser.c
+index b485f65..389b302 100644
+--- a/src/fuser.c
++++ b/src/fuser.c
+@@ -1174,7 +1174,7 @@ int main(int argc, char *argv[])
+ 		usage(_("No process specification given"));
+ 
+ 	/* Check if -M flag was used and if so check mounts */
+-	if (opts * OPT_ISMOUNTPOINT) {
++	if (opts & OPT_ISMOUNTPOINT) {
+ 	    check_mountpoints(&mounts, &names_head, &names_tail);
+ 	}
+ 
+-- 
+1.9.2
+
diff --git a/pkgs/os-specific/linux/psmisc/default.nix b/pkgs/os-specific/linux/psmisc/default.nix
index dd6c70127bf..5cf5e9a542d 100644
--- a/pkgs/os-specific/linux/psmisc/default.nix
+++ b/pkgs/os-specific/linux/psmisc/default.nix
@@ -3,15 +3,18 @@
 assert stdenv.isLinux;
 
 stdenv.mkDerivation rec {
-  name = "psmisc-22.19";
+  name = "psmisc-22.21";
 
   src = fetchurl {
     url = "mirror://sourceforge/psmisc/${name}.tar.gz";
-    sha256 = "e112ccadd4694c98f5ea4a02cd6944fdc5a2a1985f20e2b3f74f4dbca83a2a31";
+    sha256 = "0nhlm1vrrwn4a845p6y4nnnb4liq70n74zbdd5dq844jc6nkqclp";
   };
 
   buildInputs = [ncurses];
 
+  # From upstream, will be in next release.
+  patches = [ ./0001-Typo-in-fuser-makes-M-on-all-the-time.patch ];
+
   meta = {
     homepage = http://psmisc.sourceforge.net/;
     description = "A set of small useful utilities that use the proc filesystem (such as fuser, killall and pstree)";
diff --git a/pkgs/os-specific/linux/psmouse-alps/default.nix b/pkgs/os-specific/linux/psmouse-alps/default.nix
index 834acd72ef2..9dd78f5885a 100644
--- a/pkgs/os-specific/linux/psmouse-alps/default.nix
+++ b/pkgs/os-specific/linux/psmouse-alps/default.nix
@@ -1,15 +1,17 @@
-{ stdenv, fetchurl, kernelDev, zlib }:
+{ stdenv, fetchurl, kernel, zlib }:
 
 /* Only useful for kernels 3.2 to 3.5.
    Fails to build in 3.8.
    3.9 upstream already includes a proper alps driver for this */
 
+assert builtins.compareVersions "3.8" kernel.version == 1;
+
 let
   ver = "1.3";
   bname = "psmouse-alps-${ver}";
 in
 stdenv.mkDerivation {
-  name = "psmouse-alps-${kernelDev.version}-${ver}";
+  name = "psmouse-alps-${kernel.version}-${ver}";
 
   src = fetchurl {
     url = http://www.dahetral.com/public-download/alps-psmouse-dlkm-for-3-2-and-3-5/at_download/file;
@@ -19,19 +21,19 @@ stdenv.mkDerivation {
 
   buildPhase = ''
     cd src/${bname}/src
-    make -C ${kernelDev}/lib/modules/${kernelDev.modDirVersion}/build \
+    make -C ${kernel.dev}/lib/modules/${kernel.modDirVersion}/build \
       SUBDIRS=`pwd` INSTALL_PATH=$out
   '';
 
   installPhase = ''
-    make -C ${kernelDev}/lib/modules/${kernelDev.modDirVersion}/build \
+    make -C ${kernel.dev}/lib/modules/${kernel.modDirVersion}/build \
       INSTALL_MOD_PATH=$out SUBDIRS=`pwd` modules_install
   '';
       
   meta = {
     description = "ALPS dlkm driver with all known touchpads";
     homepage = http://www.dahetral.com/public-download/alps-psmouse-dlkm-for-3-2-and-3-5/view;
-    license = "GPLv2";
+    license = stdenv.lib.licenses.gpl2;
     platforms = stdenv.lib.platforms.linux;
     maintainers = with stdenv.lib.maintainers; [viric];
   };
diff --git a/pkgs/os-specific/linux/radeontools/default.nix b/pkgs/os-specific/linux/radeontools/default.nix
index 4dbe7e54247..92e00ffad3f 100644
--- a/pkgs/os-specific/linux/radeontools/default.nix
+++ b/pkgs/os-specific/linux/radeontools/default.nix
@@ -24,9 +24,9 @@ stdenv.mkDerivation {
     cp radeontool lightwatch.pl $out/bin
   '';
 
-  meta = { 
+  meta = {
     description = "Control the backlight and external video output of ATI Radeon Mobility graphics cards";
     homepage = http://fdd.com/software/radeon/;
-    license = "ZLIB";
+    license = stdenv.lib.licenses.zlib;
   };
 }
diff --git a/pkgs/os-specific/linux/reptyr/default.nix b/pkgs/os-specific/linux/reptyr/default.nix
index 573f1a578c7..e5e579081f6 100644
--- a/pkgs/os-specific/linux/reptyr/default.nix
+++ b/pkgs/os-specific/linux/reptyr/default.nix
@@ -1,11 +1,11 @@
-{stdenv, fetchgit}:
+{ stdenv, fetchurl }:
+
 stdenv.mkDerivation rec {
-  version = "0.4";
+  version = "0.5";
   name = "reptyr-${version}";
-  src = fetchgit {
-    url = "https://github.com/nelhage/reptyr.git";
-    rev = "refs/tags/${name}";
-    sha256 = "2d2814c210e4bde6f9bcf3aa20477287d7e4a5aa7ee09110b37d2eaaf7e5ecae";
+  src = fetchurl {
+    url = "https://github.com/nelhage/reptyr/archive/reptyr-${version}.tar.gz";
+    sha256 = "077cvjjf534nxh7qqisw27a0wa61mdgyik43k50f8v090rggz2xm";
   };
   makeFlags = ["PREFIX=$(out)"];
   meta = {
diff --git a/pkgs/os-specific/linux/rfkill/default.nix b/pkgs/os-specific/linux/rfkill/default.nix
index 0e0f5a3ff0c..48be4fbc343 100644
--- a/pkgs/os-specific/linux/rfkill/default.nix
+++ b/pkgs/os-specific/linux/rfkill/default.nix
@@ -1,11 +1,11 @@
 { stdenv, fetchurl }:
 
 stdenv.mkDerivation rec {
-  name = "rfkill-0.4";
-  
+  name = "rfkill-0.5";
+
   src = fetchurl {
-    url = "http://wireless.kernel.org/download/rfkill/${name}.tar.bz2";
-    sha256 = "1hb884vgyldci648azbx17w83gzynn0svrmfjgh3c2jzga1f846a";
+    url = "mirror://kernel/software/network/rfkill/${name}.tar.bz2";
+    sha256 = "01zs7p9kd92pxgcgwl5w46h3iyx4acfg6m1j5fgnflsaa350q5iy";
   };
 
   makeFlags = "PREFIX=$(out)";
diff --git a/pkgs/os-specific/linux/rfkill/rfkill-hook.sh b/pkgs/os-specific/linux/rfkill/rfkill-hook.sh
index d07c7298183..bf6e679660c 100755
--- a/pkgs/os-specific/linux/rfkill/rfkill-hook.sh
+++ b/pkgs/os-specific/linux/rfkill/rfkill-hook.sh
@@ -10,10 +10,10 @@ if [ -z "$RFKILL_STATE" ]; then
   exit 1
 fi
 
-if [ -x /var/run/current-system/etc/rfkill.hook ]; then
-  exec /var/run/current-system/etc/rfkill.hook
+if [ -x /run/current-system/etc/rfkill.hook ]; then
+  exec /run/current-system/etc/rfkill.hook
 elif [ ! -z "$RFKILL_HOOK" ]; then
   exec $RFKILL_HOOK
 else
   echo "rfkill-hook: $RFKILL_STATE"
-fi
\ No newline at end of file
+fi
diff --git a/pkgs/os-specific/linux/rfkill/udev.nix b/pkgs/os-specific/linux/rfkill/udev.nix
index 6cf6e4adfa0..054ed471eaa 100644
--- a/pkgs/os-specific/linux/rfkill/udev.nix
+++ b/pkgs/os-specific/linux/rfkill/udev.nix
@@ -31,12 +31,12 @@ stdenv.mkDerivation {
   dontBuild = true;
 
   installPhase = ''
-    ensureDir "$out/etc/udev/rules.d/";
+    mkdir -p "$out/etc/udev/rules.d/";
     cat > "$out/etc/udev/rules.d/90-rfkill.rules" << EOF
       SUBSYSTEM=="rfkill", ATTR{type}=="wlan", RUN+="$out/bin/rfkill-hook.sh" 
     EOF
 
-    ensureDir "$out/bin/";
+    mkdir -p "$out/bin/";
     cp ${./rfkill-hook.sh} "$out/bin/rfkill-hook.sh"
     chmod +x "$out/bin/rfkill-hook.sh";
   '';
diff --git a/pkgs/os-specific/linux/rtkit/default.nix b/pkgs/os-specific/linux/rtkit/default.nix
index 05ebd0bf845..fe392fb0841 100644
--- a/pkgs/os-specific/linux/rtkit/default.nix
+++ b/pkgs/os-specific/linux/rtkit/default.nix
@@ -1,15 +1,19 @@
 { stdenv, fetchurl, pkgconfig, dbus, libcap }:
 
 stdenv.mkDerivation rec {
-  name = "rtkit-0.10";
+  name = "rtkit-0.11";
   
   src = fetchurl {
-    url = "http://0pointer.de/public/${name}.tar.gz";
-    sha256 = "08118ya3pkxd6gbbshas23xwj483169fqmxzhp5sgmfr16n97skl";
+    url = "http://0pointer.de/public/${name}.tar.xz";
+    sha256 = "1l5cb1gp6wgpc9vq6sx021qs6zb0nxg3cn1ba00hjhgnrw4931b8";
   };
 
+  configureFlags = [
+    "--with-systemdsystemunitdir=$(out)/etc/systemd/system"
+  ];
+
   buildInputs = [ pkgconfig dbus libcap ];
-  
+
   meta = {
     homepage = http://0pointer.de/blog/projects/rtkit;
     descriptions = "A daemon that hands out real-time priority to processes";
diff --git a/pkgs/os-specific/linux/sdparm/default.nix b/pkgs/os-specific/linux/sdparm/default.nix
index 8389728f22d..2a796c1b3a9 100644
--- a/pkgs/os-specific/linux/sdparm/default.nix
+++ b/pkgs/os-specific/linux/sdparm/default.nix
@@ -1,11 +1,11 @@
 {stdenv, fetchurl}:
 
 stdenv.mkDerivation {
-  name = "sdparm-1.03";
+  name = "sdparm-1.08";
 
   src = fetchurl {
-    url = http://sg.danny.cz/sg/p/sdparm-1.03.tgz;
-    sha256 = "067bdhq2qc7h7ykf1yv86s9x12zscpqnsdlnr636a0nv0di2wymq";
+    url = http://sg.danny.cz/sg/p/sdparm-1.08.tgz;
+    sha256 = "0msy8anggdand1yr50vg2azcfgks7sbfpnqk7xzw9adi2jj7hsrp";
   };
 
   meta = {
diff --git a/pkgs/os-specific/linux/sepolgen/default.nix b/pkgs/os-specific/linux/sepolgen/default.nix
index 7139ec98c28..812b100699f 100644
--- a/pkgs/os-specific/linux/sepolgen/default.nix
+++ b/pkgs/os-specific/linux/sepolgen/default.nix
@@ -2,12 +2,12 @@
 
 stdenv.mkDerivation rec {
   name = "sepolgen-${version}";
-  version = "1.1.8";
+  version = "1.2.1";
   inherit (libsepol) se_release se_url;
 
   src = fetchurl {
     url = "${se_url}/${se_release}/sepolgen-${version}.tar.gz";
-    sha256 = "1sssc9d4wz7l23yczlzplsmdr891sqr9w34ccn1bfwlnc4q63xdm";
+    sha256 = "1c41hz4a64mjvbfhgc7c7plydahsc161z0qn46qz2g3bvimj9323";
   };
 
   makeFlags = "PREFIX=$(out) DESTDIR=$(out) PYTHONLIBDIR=lib/${python.libPrefix}/site-packages";
diff --git a/pkgs/os-specific/linux/setools/default.nix b/pkgs/os-specific/linux/setools/default.nix
new file mode 100644
index 00000000000..63a43b2b5e9
--- /dev/null
+++ b/pkgs/os-specific/linux/setools/default.nix
@@ -0,0 +1,33 @@
+{ stdenv, fetchurl, fetchpatch, autoreconfHook, pkgconfig, bison, flex
+, python, swig2, tcl, libsepol, libselinux, libxml2, sqlite, bzip2 }:
+
+stdenv.mkDerivation rec {
+  name = "setools-3.3.8";
+
+  src = fetchurl {
+    url = "http://oss.tresys.com/projects/setools/chrome/site/dists/${name}/${name}.tar.bz2";
+    sha256 = "16g987ijaxabc30zyjzia4nafq49rm038y1pm4vca7i3kb67wf24";
+  };
+
+  patches = [ ./ftbfs-invalid-operands-of-types.patch ];
+
+  # SWIG-TCL is broken in 3.3.8
+  configureFlags = ''
+    --with-tcl=${tcl}/lib
+    --with-sepol-devel=${libsepol}
+    --with-selinux-devel=${libselinux}
+    --disable-gui
+    --disable-swig-tcl
+  '';
+
+  buildInputs = [ autoreconfHook pkgconfig bison flex python swig2 ];
+
+  nativeBuildInputs = [ tcl libsepol libselinux libxml2 sqlite bzip2 ];
+
+  meta = {
+    description = "SELinux Tools";
+    homepage = "http://oss.tresys.com/projects/setools/";
+    license = stdenv.lib.licenses.gpl2;
+    platforms = stdenv.lib.platforms.linux;
+  };
+}
diff --git a/pkgs/os-specific/linux/setools/ftbfs-invalid-operands-of-types.patch b/pkgs/os-specific/linux/setools/ftbfs-invalid-operands-of-types.patch
new file mode 100644
index 00000000000..97a5727f05b
--- /dev/null
+++ b/pkgs/os-specific/linux/setools/ftbfs-invalid-operands-of-types.patch
@@ -0,0 +1,15 @@
+https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=750331
+
+Index: setools-git/secmds/replcon.cc
+===================================================================
+--- setools-git.orig/secmds/replcon.cc
++++ setools-git/secmds/replcon.cc
+@@ -60,7 +60,7 @@ static struct option const longopts[] =
+ 	{NULL, 0, NULL, 0}
+ };
+ 
+-extern int lsetfilecon_raw(const char *, security_context_t) __attribute__ ((weak));
++extern int lsetfilecon_raw(const char *, const char *) __attribute__ ((weak));
+ 
+ /**
+  * As that setools must work with older libselinux versions that may
diff --git a/pkgs/os-specific/linux/shadow/default.nix b/pkgs/os-specific/linux/shadow/default.nix
index 1055fccd8aa..b52801cacff 100644
--- a/pkgs/os-specific/linux/shadow/default.nix
+++ b/pkgs/os-specific/linux/shadow/default.nix
@@ -26,19 +26,28 @@ stdenv.mkDerivation rec {
 
   patches = [ ./keep-path.patch dots_in_usernames ];
 
+  outputs = [ "out" "su" ];
+
   # Assume System V `setpgrp (void)', which is the default on GNU variants
   # (`AC_FUNC_SETPGRP' is not cross-compilation capable.)
-  preConfigure = "export ac_cv_func_setpgrp_void=yes";
+  preConfigure = ''
+    export ac_cv_func_setpgrp_void=yes
+    export shadow_cv_logdir=/var/log
+  '';
 
   preBuild = assert glibc != null;
     ''
       substituteInPlace lib/nscd.c --replace /usr/sbin/nscd ${glibc}/sbin/nscd
     '';
 
-  # Don't install ‘groups’, since coreutils already provides it.
   postInstall =
     ''
+      # Don't install ‘groups’, since coreutils already provides it.
       rm $out/bin/groups $out/share/man/man1/groups.*
+
+      # Move the su binary into the su package
+      mkdir -p $su/bin
+      mv $out/bin/su $su/bin
     '';
 
   meta = {
diff --git a/pkgs/os-specific/linux/spl/const.patch b/pkgs/os-specific/linux/spl/const.patch
new file mode 100644
index 00000000000..3bfcaa22b13
--- /dev/null
+++ b/pkgs/os-specific/linux/spl/const.patch
@@ -0,0 +1,13 @@
+diff --git a/module/spl/spl-proc.c b/module/spl/spl-proc.c
+index f25239a..b731123 100644
+--- a/module/spl/spl-proc.c
++++ b/module/spl/spl-proc.c
+@@ -38,7 +38,7 @@
+ 
+ #define SS_DEBUG_SUBSYS SS_PROC
+ 
+-#if defined(CONSTIFY_PLUGIN) && LINUX_VERSION_CODE >= KERNEL_VERSION(3,8,0)
++#if defined(CONSTIFY_PLUGIN)
+ typedef struct ctl_table __no_const spl_ctl_table;
+ #else
+ typedef struct ctl_table spl_ctl_table;
diff --git a/pkgs/os-specific/linux/spl/default.nix b/pkgs/os-specific/linux/spl/default.nix
index 6a9a4cc963f..944fb6ff554 100644
--- a/pkgs/os-specific/linux/spl/default.nix
+++ b/pkgs/os-specific/linux/spl/default.nix
@@ -1,21 +1,21 @@
-{ stdenv, fetchurl, kernelDev, perl, autoconf, automake, libtool, coreutils, gawk }:
+{ stdenv, fetchurl, kernel, perl, autoconf, automake, libtool, coreutils, gawk }:
 
 stdenv.mkDerivation {
-  name = "spl-0.6.2-${kernelDev.version}";
+  name = "spl-0.6.3-${kernel.version}";
   src = fetchurl {
-    url = http://archive.zfsonlinux.org/downloads/zfsonlinux/spl/spl-0.6.2.tar.gz;
-    sha256 = "196scl8q0bkkak6m0p1l1fz254cgsizqm73bf9wk3iynamq7qmrw";
+    url = http://archive.zfsonlinux.org/downloads/zfsonlinux/spl/spl-0.6.3.tar.gz;
+    sha256 = "1qqzyj2if5wai4jiwml4i8s6v8k7hbi7jmiph800lhkk5j8s72l9";
   };
 
-  patches = [ ./install_prefix.patch ];
+  patches = [ ./install_prefix.patch ./const.patch ];
 
-  buildInputs = [ perl kernelDev autoconf automake libtool ];
+  buildInputs = [ perl autoconf automake libtool ];
 
   preConfigure = ''
     ./autogen.sh
 
     substituteInPlace ./module/spl/spl-generic.c --replace /usr/bin/hostid hostid
-    substituteInPlace ./module/spl/spl-module.c  --replace /bin/mknod mknod 
+    substituteInPlace ./module/spl/spl-module.c  --replace /bin/mknod mknod
 
     substituteInPlace ./module/spl/spl-generic.c --replace "PATH=/sbin:/usr/sbin:/bin:/usr/bin" "PATH=${coreutils}:${gawk}:/bin"
     substituteInPlace ./module/splat/splat-vnode.c --replace "PATH=/sbin:/usr/sbin:/bin:/usr/bin" "PATH=${coreutils}:/bin"
@@ -23,8 +23,8 @@ stdenv.mkDerivation {
   '';
 
   configureFlags = ''
-     --with-linux=${kernelDev}/lib/modules/${kernelDev.modDirVersion}/build
-     --with-linux-obj=${kernelDev}/lib/modules/${kernelDev.modDirVersion}/build
+     --with-linux=${kernel.dev}/lib/modules/${kernel.modDirVersion}/source
+     --with-linux-obj=${kernel.dev}/lib/modules/${kernel.modDirVersion}/build
   '';
 
   enableParallelBuilding = true;
@@ -34,12 +34,12 @@ stdenv.mkDerivation {
 
     longDescription = ''
       This kernel module is a porting layer for ZFS to work inside the linux
-      kernel. 
+      kernel.
     '';
 
     homepage = http://zfsonlinux.org/;
     platforms = stdenv.lib.platforms.linux;
     license = stdenv.lib.licenses.gpl2Plus;
-    maintainers = with stdenv.lib.maintainers; [ jcumming ];
+    maintainers = with stdenv.lib.maintainers; [ jcumming wizeman ];
   };
 }
diff --git a/pkgs/os-specific/linux/spl/git.nix b/pkgs/os-specific/linux/spl/git.nix
new file mode 100644
index 00000000000..d3ed285ccfe
--- /dev/null
+++ b/pkgs/os-specific/linux/spl/git.nix
@@ -0,0 +1,46 @@
+{ stdenv, fetchgit, kernel, perl, autoconf, automake, libtool, coreutils, gawk }:
+
+stdenv.mkDerivation {
+  name = "spl-0.6.3-${kernel.version}";
+  src = fetchgit {
+    url = git://github.com/zfsonlinux/spl.git;
+    rev = "31cb5383bff0fddc5058973e32a6f2c446d45e59";
+    sha256 = "0mcivbddms8kbapbs9x6achqyvh5i6h1rd2b3jm8g5yjn0flc5gl";
+  };
+
+  patches = [ ./install_prefix.patch ./const.patch ];
+
+  buildInputs = [ perl autoconf automake libtool ];
+
+  preConfigure = ''
+    ./autogen.sh
+
+    substituteInPlace ./module/spl/spl-generic.c --replace /usr/bin/hostid hostid
+    substituteInPlace ./module/spl/spl-module.c  --replace /bin/mknod mknod
+
+    substituteInPlace ./module/spl/spl-generic.c --replace "PATH=/sbin:/usr/sbin:/bin:/usr/bin" "PATH=${coreutils}:${gawk}:/bin"
+    substituteInPlace ./module/splat/splat-vnode.c --replace "PATH=/sbin:/usr/sbin:/bin:/usr/bin" "PATH=${coreutils}:/bin"
+    substituteInPlace ./module/splat/splat-linux.c --replace "PATH=/sbin:/usr/sbin:/bin:/usr/bin" "PATH=${coreutils}:/bin"
+  '';
+
+  configureFlags = ''
+     --with-linux=${kernel.dev}/lib/modules/${kernel.modDirVersion}/source
+     --with-linux-obj=${kernel.dev}/lib/modules/${kernel.modDirVersion}/build
+  '';
+
+  enableParallelBuilding = true;
+
+  meta = {
+    description = "Kernel module driver for solaris porting layer (needed by in-kernel zfs)";
+
+    longDescription = ''
+      This kernel module is a porting layer for ZFS to work inside the linux
+      kernel.
+    '';
+
+    homepage = http://zfsonlinux.org/;
+    platforms = stdenv.lib.platforms.linux;
+    license = stdenv.lib.licenses.gpl2Plus;
+    maintainers = with stdenv.lib.maintainers; [ wizeman ];
+  };
+}
diff --git a/pkgs/os-specific/linux/sysdig/default.nix b/pkgs/os-specific/linux/sysdig/default.nix
new file mode 100644
index 00000000000..d5e2ed3ff94
--- /dev/null
+++ b/pkgs/os-specific/linux/sysdig/default.nix
@@ -0,0 +1,43 @@
+{stdenv, fetchurl, cmake, luajit, kernel, zlib}:
+let
+  inherit (stdenv.lib) optional optionalString;
+  s = rec {
+    baseName="sysdig";
+    version="0.1.87";
+    name="${baseName}-${version}";
+    url="https://github.com/draios/sysdig/archive/${version}.tar.gz";
+    sha256="0xfildaj8kzbngpza47zqm363i6q87m97a18qlmdisrxmz11s32b";
+  };
+  buildInputs = [
+    cmake zlib luajit
+  ] ++ optional (kernel != null) kernel;
+in
+stdenv.mkDerivation {
+  inherit (s) name version;
+  inherit buildInputs;
+  src = fetchurl {
+    inherit (s) url sha256;
+  };
+
+  cmakeFlags = [
+    "-DUSE_BUNDLED_LUAJIT=OFF"
+    "-DUSE_BUNDLED_ZLIB=OFF"
+  ] ++ optional (kernel == null) "-DBUILD_DRIVER=OFF";
+  preConfigure = ''
+    export INSTALL_MOD_PATH="$out"
+  '' + optionalString (kernel != null) ''
+    export KERNELDIR="${kernel.dev}/lib/modules/${kernel.modDirVersion}/build"
+  '';
+  postInstall = optionalString (kernel != null) ''
+    make install_driver
+  '';
+
+  meta = with stdenv.lib; {
+    inherit (s) version;
+    description = ''A tracepoint-based system tracing tool for Linux (with clients for other OSes)'';
+    license = licenses.gpl2;
+    maintainers = [maintainers.raskin];
+    platforms = platforms.linux ++ platforms.darwin;
+    downloadPage = "https://github.com/draios/sysdig/releases";
+  };
+}
diff --git a/pkgs/os-specific/linux/sysdig/default.upstream b/pkgs/os-specific/linux/sysdig/default.upstream
new file mode 100644
index 00000000000..485de5741d7
--- /dev/null
+++ b/pkgs/os-specific/linux/sysdig/default.upstream
@@ -0,0 +1,8 @@
+url https://github.com/draios/sysdig/releases
+ensure_choice
+version '.*/([0-9.]+)[.]tar[.].*' '\1'
+do_overwrite () {
+  ensure_hash
+  set_var_value sha256 $CURRENT_HASH
+  set_var_value version $CURRENT_VERSION
+}
diff --git a/pkgs/os-specific/linux/syslinux/default.nix b/pkgs/os-specific/linux/syslinux/default.nix
index 98917f943f5..734613c44ac 100644
--- a/pkgs/os-specific/linux/syslinux/default.nix
+++ b/pkgs/os-specific/linux/syslinux/default.nix
@@ -1,11 +1,11 @@
 { stdenv, fetchurl, nasm, perl, libuuid }:
 
 stdenv.mkDerivation rec {
-  name = "syslinux-4.06";
+  name = "syslinux-6.02";
 
   src = fetchurl {
-    url = "mirror://kernel/linux/utils/boot/syslinux/4.xx/${name}.tar.bz2";
-    sha256 = "09md61npd5z64rv5s3knl4qsn2bqsn57irm5izk6snf46r77gdyv";
+    url = "mirror://kernel/linux/utils/boot/syslinux/${name}.tar.xz";
+    sha256 = "0y2ld2s64s6vc5pf8rj36w71rq2cfax3c1iafp0w1qbjpxy1p8xg";
   };
 
   patches = [ ./perl-deps.patch ];
@@ -14,15 +14,27 @@ stdenv.mkDerivation rec {
 
   enableParallelBuilding = true;
 
-  preBuild =
-    ''
-      substituteInPlace gpxe/src/Makefile.housekeeping --replace /bin/echo $(type -P echo)
-      substituteInPlace gpxe/src/Makefile --replace /usr/bin/perl $(type -P perl)
-      makeFlagsArray=(BINDIR=$out/bin SBINDIR=$out/sbin LIBDIR=$out/lib INCDIR=$out/include DATADIR=$out/share MANDIR=$out/share/man PERL=perl)
-    '';
+  preBuild = ''
+    substituteInPlace Makefile --replace /bin/pwd $(type -P pwd)
+    substituteInPlace gpxe/src/Makefile.housekeeping --replace /bin/echo $(type -P echo)
+    substituteInPlace gpxe/src/Makefile --replace /usr/bin/perl $(type -P perl)
+  '';
 
-  meta = {
+  makeFlags = [
+    "BINDIR=$(out)/bin"
+    "SBINDIR=$(out)/sbin"
+    "LIBDIR=$(out)/lib"
+    "INCDIR=$(out)/include"
+    "DATADIR=$(out)/share"
+    "MANDIR=$(out)/share/man"
+    "PERL=perl"
+    "bios"
+  ];
+
+  meta = with stdenv.lib; {
     homepage = http://www.syslinux.org/;
     description = "A lightweight bootloader";
+    license = licenses.gpl2;
+    platforms = platforms.linux;
   };
 }
diff --git a/pkgs/os-specific/linux/sysstat/default.nix b/pkgs/os-specific/linux/sysstat/default.nix
index 2b4888f89cd..ec504bd9235 100644
--- a/pkgs/os-specific/linux/sysstat/default.nix
+++ b/pkgs/os-specific/linux/sysstat/default.nix
@@ -21,7 +21,7 @@ stdenv.mkDerivation rec {
   meta = {
     homepage = http://sebastien.godard.pagesperso-orange.fr/;
     description = "A collection of performance monitoring tools for Linux (such as sar, iostat and pidstat)";
-    license = "GPLv2+";
+    license = stdenv.lib.licenses.gpl2Plus;
     platforms = stdenv.lib.platforms.linux;
     maintainers = [ stdenv.lib.maintainers.eelco ];
   };
diff --git a/pkgs/os-specific/linux/systemd/default.nix b/pkgs/os-specific/linux/systemd/default.nix
index 4e6c64d4c7b..9942218be6c 100644
--- a/pkgs/os-specific/linux/systemd/default.nix
+++ b/pkgs/os-specific/linux/systemd/default.nix
@@ -1,33 +1,38 @@
 { stdenv, fetchurl, pkgconfig, intltool, gperf, libcap, dbus, kmod
 , xz, pam, acl, cryptsetup, libuuid, m4, utillinux
 , glib, kbd, libxslt, coreutils, libgcrypt, sysvtools, docbook_xsl
-, kexectools
+, kexectools, libmicrohttpd, linuxHeaders
+, pythonPackages ? null, pythonSupport ? false
+, autoreconfHook
 }:
 
 assert stdenv.isLinux;
 
+assert pythonSupport -> pythonPackages != null;
+
 stdenv.mkDerivation rec {
-  version = "203";
+  version = "212";
   name = "systemd-${version}";
 
   src = fetchurl {
     url = "http://www.freedesktop.org/software/systemd/${name}.tar.xz";
-    sha256 = "07gvn3rpski8sh1nz16npjf2bvj0spsjdwc5px9685g2pi6kxcb1";
+    sha256 = "1hpjcc42svrs06q3isjm3m5aphgkpfdylmvpnif71zh46ys0cab5";
   };
 
   outputs = [ "out" "man" "libudev" ];
 
   patches =
     [ # These are all changes between upstream and
-      # https://github.com/edolstra/systemd/tree/nixos-v203.
+      # https://github.com/edolstra/systemd/tree/nixos-v212.
       ./fixes.patch
-    ]
-    ++ stdenv.lib.optional stdenv.isArm ./libc-bug-accept4-arm.patch;
+    ];
 
   buildInputs =
-    [ pkgconfig intltool gperf libcap dbus.libs kmod xz pam acl
+    [ pkgconfig intltool gperf libcap kmod xz pam acl
       /* cryptsetup */ libuuid m4 glib libxslt libgcrypt docbook_xsl
-    ];
+      libmicrohttpd linuxHeaders
+      autoreconfHook
+    ] ++ stdenv.lib.optionals pythonSupport [pythonPackages.python pythonPackages.lxml];
 
   configureFlags =
     [ "--localstatedir=/var"
@@ -42,15 +47,19 @@ stdenv.mkDerivation rec {
       "--with-dbussessionservicedir=$(out)/share/dbus-1/services"
       "--with-firmware-path=/root/test-firmware:/run/current-system/firmware"
       "--with-tty-gid=3" # tty in NixOS has gid 3
+      "--disable-networkd" # enable/use eventually
+      "--enable-compat-libs" # get rid of this eventually
+      "--disable-tests"
     ];
 
   preConfigure =
     ''
       # FIXME: patch this in systemd properly (and send upstream).
       # FIXME: use sulogin from util-linux once updated.
-      for i in src/remount-fs/remount-fs.c src/core/mount.c src/core/swap.c src/fsck/fsck.c units/emergency.service.in units/rescue.service.m4.in src/journal/cat.c src/core/shutdown.c; do
+      for i in src/remount-fs/remount-fs.c src/core/mount.c src/core/swap.c src/fsck/fsck.c units/emergency.service.in units/rescue.service.m4.in src/journal/cat.c src/core/shutdown.c src/nspawn/nspawn.c; do
         test -e $i
         substituteInPlace $i \
+          --replace /usr/bin/getent ${stdenv.glibc.bin}/bin/getent \
           --replace /bin/mount ${utillinux.bin}/bin/mount \
           --replace /bin/umount ${utillinux.bin}/bin/umount \
           --replace /sbin/swapon ${utillinux.bin}/sbin/swapon \
@@ -68,6 +77,10 @@ stdenv.mkDerivation rec {
       export NIX_CFLAGS_LINK+=" -Wl,-rpath,$libudev/lib"
     '';
 
+  # This is needed because systemd uses the gold linker, which doesn't
+  # yet have the wrapper script to add rpath flags automatically.
+  NIX_LDFLAGS = "-rpath ${pam}/lib -rpath ${libcap}/lib -rpath ${acl}/lib -rpath ${stdenv.gcc.gcc}/lib";
+
   PYTHON_BINARY = "${coreutils}/bin/env python"; # don't want a build time dependency on Python
 
   NIX_CFLAGS_COMPILE =
@@ -76,10 +89,6 @@ stdenv.mkDerivation rec {
       "-UPOLKIT_AGENT_BINARY_PATH" "-DPOLKIT_AGENT_BINARY_PATH=\"/run/current-system/sw/bin/pkttyagent\""
       "-fno-stack-protector"
 
-      # Work around our kernel headers being too old.  FIXME: remove
-      # this after the next stdenv update.
-      "-DFS_NOCOW_FL=0x00800000"
-
       # Set the release_agent on /sys/fs/cgroup/systemd to the
       # currently running systemd (/run/current-system/systemd) so
       # that we don't use an obsolete/garbage-collected release agent.
@@ -93,7 +102,12 @@ stdenv.mkDerivation rec {
   # /var is mounted.
   makeFlags = "hwdb_bin=/var/lib/udev/hwdb.bin";
 
-  installFlags = "localstatedir=$(TMPDIR)/var sysconfdir=$(out)/etc sysvinitdir=$(TMPDIR)/etc/init.d";
+  installFlags =
+    [ "localstatedir=$(TMPDIR)/var"
+      "sysconfdir=$(out)/etc"
+      "sysvinitdir=$(TMPDIR)/etc/init.d"
+      "pamconfdir=$(out)/etc/pam.d"
+    ];
 
   # Get rid of configuration-specific data.
   postInstall =
@@ -102,6 +116,8 @@ stdenv.mkDerivation rec {
       mv $out/lib/{modules-load.d,binfmt.d,sysctl.d,tmpfiles.d} $out/example
       mv $out/lib/systemd/{system,user} $out/example/systemd
 
+      rm -rf $out/etc/systemd/system
+
       # Install SysV compatibility commands.
       mkdir -p $out/sbin
       ln -s $out/lib/systemd/systemd $out/sbin/telinit
@@ -137,19 +153,6 @@ stdenv.mkDerivation rec {
   # runtime; otherwise we can't and we need to reboot.
   passthru.interfaceVersion = 2;
 
-  passthru.headers = stdenv.mkDerivation {
-    name = "systemd-headers-${version}";
-    inherit src;
-
-    phases = [ "unpackPhase" "installPhase" ];
-
-    # some are needed by dbus.libs, which is needed for systemd :-)
-    installPhase = ''
-      mkdir -p "$out/include/systemd"
-      mv src/systemd/*.h "$out/include/systemd"
-    '';
-  };
-
   meta = {
     homepage = "http://www.freedesktop.org/wiki/Software/systemd";
     description = "A system and service manager for Linux";
diff --git a/pkgs/os-specific/linux/systemd/fixes.patch b/pkgs/os-specific/linux/systemd/fixes.patch
index 0ad420cd35c..72cf0e92bb8 100644
--- a/pkgs/os-specific/linux/systemd/fixes.patch
+++ b/pkgs/os-specific/linux/systemd/fixes.patch
@@ -1,144 +1,408 @@
-diff --git a/man/systemd.special.xml b/man/systemd.special.xml
-index 7164b1e..29401eb 100644
---- a/man/systemd.special.xml
-+++ b/man/systemd.special.xml
-@@ -381,7 +381,7 @@
-                                         this unit during
-                                         installation. This is best
-                                         configured via
--                                        <varname>WantedBy=multi-uer.target</varname>
-+                                        <varname>WantedBy=multi-user.target</varname>
-                                         in the unit's
-                                         <literal>[Install]</literal>
-                                         section.</para>
-diff --git a/rules/80-net-name-slot.rules b/rules/80-net-name-slot.rules
-index 15b5bc4..c5f1b38 100644
---- a/rules/80-net-name-slot.rules
-+++ b/rules/80-net-name-slot.rules
-@@ -1,6 +1,6 @@
- # do not edit this file, it will be overwritten on update
- 
--ACTION=="remove", GOTO="net_name_slot_end"
-+ACTION!="add", GOTO="net_name_slot_end"
- SUBSYSTEM!="net", GOTO="net_name_slot_end"
- NAME!="", GOTO="net_name_slot_end"
+diff --git a/Makefile.am b/Makefile.am
+index 3d9e5c1..46487f6 100644
+--- a/Makefile.am
++++ b/Makefile.am
+@@ -1095,7 +1095,7 @@ BUILT_SOURCES += \
+ 
+ src/shared/errno-list.txt:
+ 	$(AM_V_at)$(MKDIR_P) $(dir $@)
+-	$(AM_V_GEN)$(CPP) $(CFLAGS) $(AM_CPPFLAGS) $(CPPFLAGS) -dM -include errno.h - < /dev/null | $(AWK) '/^#define[ \t]+E[^ _]+[ \t]+[0-9]/ { print $$2; }'  > $@
++	$(AM_V_GEN)$(CPP) $(CFLAGS) $(AM_CPPFLAGS) $(CPPFLAGS) -dM -include errno.h - < /dev/null | $(AWK) '/^#define[ \t]+E[^ _]+[ \t]+/ { print $$2; }'  > $@
+ 
+ src/shared/errno-from-name.gperf: src/shared/errno-list.txt
+ 	$(AM_V_at)$(MKDIR_P) $(dir $@)
+@@ -1107,7 +1107,7 @@ src/shared/errno-from-name.h: src/shared/errno-from-name.gperf
+ 
+ src/shared/errno-to-name.h: src/shared/errno-list.txt
+ 	$(AM_V_at)$(MKDIR_P) $(dir $@)
+-	$(AM_V_GEN)$(AWK) 'BEGIN{ print "static const char* const errno_names[] = { "} { printf "[%s] = \"%s\",\n", $$1, $$1 } END{print "};"}' < $< > $@
++	$(AM_V_GEN)$(AWK) 'BEGIN{ print "static const char* const errno_names[] = { "} !/EDEADLOCK/ && !/EWOULDBLOCK/ && !/ENOTSUP/ { printf "[%s] = \"%s\",\n", $$1, $$1 } END{print "};"}' < $< > $@
+ 
+ src/shared/af-list.txt:
+ 	$(AM_V_at)$(MKDIR_P) $(dir $@)
+@@ -1707,7 +1707,9 @@ dist_tmpfiles_DATA += \
+ endif
+ 
+ SYSINIT_TARGET_WANTS += \
+-	systemd-tmpfiles-setup-dev.service \
++	systemd-tmpfiles-setup-dev.service
++
++MULTI_USER_TARGET_WANTS += \
+ 	systemd-tmpfiles-setup.service
+ 
+ dist_zshcompletion_DATA += \
+@@ -1961,6 +1963,7 @@ systemd_cgls_SOURCES = \
+ 	src/cgls/cgls.c
+ 
+ systemd_cgls_LDADD = \
++	libsystemd-internal.la \
+ 	libsystemd-shared.la
+ 
+ # ------------------------------------------------------------------------------
+diff --git a/TODO b/TODO
+index e2ca1e6..d7efdd5 100644
+--- a/TODO
++++ b/TODO
+@@ -1,4 +1,6 @@
+ Bugfixes:
++* Should systemctl status \* work on all unit types, not just .service?
++
+ * enabling an instance unit creates a pointless link, and
+   the unit will be started with getty@getty.service:
+     $ systemctl enable getty@.service
+diff --git a/rules/42-usb-hid-pm.rules b/rules/42-usb-hid-pm.rules
+index c675b5b..4c300da 100644
+--- a/rules/42-usb-hid-pm.rules
++++ b/rules/42-usb-hid-pm.rules
+@@ -12,10 +12,6 @@ ACTION=="add", SUBSYSTEM=="usb", ATTR{product}=="QEMU USB Mouse", ATTR{serial}!=
+ ACTION=="add", SUBSYSTEM=="usb", ATTR{product}=="QEMU USB Tablet", ATTR{serial}!="1", TEST=="power/control", ATTR{power/control}="auto"
+ ACTION=="add", SUBSYSTEM=="usb", ATTR{product}=="QEMU USB Keyboard", ATTR{serial}!="1", TEST=="power/control", ATTR{power/control}="auto"
+ 
+-# Catch-all for Avocent HID devices. Keyed off interface in order to only
+-# trigger on HID class devices.
+-ACTION=="add", SUBSYSTEM=="usb", ATTRS{idVendor}=="0624", ATTR{bInterfaceClass}=="03", TEST=="../power/control", ATTR{../power/control}="auto"
+-
+ # Dell DRAC 4
+ ACTION=="add", SUBSYSTEM=="usb", ATTR{idVendor}=="413c", ATTR{idProduct}=="2500", TEST=="power/control", ATTR{power/control}="auto"
  
 diff --git a/rules/99-systemd.rules.in b/rules/99-systemd.rules.in
-index d17bdd9..040b10e 100644
+index db72373..2875958 100644
 --- a/rules/99-systemd.rules.in
 +++ b/rules/99-systemd.rules.in
 @@ -14,10 +14,6 @@ KERNEL=="vport*", TAG+="systemd"
- SUBSYSTEM=="block", KERNEL!="ram*|loop*", TAG+="systemd"
- SUBSYSTEM=="block", KERNEL!="ram*|loop*", ENV{DM_UDEV_DISABLE_OTHER_RULES_FLAG}=="1", ENV{SYSTEMD_READY}="0"
+ SUBSYSTEM=="block", KERNEL!="ram*", TAG+="systemd"
+ SUBSYSTEM=="block", KERNEL!="ram*", ENV{DM_UDEV_DISABLE_OTHER_RULES_FLAG}=="1", ENV{SYSTEMD_READY}="0"
  
 -# Ignore encrypted devices with no identified superblock on it, since
 -# we are probably still calling mke2fs or mkswap on it.
--SUBSYSTEM=="block", KERNEL!="ram*|loop*", ENV{DM_UUID}=="CRYPT-*", ENV{ID_PART_TABLE_TYPE}=="", ENV{ID_FS_USAGE}=="", ENV{SYSTEMD_READY}="0"
+-SUBSYSTEM=="block", KERNEL!="ram*", ENV{DM_UUID}=="CRYPT-*", ENV{ID_PART_TABLE_TYPE}=="", ENV{ID_FS_USAGE}=="", ENV{SYSTEMD_READY}="0"
 -
  # Ignore raid devices that are not yet assembled and started
  SUBSYSTEM=="block", ENV{DEVTYPE}=="disk", KERNEL=="md*", TEST!="md/array_state", ENV{SYSTEMD_READY}="0"
  SUBSYSTEM=="block", ENV{DEVTYPE}=="disk", KERNEL=="md*", ATTR{md/array_state}=="|clear|inactive", ENV{SYSTEMD_READY}="0"
-diff --git a/src/core/cgroup-semantics.c b/src/core/cgroup-semantics.c
-index 82b02bb..7df9d01 100644
---- a/src/core/cgroup-semantics.c
-+++ b/src/core/cgroup-semantics.c
-@@ -255,7 +255,7 @@ static int map_blkio(const CGroupSemantics *s, const char *value, char **ret) {
- }
+@@ -43,7 +39,7 @@ SUBSYSTEM=="net", KERNEL!="lo", TAG+="systemd", ENV{SYSTEMD_ALIAS}+="/sys/subsys
+ SUBSYSTEM=="bluetooth", TAG+="systemd", ENV{SYSTEMD_ALIAS}+="/sys/subsystem/bluetooth/devices/%k"
+ 
+ SUBSYSTEM=="bluetooth", TAG+="systemd", ENV{SYSTEMD_WANTS}+="bluetooth.target"
+-ENV{ID_SMARTCARD_READER}=="*?", TAG+="systemd", ENV{SYSTEMD_WANTS}+="smartcard.target"
++ENV{ID_SMARTCARD_READER}=="?*", TAG+="systemd", ENV{SYSTEMD_WANTS}+="smartcard.target"
+ SUBSYSTEM=="sound", KERNEL=="card*", TAG+="systemd", ENV{SYSTEMD_WANTS}+="sound.target"
+ 
+ SUBSYSTEM=="printer", TAG+="systemd", ENV{SYSTEMD_WANTS}+="printer.target"
+diff --git a/src/cgls/cgls.c b/src/cgls/cgls.c
+index b8e275d..1840594 100644
+--- a/src/cgls/cgls.c
++++ b/src/cgls/cgls.c
+@@ -35,6 +35,10 @@
+ #include "build.h"
+ #include "output-mode.h"
+ #include "fileio.h"
++#include "sd-bus.h"
++#include "bus-util.h"
++#include "bus-error.h"
++#include "unit-name.h"
+ 
+ static bool arg_no_pager = false;
+ static bool arg_kernel_threads = false;
+@@ -127,6 +131,7 @@ int main(int argc, char *argv[]) {
+         int r = 0, retval = EXIT_FAILURE;
+         int output_flags;
+         char _cleanup_free_ *root = NULL;
++        _cleanup_bus_unref_ sd_bus *bus = NULL;
+ 
+         log_parse_environment();
+         log_open();
+@@ -151,6 +156,12 @@ int main(int argc, char *argv[]) {
+                 arg_all * OUTPUT_SHOW_ALL |
+                 (arg_full > 0) * OUTPUT_FULL_WIDTH;
+ 
++        r = bus_open_transport(BUS_TRANSPORT_LOCAL, NULL, false, &bus);
++        if (r < 0) {
++                log_error("Failed to create bus connection: %s", strerror(-r));
++                goto finish;
++        }
++
+         if (optind < argc) {
+                 int i;
+ 
+@@ -189,8 +200,52 @@ int main(int argc, char *argv[]) {
+                 } else {
+                         if (arg_machine) {
+                                 char *m;
++                                const char *cgroup;
++                                _cleanup_free_ char *scope = NULL;
++                                _cleanup_free_ char *path = NULL;
++                                _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
++                                _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
++
+                                 m = strappenda("/run/systemd/machines/", arg_machine);
+-                                r = parse_env_file(m, NEWLINE, "CGROUP", &root, NULL);
++                                r = parse_env_file(m, NEWLINE, "SCOPE", &scope, NULL);
++                                if (r < 0) {
++                                        log_error("Failed to get machine path: %s", strerror(-r));
++                                        goto finish;
++                                }
++
++                                path = unit_dbus_path_from_name(scope);
++                                if (!path) {
++                                        r = log_oom();
++                                        goto finish;
++                                }
++
++                                r = sd_bus_get_property(
++                                                bus,
++                                                "org.freedesktop.systemd1",
++                                                path,
++                                                "org.freedesktop.systemd1.Scope",
++                                                "ControlGroup",
++                                                &error,
++                                                &reply,
++                                                "s");
++
++                                if (r < 0) {
++                                        log_error("Failed to query ControlGroup: %s", bus_error_message(&error, -r));
++                                        goto finish;
++                                }
++
++                                r = sd_bus_message_read(reply, "s", &cgroup);
++                                if (r < 0) {
++                                        bus_log_parse_error(r);
++                                        goto finish;
++                                }
++
++                                root = strdup(cgroup);
++                                if (!root) {
++                                        r = log_oom();
++                                        goto finish;
++                                }
++
+                         } else
+                                 r = cg_get_root_path(&root);
+                         if (r < 0) {
+diff --git a/src/core/cgroup.c b/src/core/cgroup.c
+index 3dd4c91..4201e1e 100644
+--- a/src/core/cgroup.c
++++ b/src/core/cgroup.c
+@@ -871,7 +871,7 @@ int manager_setup_cgroup(Manager *m) {
+         safe_close(m->pin_cgroupfs_fd);
+ 
+         m->pin_cgroupfs_fd = open(path, O_RDONLY|O_CLOEXEC|O_DIRECTORY|O_NOCTTY|O_NONBLOCK);
+-        if (r < 0) {
++        if (m->pin_cgroupfs_fd < 0) {
+                 log_error("Failed to open pin file: %m");
+                 return -errno;
+         }
+diff --git a/src/core/dbus-cgroup.c b/src/core/dbus-cgroup.c
+index 775825b..5b1c4e3 100644
+--- a/src/core/dbus-cgroup.c
++++ b/src/core/dbus-cgroup.c
+@@ -173,6 +173,7 @@ int bus_cgroup_set_property(
+ 
+                 if (mode != UNIT_CHECK) {
+                         c->cpu_accounting = b;
++                        u->cgroup_realized_mask &= ~CGROUP_CPUACCT;
+                         unit_write_drop_in_private(u, mode, name, b ? "CPUAccounting=yes" : "CPUAccounting=no");
+                 }
  
- static const CGroupSemantics semantics[] = {
--        { "cpu",     "cpu.shares",                 "CPUShare",              false, parse_cpu_shares,          NULL,       NULL },
-+        { "cpu",     "cpu.shares",                 "CPUShares",             false, parse_cpu_shares,          NULL,       NULL },
-         { "memory",  "memory.soft_limit_in_bytes", "MemorySoftLimit",       false, parse_memory_limit,        NULL,       NULL },
-         { "memory",  "memory.limit_in_bytes",      "MemoryLimit",           false, parse_memory_limit,        NULL,       NULL },
-         { "devices", "devices.allow",              "DeviceAllow",           true,  parse_device,              map_device, NULL },
-diff --git a/src/core/dbus-execute.h b/src/core/dbus-execute.h
-index 91d70e5..698102f 100644
---- a/src/core/dbus-execute.h
-+++ b/src/core/dbus-execute.h
-@@ -63,7 +63,7 @@
-         "  <property name=\"CPUSchedulingPolicy\" type=\"i\" access=\"read\"/>\n" \
-         "  <property name=\"CPUSchedulingPriority\" type=\"i\" access=\"read\"/>\n" \
-         "  <property name=\"CPUAffinity\" type=\"ay\" access=\"read\"/>\n" \
--        "  <property name=\"TimerSlackNS\" type=\"t\" access=\"read\"/>\n" \
-+        "  <property name=\"TimerSlackNSec\" type=\"t\" access=\"read\"/>\n" \
-         "  <property name=\"CPUSchedulingResetOnFork\" type=\"b\" access=\"read\"/>\n" \
-         "  <property name=\"NonBlocking\" type=\"b\" access=\"read\"/>\n" \
-         "  <property name=\"StandardInput\" type=\"s\" access=\"read\"/>\n" \
-diff --git a/src/core/dbus-manager.c b/src/core/dbus-manager.c
-index 56b02a1..2b6d799 100644
---- a/src/core/dbus-manager.c
-+++ b/src/core/dbus-manager.c
-@@ -1550,7 +1550,7 @@ static DBusHandlerResult bus_manager_message_handler(DBusConnection *connection,
-                 _cleanup_strv_free_ char **l = NULL;
-                 char **e = NULL;
- 
--                SELINUX_ACCESS_CHECK(connection, message, "reboot");
-+                SELINUX_ACCESS_CHECK(connection, message, "reload");
- 
-                 r = bus_parse_strv(message, &l);
-                 if (r == -ENOMEM)
-@@ -1577,7 +1577,7 @@ static DBusHandlerResult bus_manager_message_handler(DBusConnection *connection,
-                 _cleanup_strv_free_ char **l = NULL;
-                 char **e = NULL;
- 
--                SELINUX_ACCESS_CHECK(connection, message, "reboot");
-+                SELINUX_ACCESS_CHECK(connection, message, "reload");
- 
-                 r = bus_parse_strv(message, &l);
-                 if (r == -ENOMEM)
-@@ -1605,7 +1605,7 @@ static DBusHandlerResult bus_manager_message_handler(DBusConnection *connection,
-                 char **f = NULL;
-                 DBusMessageIter iter;
- 
--                SELINUX_ACCESS_CHECK(connection, message, "reboot");
-+                SELINUX_ACCESS_CHECK(connection, message, "reload");
- 
-                 if (!dbus_message_iter_init(message, &iter))
-                         goto oom;
-diff --git a/src/core/dbus-swap.c b/src/core/dbus-swap.c
-index 2e99fba..e72749a 100644
---- a/src/core/dbus-swap.c
-+++ b/src/core/dbus-swap.c
-@@ -93,6 +93,7 @@ static DEFINE_BUS_PROPERTY_APPEND_ENUM(bus_swap_append_swap_result, swap_result,
- static const BusProperty bus_swap_properties[] = {
-         { "What",       bus_property_append_string, "s", offsetof(Swap, what),  true },
-         { "Priority",   bus_swap_append_priority,   "i", 0 },
-+        { "TimeoutUSec",bus_property_append_usec,   "t", offsetof(Swap, timeout_usec)},
-         BUS_EXEC_COMMAND_PROPERTY("ExecActivate",   offsetof(Swap, exec_command[SWAP_EXEC_ACTIVATE]),   false),
-         BUS_EXEC_COMMAND_PROPERTY("ExecDeactivate", offsetof(Swap, exec_command[SWAP_EXEC_DEACTIVATE]), false),
-         { "ControlPID", bus_property_append_pid,    "u", offsetof(Swap, control_pid) },
-diff --git a/src/core/main.c b/src/core/main.c
-index 7fc06be..101ce79 100644
---- a/src/core/main.c
-+++ b/src/core/main.c
-@@ -1590,14 +1590,14 @@ int main(int argc, char *argv[]) {
-                         log_error("Failed to adjust timer slack: %m");
+@@ -192,6 +193,7 @@ int bus_cgroup_set_property(
  
-         if (arg_capability_bounding_set_drop) {
--                r = capability_bounding_set_drop(arg_capability_bounding_set_drop, true);
-+                r = capability_bounding_set_drop_usermode(arg_capability_bounding_set_drop);
-                 if (r < 0) {
--                        log_error("Failed to drop capability bounding set: %s", strerror(-r));
-+                        log_error("Failed to drop capability bounding set of usermode helpers: %s", strerror(-r));
-                         goto finish;
+                 if (mode != UNIT_CHECK) {
+                         c->cpu_shares = ul;
++                        u->cgroup_realized_mask &= ~CGROUP_CPU;
+                         unit_write_drop_in_private_format(u, mode, name, "CPUShares=%lu", ul);
                  }
--                r = capability_bounding_set_drop_usermode(arg_capability_bounding_set_drop);
-+                r = capability_bounding_set_drop(arg_capability_bounding_set_drop, true);
-                 if (r < 0) {
--                        log_error("Failed to drop capability bounding set of usermode helpers: %s", strerror(-r));
-+                        log_error("Failed to drop capability bounding set: %s", strerror(-r));
-                         goto finish;
+ 
+@@ -206,6 +208,7 @@ int bus_cgroup_set_property(
+ 
+                 if (mode != UNIT_CHECK) {
+                         c->blockio_accounting = b;
++                        u->cgroup_realized_mask &= ~CGROUP_BLKIO;
+                         unit_write_drop_in_private(u, mode, name, b ? "BlockIOAccounting=yes" : "BlockIOAccounting=no");
+                 }
+ 
+@@ -225,6 +228,7 @@ int bus_cgroup_set_property(
+ 
+                 if (mode != UNIT_CHECK) {
+                         c->blockio_weight = ul;
++                        u->cgroup_realized_mask &= ~CGROUP_BLKIO;
+                         unit_write_drop_in_private_format(u, mode, name, "BlockIOWeight=%lu", ul);
+                 }
+ 
+@@ -294,6 +298,8 @@ int bus_cgroup_set_property(
+                                                 cgroup_context_free_blockio_device_bandwidth(c, a);
+                         }
+ 
++                        u->cgroup_realized_mask &= ~CGROUP_BLKIO;
++
+                         f = open_memstream(&buf, &size);
+                         if (!f)
+                                 return -ENOMEM;
+@@ -375,6 +381,8 @@ int bus_cgroup_set_property(
+                                         cgroup_context_free_blockio_device_weight(c, c->blockio_device_weights);
+                         }
+ 
++                        u->cgroup_realized_mask &= ~CGROUP_BLKIO;
++
+                         f = open_memstream(&buf, &size);
+                         if (!f)
+                                 return -ENOMEM;
+@@ -398,6 +406,7 @@ int bus_cgroup_set_property(
+ 
+                 if (mode != UNIT_CHECK) {
+                         c->memory_accounting = b;
++                        u->cgroup_realized_mask &= ~CGROUP_MEMORY;
+                         unit_write_drop_in_private(u, mode, name, b ? "MemoryAccounting=yes" : "MemoryAccounting=no");
+                 }
+ 
+@@ -412,6 +421,7 @@ int bus_cgroup_set_property(
+ 
+                 if (mode != UNIT_CHECK) {
+                         c->memory_limit = limit;
++                        u->cgroup_realized_mask &= ~CGROUP_MEMORY;
+                         unit_write_drop_in_private_format(u, mode, name, "%s=%" PRIu64, name, limit);
+                 }
+ 
+@@ -433,6 +443,7 @@ int bus_cgroup_set_property(
+                         char *buf;
+ 
+                         c->device_policy = p;
++                        u->cgroup_realized_mask &= ~CGROUP_DEVICE;
+ 
+                         buf = strappenda("DevicePolicy=", policy);
+                         unit_write_drop_in_private(u, mode, name, buf);
+@@ -511,6 +522,8 @@ int bus_cgroup_set_property(
+                                         cgroup_context_free_device_allow(c, c->device_allow);
+                         }
+ 
++                        u->cgroup_realized_mask &= ~CGROUP_DEVICE;
++
+                         f = open_memstream(&buf, &size);
+                         if (!f)
+                                 return -ENOMEM;
+diff --git a/src/core/dbus-execute.c b/src/core/dbus-execute.c
+index 13b3d0d..37d4154 100644
+--- a/src/core/dbus-execute.c
++++ b/src/core/dbus-execute.c
+@@ -842,7 +842,7 @@ int bus_exec_context_set_transient_property(
+                         strv_free(c->environment);
+                         c->environment = e;
+ 
+-                        joined = strv_join(c->environment, " ");
++                        joined = strv_join_quoted(c->environment);
+                         if (!joined)
+                                 return -ENOMEM;
+ 
+diff --git a/src/core/job.c b/src/core/job.c
+index 35a9de6..dc4f441 100644
+--- a/src/core/job.c
++++ b/src/core/job.c
+@@ -1060,6 +1060,9 @@ int job_coldplug(Job *j) {
+         if (r < 0)
+                 return r;
+ 
++        if (j->state == JOB_WAITING)
++                job_add_to_run_queue(j);
++
+         if (j->begin_usec == 0 || j->unit->job_timeout == 0)
+                 return 0;
+ 
+diff --git a/src/core/killall.c b/src/core/killall.c
+index 57ed41c..eab48f7 100644
+--- a/src/core/killall.c
++++ b/src/core/killall.c
+@@ -168,7 +168,7 @@ static int killall(int sig, Set *pids, bool send_sighup) {
+                         continue;
+ 
+                 if (sig == SIGKILL) {
+-                        _cleanup_free_ char *s;
++                        _cleanup_free_ char *s = NULL;
+ 
+                         get_process_comm(pid, &s);
+                         log_notice("Sending SIGKILL to PID "PID_FMT" (%s).", pid, strna(s));
+diff --git a/src/core/machine-id-setup.c b/src/core/machine-id-setup.c
+index d459afe..2a58e48 100644
+--- a/src/core/machine-id-setup.c
++++ b/src/core/machine-id-setup.c
+@@ -93,32 +93,9 @@ static int generate(char id[34], const char *root) {
                  }
          }
-@@ -1650,6 +1650,7 @@ int main(int argc, char *argv[]) {
-         /* This will close all file descriptors that were opened, but
-          * not claimed by any unit. */
-         fdset_free(fds);
-+        fds = NULL;
  
-         if (serialization) {
-                 fclose(serialization);
-@@ -1857,7 +1858,7 @@ finish:
+-        /* If that didn't work, see if we are running in qemu/kvm and a
+-         * machine ID was passed in via -uuid on the qemu/kvm command
+-         * line */
+-
+-        r = detect_vm(&vm_id);
+-        if (r > 0 && streq(vm_id, "kvm")) {
+-                char uuid[37];
+-
+-                fd = open("/sys/class/dmi/id/product_uuid", O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
+-                if (fd >= 0) {
+-                        k = loop_read(fd, uuid, 36, false);
+-                        safe_close(fd);
+-
+-                        if (k >= 36) {
+-                                r = shorten_uuid(id, uuid);
+-                                if (r >= 0) {
+-                                        log_info("Initializing machine ID from KVM UUID.");
+-                                        return 0;
+-                                }
+-                        }
+-                }
+-        }
+-
+-        /* If that didn't work either, see if we are running in a
+-         * container, and a machine ID was passed in via
+-         * $container_uuid the way libvirt/LXC does it */
++        /* If that didn't work, see if we are running in a container,
++         * and a machine ID was passed in via $container_uuid the way
++         * libvirt/LXC does it */
+         r = detect_container(NULL);
+         if (r > 0) {
+                 _cleanup_free_ char *e = NULL;
+@@ -133,6 +110,30 @@ static int generate(char id[34], const char *root) {
+                                 }
+                         }
+                 }
++
++        } else {
++                /* If we are not running in a container, see if we are
++                 * running in qemu/kvm and a machine ID was passed in
++                 * via -uuid on the qemu/kvm command line */
++
++                r = detect_vm(&vm_id);
++                if (r > 0 && streq(vm_id, "kvm")) {
++                        char uuid[37];
++
++                        fd = open("/sys/class/dmi/id/product_uuid", O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
++                        if (fd >= 0) {
++                                k = loop_read(fd, uuid, 36, false);
++                                safe_close(fd);
++
++                                if (k >= 36) {
++                                        r = shorten_uuid(id, uuid);
++                                        if (r >= 0) {
++                                                log_info("Initializing machine ID from KVM UUID.");
++                                                return 0;
++                                        }
++                                }
++                        }
++                }
+         }
+ 
+         /* If that didn't work, generate a random machine id */
+diff --git a/src/core/main.c b/src/core/main.c
+index 41605ee..c65701d 100644
+--- a/src/core/main.c
++++ b/src/core/main.c
+@@ -1840,6 +1840,7 @@ finish:
+         if (reexecute) {
+                 const char **args;
+                 unsigned i, args_size;
++                sigset_t ss;
+ 
+                 /* Close and disarm the watchdog, so that the new
+                  * instance can reinitialize it, but doesn't get
+@@ -1883,7 +1884,7 @@ finish:
                          char_array_0(sfd);
  
                          i = 0;
@@ -147,69 +411,252 @@ index 7fc06be..101ce79 100644
                          if (switch_root_dir)
                                  args[i++] = "--switched-root";
                          args[i++] = arg_running_as == SYSTEMD_SYSTEM ? "--system" : "--user";
+@@ -1923,6 +1924,13 @@ finish:
+                 args[i++] = NULL;
+                 assert(i <= args_size);
+ 
++                /* reenable any blocked signals, especially important
++                 * if we switch from initial ramdisk to init=... */
++                reset_all_signal_handlers();
++
++                assert_se(sigemptyset(&ss) == 0);
++                assert_se(sigprocmask(SIG_SETMASK, &ss, NULL) == 0);
++
+                 if (switch_root_init) {
+                         args[0] = switch_root_init;
+                         execv(args[0], (char* const*) args);
 diff --git a/src/core/manager.c b/src/core/manager.c
-index c7f8f20..0508628 100644
+index 224106c..7342095 100644
 --- a/src/core/manager.c
 +++ b/src/core/manager.c
-@@ -1372,7 +1372,7 @@ static int manager_process_signal_fd(Manager *m) {
+@@ -422,7 +422,7 @@ int manager_new(SystemdRunningAs running_as, Manager **_m) {
+                 return -ENOMEM;
  
-                 case SIGINT:
-                         if (m->running_as == SYSTEMD_SYSTEM) {
--                                manager_start_target(m, SPECIAL_CTRL_ALT_DEL_TARGET, JOB_REPLACE);
-+                                manager_start_target(m, SPECIAL_CTRL_ALT_DEL_TARGET, JOB_REPLACE_IRREVERSIBLY);
-                                 break;
-                         }
+ #ifdef ENABLE_EFI
+-        if (detect_container(NULL) <= 0)
++        if (running_as == SYSTEMD_SYSTEM && detect_container(NULL) <= 0)
+                 boot_timestamps(&m->userspace_timestamp, &m->firmware_timestamp, &m->loader_timestamp);
+ #endif
+ 
+@@ -2129,9 +2129,6 @@ int manager_serialize(Manager *m, FILE *f, FDSet *fds, bool switching_root) {
+                 if (u->id != t)
+                         continue;
+ 
+-                if (!unit_can_serialize(u))
+-                        continue;
+-
+                 /* Start marker */
+                 fputs(u->id, f);
+                 fputc('\n', f);
+diff --git a/src/core/namespace.c b/src/core/namespace.c
+index 9f15211..e41cf5b 100644
+--- a/src/core/namespace.c
++++ b/src/core/namespace.c
+@@ -42,6 +42,7 @@
+ #include "mkdir.h"
+ #include "dev-setup.h"
+ #include "def.h"
++#include "label.h"
+ 
+ typedef enum MountMode {
+         /* This is ordered by priority! */
+@@ -68,6 +69,7 @@ static int append_mounts(BindMount **p, char **strv, MountMode mode) {
+         STRV_FOREACH(i, strv) {
+ 
+                 (*p)->ignore = false;
++                (*p)->done = false;
+ 
+                 if ((mode == INACCESSIBLE || mode == READONLY || mode == READWRITE) && (*i)[0] == '-') {
+                         (*p)->ignore = true;
+@@ -217,7 +219,10 @@ static int mount_dev(BindMount *m) {
+                         goto fail;
+                 }
  
++                label_context_set(d, st.st_mode);
+                 r = mknod(dn, st.st_mode, st.st_rdev);
++                label_context_clear();
++
+                 if (r < 0) {
+                         r = -errno;
+                         goto fail;
+@@ -350,7 +355,7 @@ int setup_namespace(
+                 private_dev;
+ 
+         if (n > 0) {
+-                m = mounts = (BindMount *) alloca(n * sizeof(BindMount));
++                m = mounts = (BindMount *) alloca0(n * sizeof(BindMount));
+                 r = append_mounts(&m, read_write_dirs, READWRITE);
+                 if (r < 0)
+                         return r;
 diff --git a/src/core/service.c b/src/core/service.c
-index 3617c24..4d0e2ad 100644
+index ae3695a..6b3aa45 100644
 --- a/src/core/service.c
 +++ b/src/core/service.c
-@@ -2642,6 +2642,9 @@ static int service_serialize(Unit *u, FILE *f, FDSet *fds) {
-         if (s->exec_context.var_tmp_dir)
-                 unit_serialize_item(u, f, "var-tmp-dir", s->exec_context.var_tmp_dir);
+@@ -1096,11 +1096,6 @@ static int service_verify(Service *s) {
+                 return -EINVAL;
+         }
+ 
+-        if (s->type == SERVICE_ONESHOT && s->restart != SERVICE_RESTART_NO) {
+-                log_error_unit(UNIT(s)->id, "%s has Restart setting other than no, which isn't allowed for Type=oneshot services. Refusing.", UNIT(s)->id);
+-                return -EINVAL;
+-        }
+-
+         if (s->type == SERVICE_DBUS && !s->bus_name) {
+                 log_error_unit(UNIT(s)->id, "%s is of type D-Bus but no D-Bus service name has been specified. Refusing.", UNIT(s)->id);
+                 return -EINVAL;
+diff --git a/src/core/socket.c b/src/core/socket.c
+index 7c18a2b..1a560a6 100644
+--- a/src/core/socket.c
++++ b/src/core/socket.c
+@@ -663,16 +663,25 @@ static int instance_from_socket(int fd, unsigned nr, char **instance) {
+                 int k;
+ 
+                 k = getpeercred(fd, &ucred);
+-                if (k < 0)
++                if (k == -ENODATA) {
++                        /* This handles the case where somebody is
++                         * connecting from another pid/uid namespace
++                         * (e.g. from outside of our container). */
++                        if (asprintf(&r,
++                                     "%u-unknown",
++                                     nr) < 0)
++                                return -ENOMEM;
++                }
++                else if (k < 0)
+                         return k;
+-
+-                if (asprintf(&r,
+-                             "%u-%lu-%lu",
+-                             nr,
+-                             (unsigned long) ucred.pid,
+-                             (unsigned long) ucred.uid) < 0)
+-                        return -ENOMEM;
+-
++                else {
++                        if (asprintf(&r,
++                                     "%u-%lu-%lu",
++                                     nr,
++                                     (unsigned long) ucred.pid,
++                                     (unsigned long) ucred.uid) < 0)
++                                return -ENOMEM;
++                }
+                 break;
+         }
+ 
+@@ -1242,6 +1251,8 @@ static int socket_spawn(Socket *s, ExecCommand *c, pid_t *_pid) {
+                        NULL,
+                        s->exec_runtime,
+                        &pid);
++        if (r < 0)
++                goto fail;
  
-+        if (s->forbid_restart)
-+                unit_serialize_item(u, f, "forbid-restart", yes_no(s->forbid_restart));
+         strv_free(argv);
+         if (r < 0)
+@@ -1497,6 +1508,12 @@ static void socket_enter_running(Socket *s, int cfd) {
+                         }
+ 
+                 if (!pending) {
++                        if (!UNIT_ISSET(s->service)) {
++                                log_error_unit(UNIT(s)->id, "%s: service to activate vanished, refusing activation.", UNIT(s)->id);
++                                r = -ENOENT;
++                                goto fail;
++                        }
 +
-         return 0;
+                         r = manager_add_job(UNIT(s)->manager, JOB_START, UNIT_DEREF(s->service), JOB_REPLACE, true, &error, NULL);
+                         if (r < 0)
+                                 goto fail;
+diff --git a/src/core/timer.c b/src/core/timer.c
+index 6c85304..720b8af 100644
+--- a/src/core/timer.c
++++ b/src/core/timer.c
+@@ -111,6 +111,23 @@ static int timer_add_default_dependencies(Timer *t) {
+         return unit_add_two_dependencies_by_name(UNIT(t), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true);
  }
  
-@@ -2776,6 +2779,14 @@ static int service_deserialize_item(Unit *u, const char *key, const char *value,
-                         return log_oom();
- 
-                 s->exec_context.var_tmp_dir = t;
-+        } else if (streq(key, "forbid-restart")) {
-+                int b;
++static void update_stampfile(Timer *t, usec_t timestamp) {
++        _cleanup_close_ int fd = -1;
 +
-+                b = parse_boolean(value);
-+                if (b < 0)
-+                        log_debug_unit(u->id, "Failed to parse forbid-restart value %s", value);
-+                else
-+                        s->forbid_restart = b;
-         } else
-                 log_debug_unit(u->id, "Unknown serialization key '%s'", key);
- 
-diff --git a/src/core/snapshot.c b/src/core/snapshot.c
-index a63eccd..a6807eb 100644
---- a/src/core/snapshot.c
-+++ b/src/core/snapshot.c
-@@ -217,8 +217,10 @@ int snapshot_create(Manager *m, const char *name, bool cleanup, DBusError *e, Sn
-                         if (asprintf(&n, "snapshot-%u.snapshot", ++ m->n_snapshots) < 0)
-                                 return -ENOMEM;
++        mkdir_parents_label(t->stamp_path, 0755);
++
++        /* Update the file atime + mtime, if we can */
++        fd = open(t->stamp_path, O_WRONLY|O_CREAT|O_TRUNC|O_CLOEXEC, 0644);
++        if (fd >= 0) {
++                struct timespec ts[2];
++
++                timespec_store(&ts[0], timestamp);
++                ts[1] = ts[0];
++
++                futimens(fd, ts);
++        }
++}
++
+ static int timer_setup_persistent(Timer *t) {
+         int r;
  
--                        if (!manager_get_unit(m, n))
-+                        if (!manager_get_unit(m, n)) {
-+                                name = n;
-                                 break;
-+                        }
+@@ -131,7 +148,7 @@ static int timer_setup_persistent(Timer *t) {
  
-                         free(n);
-                 }
+                 e = getenv("XDG_DATA_HOME");
+                 if (e)
+-                        t->stamp_path = strjoin(e, "/systemd/timers/", UNIT(t)->id, NULL);
++                        t->stamp_path = strjoin(e, "/systemd/timers/stamp-", UNIT(t)->id, NULL);
+                 else {
+ 
+                         _cleanup_free_ char *h = NULL;
+@@ -496,22 +513,8 @@ static void timer_enter_running(Timer *t) {
+ 
+         dual_timestamp_get(&t->last_trigger);
+ 
+-        if (t->stamp_path) {
+-                _cleanup_close_ int fd = -1;
+-
+-                mkdir_parents_label(t->stamp_path, 0755);
+-
+-                /* Update the file atime + mtime, if we can */
+-                fd = open(t->stamp_path, O_WRONLY|O_CREAT|O_TRUNC|O_CLOEXEC, 0644);
+-                if (fd >= 0) {
+-                        struct timespec ts[2];
+-
+-                        timespec_store(&ts[0], t->last_trigger.realtime);
+-                        ts[1] = ts[0];
+-
+-                        futimens(fd, ts);
+-                }
+-        }
++        if (t->stamp_path)
++                update_stampfile(t, t->last_trigger.realtime);
+ 
+         timer_set_state(t, TIMER_RUNNING);
+         return;
+@@ -539,6 +542,11 @@ static int timer_start(Unit *u) {
+ 
+                 if (stat(t->stamp_path, &st) >= 0)
+                         t->last_trigger.realtime = timespec_load(&st.st_atim);
++                else if (errno == ENOENT)
++                        /* The timer has never run before,
++                         * make sure a stamp file exists.
++                         */
++                        update_stampfile(t, now(CLOCK_REALTIME));
+         }
+ 
+         t->result = TIMER_SUCCESS;
+diff --git a/src/core/transaction.c b/src/core/transaction.c
+index d00f427..2befc32 100644
+--- a/src/core/transaction.c
++++ b/src/core/transaction.c
+@@ -378,7 +378,7 @@ static int transaction_verify_order_one(Transaction *tr, Job *j, Job *from, unsi
+                                       "Found dependency on %s/%s",
+                                       k->unit->id, job_type_to_string(k->type));
+ 
+-                        if (!delete &&
++                        if (!delete && hashmap_get(tr->jobs, k->unit) &&
+                             !unit_matters_to_anchor(k->unit, k)) {
+                                 /* Ok, we can drop this one, so let's
+                                  * do so. */
 diff --git a/src/core/umount.c b/src/core/umount.c
-index 1e95ad7..9f0e471 100644
+index d1258f0..0311812 100644
 --- a/src/core/umount.c
 +++ b/src/core/umount.c
-@@ -435,6 +435,8 @@ static int mount_points_list_umount(MountPoint **head, bool *changed, bool log_e
+@@ -404,6 +404,8 @@ static int mount_points_list_umount(MountPoint **head, bool *changed, bool log_e
                   * anyway, since we are running from it. They have
                   * already been remounted ro. */
                  if (path_equal(m->path, "/")
@@ -218,285 +665,986 @@ index 1e95ad7..9f0e471 100644
  #ifndef HAVE_SPLIT_USR
                      || path_equal(m->path, "/usr")
  #endif
+diff --git a/src/core/unit.c b/src/core/unit.c
+index 153b79b..ed52694 100644
+--- a/src/core/unit.c
++++ b/src/core/unit.c
+@@ -2287,25 +2287,25 @@ bool unit_can_serialize(Unit *u) {
+ }
+ 
+ int unit_serialize(Unit *u, FILE *f, FDSet *fds, bool serialize_jobs) {
+-        ExecRuntime *rt;
+         int r;
+ 
+         assert(u);
+         assert(f);
+         assert(fds);
+ 
+-        if (!unit_can_serialize(u))
+-                return 0;
+-
+-        r = UNIT_VTABLE(u)->serialize(u, f, fds);
+-        if (r < 0)
+-                return r;
++        if (unit_can_serialize(u)) {
++                ExecRuntime *rt;
+ 
+-        rt = unit_get_exec_runtime(u);
+-        if (rt) {
+-                r = exec_runtime_serialize(rt, u, f, fds);
++                r = UNIT_VTABLE(u)->serialize(u, f, fds);
+                 if (r < 0)
+                         return r;
++
++                rt = unit_get_exec_runtime(u);
++                if (rt) {
++                        r = exec_runtime_serialize(rt, u, f, fds);
++                        if (r < 0)
++                                return r;
++                }
+         }
+ 
+         dual_timestamp_serialize(f, "inactive-exit-timestamp", &u->inactive_exit_timestamp);
+@@ -2367,17 +2367,14 @@ void unit_serialize_item(Unit *u, FILE *f, const char *key, const char *value) {
+ }
+ 
+ int unit_deserialize(Unit *u, FILE *f, FDSet *fds) {
+-        size_t offset;
+         ExecRuntime **rt = NULL;
++        size_t offset;
+         int r;
+ 
+         assert(u);
+         assert(f);
+         assert(fds);
+ 
+-        if (!unit_can_serialize(u))
+-                return 0;
+-
+         offset = UNIT_VTABLE(u)->exec_runtime_offset;
+         if (offset > 0)
+                 rt = (ExecRuntime**) ((uint8_t*) u + offset);
+@@ -2487,24 +2484,34 @@ int unit_deserialize(Unit *u, FILE *f, FDSet *fds) {
+                         if (!s)
+                                 return -ENOMEM;
+ 
+-                        free(u->cgroup_path);
+-                        u->cgroup_path = s;
++                        if (u->cgroup_path) {
++                                void *p;
+ 
++                                p = hashmap_remove(u->manager->cgroup_unit, u->cgroup_path);
++                                log_info("Removing cgroup_path %s from hashmap (%p)",
++                                         u->cgroup_path, p);
++                                free(u->cgroup_path);
++                        }
++
++                        u->cgroup_path = s;
+                         assert(hashmap_put(u->manager->cgroup_unit, s, u) == 1);
++
+                         continue;
+                 }
+ 
+-                if (rt) {
+-                        r = exec_runtime_deserialize_item(rt, u, l, v, fds);
++                if (unit_can_serialize(u)) {
++                        if (rt) {
++                                r = exec_runtime_deserialize_item(rt, u, l, v, fds);
++                                if (r < 0)
++                                        return r;
++                                if (r > 0)
++                                        continue;
++                        }
++
++                        r = UNIT_VTABLE(u)->deserialize_item(u, l, v, fds);
+                         if (r < 0)
+                                 return r;
+-                        if (r > 0)
+-                                continue;
+                 }
+-
+-                r = UNIT_VTABLE(u)->deserialize_item(u, l, v, fds);
+-                if (r < 0)
+-                        return r;
+         }
+ }
+ 
 diff --git a/src/cryptsetup/cryptsetup-generator.c b/src/cryptsetup/cryptsetup-generator.c
-index 81b7708..edd0b40 100644
+index 75d56dd..be8fb2f 100644
 --- a/src/cryptsetup/cryptsetup-generator.c
 +++ b/src/cryptsetup/cryptsetup-generator.c
-@@ -111,6 +111,7 @@ static int create_disk(
-                 "Conflicts=umount.target\n"
-                 "DefaultDependencies=no\n"
-                 "BindsTo=dev-mapper-%i.device\n"
-+                "IgnoreOnIsolate=true\n"
-                 "After=systemd-readahead-collect.service systemd-readahead-replay.service\n",
-                 f);
- 
-diff --git a/src/fstab-generator/fstab-generator.c b/src/fstab-generator/fstab-generator.c
-index c17299f..6b3e67e 100644
---- a/src/fstab-generator/fstab-generator.c
-+++ b/src/fstab-generator/fstab-generator.c
-@@ -351,7 +351,7 @@ static int add_mount(
- 
-         if (automount && !path_equal(where, "/")) {
-                 automount_name = unit_name_from_path(where, ".automount");
--                if (!name)
-+                if (!automount_name)
+@@ -29,6 +29,7 @@
+ #include "mkdir.h"
+ #include "strv.h"
+ #include "fileio.h"
++#include "path-util.h"
+ 
+ static const char *arg_dest = "/tmp";
+ static bool arg_enabled = true;
+@@ -144,16 +145,19 @@ static int create_disk(
+                         if (!uu)
+                                 return log_oom();
+ 
+-                        if (is_device_path(uu)) {
+-                                _cleanup_free_ char *dd;
++                        if (!path_equal(uu, "/dev/null")) {
+ 
+-                                dd = unit_name_from_path(uu, ".device");
+-                                if (!dd)
+-                                        return log_oom();
++                                if (is_device_path(uu)) {
++                                        _cleanup_free_ char *dd;
+ 
+-                                fprintf(f, "After=%1$s\nRequires=%1$s\n", dd);
+-                        } else
+-                                fprintf(f, "RequiresMountsFor=%s\n", password);
++                                        dd = unit_name_from_path(uu, ".device");
++                                        if (!dd)
++                                                return log_oom();
++
++                                        fprintf(f, "After=%1$s\nRequires=%1$s\n", dd);
++                                } else
++                                        fprintf(f, "RequiresMountsFor=%s\n", password);
++                        }
+                 }
+         }
+ 
+@@ -287,7 +291,7 @@ static int parse_proc_cmdline_item(const char *key, const char *value) {
+         } else if (STR_IN_SET(key, "luks.key", "rd.luks.key") && value) {
+ 
+                 free(arg_keyfile);
+-                arg_keyfile = strdup(key);
++                arg_keyfile = strdup(value);
+                 if (!arg_keyfile)
                          return log_oom();
  
-                 automount_unit = strjoin(arg_dest, "/", automount_name, NULL);
-@@ -596,9 +596,9 @@ static int parse_proc_cmdline(void) {
-                 } else if (startswith(word, "rd.fstab=")) {
- 
-                         if (in_initrd()) {
--                                r = parse_boolean(word + 6);
-+                                r = parse_boolean(word + 9);
-                                 if (r < 0)
--                                        log_warning("Failed to parse fstab switch %s. Ignoring.", word + 6);
-+                                        log_warning("Failed to parse fstab switch %s. Ignoring.", word + 9);
-                                 else
-                                         arg_enabled = r;
-                         }
-diff --git a/src/journal/journal-file.c b/src/journal/journal-file.c
-index 38499a6..bb80905 100644
---- a/src/journal/journal-file.c
-+++ b/src/journal/journal-file.c
-@@ -907,6 +907,8 @@ static int journal_file_append_field(
+diff --git a/src/cryptsetup/cryptsetup.c b/src/cryptsetup/cryptsetup.c
+index 9b9074c..ad6c76c 100644
+--- a/src/cryptsetup/cryptsetup.c
++++ b/src/cryptsetup/cryptsetup.c
+@@ -88,6 +88,13 @@ static int parse_one_option(const char *option) {
+                         return 0;
+                 }
  
-         osize = offsetof(Object, field.payload) + size;
-         r = journal_file_append_object(f, OBJECT_FIELD, osize, &o, &p);
-+        if (r < 0)
++                if (arg_key_size % 8) {
++                        log_error("size= not a multiple of 8, ignoring.");
++                        return 0;
++                }
++
++                arg_key_size /= 8;
++
+         } else if (startswith(option, "key-slot=")) {
+ 
+                 arg_type = CRYPT_LUKS1;
+@@ -404,7 +411,7 @@ static int attach_luks_or_plain(struct crypt_device *cd,
+                 /* for CRYPT_PLAIN limit reads
+                  * from keyfile to key length, and
+                  * ignore keyfile-size */
+-                arg_keyfile_size = arg_key_size / 8;
++                arg_keyfile_size = arg_key_size;
+ 
+                 /* In contrast to what the name
+                  * crypt_setup() might suggest this
+@@ -567,7 +574,7 @@ int main(int argc, char *argv[]) {
+                 else
+                         until = 0;
+ 
+-                arg_key_size = (arg_key_size > 0 ? arg_key_size : 256);
++                arg_key_size = (arg_key_size > 0 ? arg_key_size : (256 / 8));
+ 
+                 if (key_file) {
+                         struct stat st;
+diff --git a/src/fsck/fsck.c b/src/fsck/fsck.c
+index 18f2aca..2a2b1ea 100644
+--- a/src/fsck/fsck.c
++++ b/src/fsck/fsck.c
+@@ -285,7 +285,7 @@ int main(int argc, char *argv[]) {
+ 
+         type = udev_device_get_property_value(udev_device, "ID_FS_TYPE");
+         if (type) {
+-                const char *checker = strappenda("/sbin/fsck.", type);
++                const char *checker = strappenda("/run/current-system/sw/sbin/fsck.", type);
+                 r = access(checker, X_OK);
+                 if (r < 0) {
+                         if (errno == ENOENT) {
+@@ -302,7 +302,7 @@ int main(int argc, char *argv[]) {
+                         return EXIT_FAILURE;
+                 }
+ 
+-        cmdline[i++] = "/sbin/fsck";
++        cmdline[i++] = "/run/current-system/sw/sbin/fsck";
+         cmdline[i++] = "-a";
+         cmdline[i++] = "-T";
+         cmdline[i++] = "-l";
+diff --git a/src/getty-generator/getty-generator.c b/src/getty-generator/getty-generator.c
+index 6a4aa2c..700e90a 100644
+--- a/src/getty-generator/getty-generator.c
++++ b/src/getty-generator/getty-generator.c
+@@ -72,7 +72,7 @@ static int add_serial_getty(const char *tty) {
+ 
+         log_debug("Automatically adding serial getty for /dev/%s.", tty);
+ 
+-        n = unit_name_replace_instance("serial-getty@.service", tty);
++        n = unit_name_from_path_instance("serial-getty", tty, ".service");
+         if (!n)
+                 return log_oom();
+ 
+@@ -86,7 +86,7 @@ static int add_container_getty(const char *tty) {
+ 
+         log_debug("Automatically adding container getty for /dev/pts/%s.", tty);
+ 
+-        n = unit_name_replace_instance("container-getty@.service", tty);
++        n = unit_name_from_path_instance("container-getty", tty, ".service");
+         if (!n)
+                 return log_oom();
+ 
+diff --git a/src/journal/catalog.c b/src/journal/catalog.c
+index 3ed0b7e..02dedc4 100644
+--- a/src/journal/catalog.c
++++ b/src/journal/catalog.c
+@@ -103,7 +103,7 @@ static int finish_item(
+                 const char *payload) {
+ 
+         ssize_t offset;
+-        CatalogItem *i;
++        _cleanup_free_ CatalogItem *i = NULL;
+         int r;
+ 
+         assert(h);
+@@ -126,13 +126,14 @@ static int finish_item(
+         i->offset = htole64((uint64_t) offset);
+ 
+         r = hashmap_put(h, i, i);
+-        if (r == EEXIST) {
++        if (r == -EEXIST) {
+                 log_warning("Duplicate entry for " SD_ID128_FORMAT_STR ".%s, ignoring.",
+                             SD_ID128_FORMAT_VAL(id), language ? language : "C");
+-                free(i);
+                 return 0;
+-        }
++        } else if (r < 0)
 +                return r;
  
-         o->field.hash = htole64(hash);
-         memcpy(o->field.payload, field, size);
++        i = NULL;
+         return 0;
+ }
+ 
+@@ -383,8 +384,8 @@ error:
+ int catalog_update(const char* database, const char* root, const char* const* dirs) {
+         _cleanup_strv_free_ char **files = NULL;
+         char **f;
+-        Hashmap *h;
+         struct strbuf *sb = NULL;
++        _cleanup_hashmap_free_free_ Hashmap *h = NULL;
+         _cleanup_free_ CatalogItem *items = NULL;
+         CatalogItem *i;
+         Iterator j;
+@@ -406,13 +407,17 @@ int catalog_update(const char* database, const char* root, const char* const* di
+         }
+ 
+         STRV_FOREACH(f, files) {
+-                log_debug("reading file '%s'", *f);
+-                catalog_import_file(h, sb, *f);
++                log_debug("Reading file '%s'", *f);
++                r = catalog_import_file(h, sb, *f);
++                if (r < 0) {
++                        log_error("Failed to import file '%s': %s.",
++                                  *f, strerror(-r));
++                        goto finish;
++                }
+         }
+ 
+         if (hashmap_size(h) <= 0) {
+                 log_info("No items in catalog.");
+-                r = 0;
+                 goto finish;
+         } else
+                 log_debug("Found %u items in catalog.", hashmap_size(h));
+@@ -443,11 +448,7 @@ int catalog_update(const char* database, const char* root, const char* const* di
+                 log_debug("%s: wrote %u items, with %zu bytes of strings, %ld total size.",
+                           database, n, sb->len, r);
+ 
+-        r = 0;
+-
+ finish:
+-        if (h)
+-                hashmap_free_free(h);
+         if (sb)
+                 strbuf_cleanup(sb);
+ 
+diff --git a/src/journal/journal-file.c b/src/journal/journal-file.c
+index f2f1f35..fd9d2a8 100644
+--- a/src/journal/journal-file.c
++++ b/src/journal/journal-file.c
+@@ -274,12 +274,6 @@ static int journal_file_verify_header(JournalFile *f) {
+             !VALID64(le64toh(f->header->entry_array_offset)))
+                 return -ENODATA;
+ 
+-        if (le64toh(f->header->data_hash_table_offset) < le64toh(f->header->header_size) ||
+-            le64toh(f->header->field_hash_table_offset) < le64toh(f->header->header_size) ||
+-            le64toh(f->header->tail_object_offset) < le64toh(f->header->header_size) ||
+-            le64toh(f->header->entry_array_offset) < le64toh(f->header->header_size))
+-                return -ENODATA;
+-
+         if (f->writable) {
+                 uint8_t state;
+                 sd_id128_t machine_id;
+diff --git a/src/journal/journal-remote-parse.c b/src/journal/journal-remote-parse.c
+index 142de0e..239ff38 100644
+--- a/src/journal/journal-remote-parse.c
++++ b/src/journal/journal-remote-parse.c
+@@ -40,7 +40,7 @@ void source_free(RemoteSource *source) {
+ 
+ static int get_line(RemoteSource *source, char **line, size_t *size) {
+         ssize_t n, remain;
+-        char *c;
++        char *c = NULL;
+         char *newbuf = NULL;
+         size_t newsize = 0;
+ 
+@@ -49,7 +49,9 @@ static int get_line(RemoteSource *source, char **line, size_t *size) {
+         assert(source->filled <= source->size);
+         assert(source->buf == NULL || source->size > 0);
+ 
+-        c = memchr(source->buf, '\n', source->filled);
++        if (source->buf)
++                c = memchr(source->buf, '\n', source->filled);
++
+         if (c != NULL)
+                 goto docopy;
+ 
+diff --git a/src/journal/journald-kmsg.c b/src/journal/journald-kmsg.c
+index 35948ea..48725e4 100644
+--- a/src/journal/journald-kmsg.c
++++ b/src/journal/journald-kmsg.c
+@@ -152,7 +152,7 @@ static void dev_kmsg_record(Server *s, char *p, size_t l) {
+                 /* Did we lose any? */
+                 if (serial > *s->kernel_seqnum)
+                         server_driver_message(s, SD_MESSAGE_JOURNAL_MISSED, "Missed %"PRIu64" kernel messages",
+-                                              serial - *s->kernel_seqnum - 1);
++                                              serial - *s->kernel_seqnum);
+ 
+                 /* Make sure we never read this one again. Note that
+                  * we always store the next message serial we expect
 diff --git a/src/journal/journald-server.c b/src/journal/journald-server.c
-index 88163c0..e09ba4c 100644
+index 6da81e7..b6f8e7e 100644
 --- a/src/journal/journald-server.c
 +++ b/src/journal/journald-server.c
-@@ -333,8 +333,10 @@ void server_rotate(Server *s) {
-                 if (r < 0)
-                         if (f)
-                                 log_error("Failed to rotate %s: %s", f->path, strerror(-r));
--                        else
-+                        else {
-                                 log_error("Failed to create user journal: %s", strerror(-r));
-+                                hashmap_remove(s->user_journals, k);
-+                        }
-                 else {
-                         hashmap_replace(s->user_journals, k, f);
-                         server_fix_perms(s, f, PTR_TO_UINT32(k));
-@@ -975,7 +977,8 @@ int process_event(Server *s, struct epoll_event *ev) {
-                 ssize_t n;
- 
-                 if (ev->events != EPOLLIN) {
--                        log_error("Got invalid event from epoll.");
-+                        log_error("Got invalid event from epoll for %s: %"PRIx32,
-+                                  "signal fd", ev->events);
-                         return -EIO;
-                 }
+@@ -67,6 +67,7 @@
+ #define DEFAULT_SYNC_INTERVAL_USEC (5*USEC_PER_MINUTE)
+ #define DEFAULT_RATE_LIMIT_INTERVAL (30*USEC_PER_SEC)
+ #define DEFAULT_RATE_LIMIT_BURST 1000
++#define DEFAULT_MAX_FILE_USEC USEC_PER_MONTH
  
-@@ -1024,8 +1027,12 @@ int process_event(Server *s, struct epoll_event *ev) {
-         } else if (ev->data.fd == s->dev_kmsg_fd) {
-                 int r;
+ #define RECHECK_AVAILABLE_SPACE_USEC (30*USEC_PER_SEC)
  
--                if (ev->events != EPOLLIN) {
--                        log_error("Got invalid event from epoll.");
-+                if (ev->events & EPOLLERR)
-+                        log_warning("/dev/kmsg buffer overrun, some messages lost.");
+@@ -1473,6 +1474,8 @@ int server_init(Server *s) {
+         s->forward_to_syslog = true;
+         s->forward_to_wall = true;
+ 
++        s->max_file_usec = DEFAULT_MAX_FILE_USEC;
 +
-+                if (!(ev->events & EPOLLIN)) {
-+                        log_error("Got invalid event from epoll for %s: %"PRIx32,
-+                                  "/dev/kmsg", ev->events);
-                         return -EIO;
-                 }
+         s->max_level_store = LOG_DEBUG;
+         s->max_level_syslog = LOG_DEBUG;
+         s->max_level_kmsg = LOG_NOTICE;
+diff --git a/src/journal/microhttpd-util.c b/src/journal/microhttpd-util.c
+index f693e0f..9a8d5c6 100644
+--- a/src/journal/microhttpd-util.c
++++ b/src/journal/microhttpd-util.c
+@@ -129,7 +129,7 @@ void log_func_gnutls(int level, const char *message) {
+         if (0 <= level && level < (int) ELEMENTSOF(log_level_map))
+                 ourlevel = log_level_map[level];
+         else
+-                level = LOG_DEBUG;
++                ourlevel = LOG_DEBUG;
+ 
+         log_meta(ourlevel, NULL, 0, NULL, "gnutls: %s", message);
+ }
+diff --git a/src/journal/test-catalog.c b/src/journal/test-catalog.c
+index b087a8b..967ab67 100644
+--- a/src/journal/test-catalog.c
++++ b/src/journal/test-catalog.c
+@@ -157,7 +157,8 @@ int main(int argc, char *argv[]) {
+ 
+         setlocale(LC_ALL, "de_DE.UTF-8");
+ 
+-        log_set_max_level(LOG_DEBUG);
++        log_parse_environment();
++        log_open();
+ 
+         test_catalog_file_lang();
+ 
+diff --git a/src/libsystemd/sd-rtnl/rtnl-message.c b/src/libsystemd/sd-rtnl/rtnl-message.c
+index 84a8ffa..e79b318 100644
+--- a/src/libsystemd/sd-rtnl/rtnl-message.c
++++ b/src/libsystemd/sd-rtnl/rtnl-message.c
+@@ -335,24 +335,28 @@ int sd_rtnl_message_link_get_flags(sd_rtnl_message *m, unsigned *flags) {
+ /* If successful the updated message will be correctly aligned, if
+    unsuccessful the old message is untouched. */
+ static int add_rtattr(sd_rtnl_message *m, unsigned short type, const void *data, size_t data_length) {
+-        uint32_t rta_length, message_length;
++        uint32_t rta_length;
++        size_t message_length, padding_length;
+         struct nlmsghdr *new_hdr;
+         struct rtattr *rta;
+         char *padding;
+         unsigned i;
++        int offset;
+ 
+         assert(m);
+         assert(m->hdr);
+         assert(!m->sealed);
+         assert(NLMSG_ALIGN(m->hdr->nlmsg_len) == m->hdr->nlmsg_len);
+-        assert(!data || data_length > 0);
+-        assert(data || m->n_containers < RTNL_CONTAINER_DEPTH);
++        assert(!data || data_length);
++
++        /* get offset of the new attribute */
++        offset = m->hdr->nlmsg_len;
+ 
+         /* get the size of the new rta attribute (with padding at the end) */
+         rta_length = RTA_LENGTH(data_length);
+ 
+         /* get the new message size (with padding at the end) */
+-        message_length = m->hdr->nlmsg_len + RTA_ALIGN(rta_length);
++        message_length = offset + RTA_ALIGN(rta_length);
+ 
+         /* realloc to fit the new attribute */
+         new_hdr = realloc(m->hdr, message_length);
+@@ -361,32 +365,35 @@ static int add_rtattr(sd_rtnl_message *m, unsigned short type, const void *data,
+         m->hdr = new_hdr;
+ 
+         /* get pointer to the attribute we are about to add */
+-        rta = (struct rtattr *) ((uint8_t *) m->hdr + m->hdr->nlmsg_len);
++        rta = (struct rtattr *) ((uint8_t *) m->hdr + offset);
+ 
+         /* if we are inside containers, extend them */
+         for (i = 0; i < m->n_containers; i++)
+-                GET_CONTAINER(m, i)->rta_len += message_length - m->hdr->nlmsg_len;
++                GET_CONTAINER(m, i)->rta_len += message_length - offset;
+ 
+         /* fill in the attribute */
+         rta->rta_type = type;
+         rta->rta_len = rta_length;
+-        if (!data) {
+-                /* this is the start of a new container */
+-                m->container_offsets[m->n_containers ++] = m->hdr->nlmsg_len;
+-        } else {
++        if (data)
+                 /* we don't deal with the case where the user lies about the type
+                  * and gives us too little data (so don't do that)
+-                */
++                 */
+                 padding = mempcpy(RTA_DATA(rta), data, data_length);
+-                /* make sure also the padding at the end of the message is initialized */
+-                memzero(padding,
+-                        (uint8_t *) m->hdr + message_length - (uint8_t *) padding);
++        else {
++                /* if no data was passed, make sure we still initialize the padding
++                   note that we can have data_length > 0 (used by some containers) */
++                padding = RTA_DATA(rta);
++                data_length = 0;
+         }
  
-@@ -1039,7 +1046,9 @@ int process_event(Server *s, struct epoll_event *ev) {
-                    ev->data.fd == s->syslog_fd) {
++        /* make sure also the padding at the end of the message is initialized */
++        padding_length = (uint8_t*)m->hdr + message_length - (uint8_t*)padding;
++        memzero(padding, padding_length);
++
+         /* update message size */
+         m->hdr->nlmsg_len = message_length;
  
-                 if (ev->events != EPOLLIN) {
--                        log_error("Got invalid event from epoll.");
-+                        log_error("Got invalid event from epoll for %s: %"PRIx32,
-+                                  ev->data.fd == s->native_fd ? "native fd" : "syslog fd",
-+                                  ev->events);
-                         return -EIO;
-                 }
+-        return 0;
++        return offset;
+ }
  
-@@ -1140,12 +1149,7 @@ int process_event(Server *s, struct epoll_event *ev) {
-                                 char *e;
+ int sd_rtnl_message_append_string(sd_rtnl_message *m, unsigned short type, const char *data) {
+@@ -761,22 +768,29 @@ int sd_rtnl_message_open_container(sd_rtnl_message *m, unsigned short type) {
  
-                                 if (n > 0 && n_fds == 0) {
--                                        e = memchr(s->buffer, '\n', n);
--                                        if (e)
--                                                *e = 0;
--                                        else
--                                                s->buffer[n] = 0;
--
-+                                        s->buffer[n] = 0;
-                                         server_process_syslog_message(s, strstrip(s->buffer), ucred, tv, label, label_len);
-                                 } else if (n_fds > 0)
-                                         log_warning("Got file descriptors via syslog socket. Ignoring.");
-@@ -1167,7 +1171,8 @@ int process_event(Server *s, struct epoll_event *ev) {
-         } else if (ev->data.fd == s->stdout_fd) {
- 
-                 if (ev->events != EPOLLIN) {
--                        log_error("Got invalid event from epoll.");
-+                        log_error("Got invalid event from epoll for %s: %"PRIx32,
-+                                  "stdout fd", ev->events);
-                         return -EIO;
-                 }
+         assert_return(m, -EINVAL);
+         assert_return(!m->sealed, -EPERM);
++        assert_return(m->n_containers < RTNL_CONTAINER_DEPTH, -ERANGE);
  
-@@ -1178,6 +1183,8 @@ int process_event(Server *s, struct epoll_event *ev) {
-                 StdoutStream *stream;
+         sd_rtnl_message_get_type(m, &rtm_type);
  
-                 if ((ev->events|EPOLLIN|EPOLLHUP) != (EPOLLIN|EPOLLHUP)) {
-+                        log_error("Got invalid event from epoll for %s: %"PRIx32,
-+                                  "stdout stream", ev->events);
-                         log_error("Got invalid event from epoll.");
-                         return -EIO;
-                 }
-diff --git a/src/journal/mmap-cache.c b/src/journal/mmap-cache.c
-index 54bf114..bd197d0 100644
---- a/src/journal/mmap-cache.c
-+++ b/src/journal/mmap-cache.c
-@@ -308,9 +308,13 @@ static void mmap_cache_free(MMapCache *m) {
-         while ((c = hashmap_first(m->contexts)))
-                 context_free(c);
++        int r = -ENOTSUP;
++
+         if (rtnl_message_type_is_link(rtm_type)) {
+ 
+                 if ((type == IFLA_LINKINFO && m->n_containers == 0) ||
+                     (type == IFLA_INFO_DATA && m->n_containers == 1 &&
+                      GET_CONTAINER(m, 0)->rta_type == IFLA_LINKINFO))
+-                        return add_rtattr(m, type, NULL, 0);
++                        r = add_rtattr(m, type, NULL, 0);
+                 else if (type == VETH_INFO_PEER && m->n_containers == 2 &&
+                          GET_CONTAINER(m, 1)->rta_type == IFLA_INFO_DATA &&
+                          GET_CONTAINER(m, 0)->rta_type == IFLA_LINKINFO)
+-                        return add_rtattr(m, type, NULL, sizeof(struct ifinfomsg));
++                        r=  add_rtattr(m, type, NULL, sizeof(struct ifinfomsg));
+         }
  
-+        hashmap_free(m->contexts);
+-        return -ENOTSUP;
++        if (r < 0) return r;
 +
-         while ((f = hashmap_first(m->fds)))
-                 fd_free(f);
++        m->container_offsets[m->n_containers ++] = r;
++
++        return 0;
+ }
+ 
+ int sd_rtnl_message_close_container(sd_rtnl_message *m) {
+diff --git a/src/libudev/libudev-monitor.c b/src/libudev/libudev-monitor.c
+index ba1b04d..85b1e40 100644
+--- a/src/libudev/libudev-monitor.c
++++ b/src/libudev/libudev-monitor.c
+@@ -108,15 +108,13 @@ static struct udev_monitor *udev_monitor_new(struct udev *udev)
+ 
+ /* we consider udev running when /dev is on devtmpfs */
+ static bool udev_has_devtmpfs(struct udev *udev) {
+-        struct file_handle *h;
++        union file_handle_union h = { .handle.handle_bytes = MAX_HANDLE_SZ, };
+         int mount_id;
+         _cleanup_fclose_ FILE *f = NULL;
+         char line[LINE_MAX], *e;
+         int r;
  
-+        hashmap_free(m->fds);
+-        h = alloca(MAX_HANDLE_SZ);
+-        h->handle_bytes = MAX_HANDLE_SZ;
+-        r = name_to_handle_at(AT_FDCWD, "/dev", h, &mount_id, 0);
++        r = name_to_handle_at(AT_FDCWD, "/dev", &h.handle, &mount_id, 0);
+         if (r < 0)
+                 return false;
+ 
+diff --git a/src/login/70-uaccess.rules b/src/login/70-uaccess.rules
+index e1cf897..57f619d 100644
+--- a/src/login/70-uaccess.rules
++++ b/src/login/70-uaccess.rules
+@@ -12,7 +12,7 @@ ENV{MAJOR}=="", GOTO="uaccess_end"
+ SUBSYSTEM=="usb", ENV{ID_USB_INTERFACES}=="*:060101:*", TAG+="uaccess"
+ 
+ # Digicams with proprietary protocol
+-ENV{ID_GPHOTO2}=="*?", TAG+="uaccess"
++ENV{ID_GPHOTO2}=="?*", TAG+="uaccess"
+ 
+ # SCSI and USB scanners
+ ENV{libsane_matched}=="yes", TAG+="uaccess"
+@@ -49,13 +49,13 @@ SUBSYSTEM=="drm", KERNEL=="card*|renderD*", TAG+="uaccess"
+ SUBSYSTEM=="misc", KERNEL=="kvm", TAG+="uaccess"
+ 
+ # smart-card readers
+-ENV{ID_SMARTCARD_READER}=="*?", TAG+="uaccess"
++ENV{ID_SMARTCARD_READER}=="?*", TAG+="uaccess"
+ 
+ # (USB) authentication devices
+-ENV{ID_SECURITY_TOKEN}=="*?", TAG+="uaccess"
++ENV{ID_SECURITY_TOKEN}=="?*", TAG+="uaccess"
+ 
+ # PDA devices
+-ENV{ID_PDA}=="*?", TAG+="uaccess"
++ENV{ID_PDA}=="?*", TAG+="uaccess"
+ 
+ # Programmable remote control
+ ENV{ID_REMOTE_CONTROL}=="1", TAG+="uaccess"
+@@ -64,10 +64,10 @@ ENV{ID_REMOTE_CONTROL}=="1", TAG+="uaccess"
+ SUBSYSTEM=="input", ENV{ID_INPUT_JOYSTICK}=="?*", TAG+="uaccess"
+ 
+ # color measurement devices
+-ENV{COLOR_MEASUREMENT_DEVICE}=="*?", TAG+="uaccess"
++ENV{COLOR_MEASUREMENT_DEVICE}=="?*", TAG+="uaccess"
+ 
+ # DDC/CI device, usually high-end monitors such as the DreamColor
+-ENV{DDC_DEVICE}=="*?", TAG+="uaccess"
++ENV{DDC_DEVICE}=="?*", TAG+="uaccess"
+ 
+ # media player raw devices (for user-mode drivers, Android SDK, etc.)
+ SUBSYSTEM=="usb", ENV{ID_MEDIA_PLAYER}=="?*", TAG+="uaccess"
+diff --git a/src/login/logind-acl.c b/src/login/logind-acl.c
+index dc86f0f..4bbeb64 100644
+--- a/src/login/logind-acl.c
++++ b/src/login/logind-acl.c
+@@ -279,7 +279,9 @@ int devnode_acl_all(struct udev *udev,
+ 
+                 log_debug("Fixing up ACLs at %s for seat %s", n, seat);
+                 k = devnode_acl(n, flush, del, old_uid, add, new_uid);
+-                if (k < 0)
++                if (k == -ENOENT)
++                        log_debug("Device %s disappeared while setting ACLs", n);
++                else if (k < 0)
+                         r = k;
+         }
+ 
+diff --git a/src/login/logind-action.c b/src/login/logind-action.c
+index 1928f43..d69c7ad 100644
+--- a/src/login/logind-action.c
++++ b/src/login/logind-action.c
+@@ -79,14 +79,12 @@ int manager_handle_action(
+                         return 0;
+                 }
+ 
+-                /* If we have more than one or no displays connected,
+-                 * don't react to lid closing. The no display case we
+-                 * treat like this under the assumption that there is
+-                 * no modern drm driver available. */
++                /* If we have more than one display connected,
++                 * don't react to lid closing. */
+                 n = manager_count_displays(m);
+                 if (n < 0)
+                         log_warning("Display counting failed: %s", strerror(-n));
+-                else if (n != 1) {
++                else if (n > 1) {
+                         log_debug("Ignoring lid switch request, %i displays connected.", n);
+                         return 0;
+                 }
+diff --git a/src/login/logind-seat.c b/src/login/logind-seat.c
+index 3f5efdc..1ee6ced 100644
+--- a/src/login/logind-seat.c
++++ b/src/login/logind-seat.c
+@@ -275,8 +275,13 @@ int seat_switch_to(Seat *s, unsigned int num) {
+         if (!num)
+                 return -EINVAL;
+ 
+-        if (num >= s->position_count || !s->positions[num])
++        if (num >= s->position_count || !s->positions[num]) {
++                /* allow switching to unused VTs to trigger auto-activate */
++                if (seat_has_vts(s) && num < 64)
++                        return chvt(num);
 +
-         while (m->unused)
-                 window_free(m->unused);
+                 return -EINVAL;
++        }
  
-diff --git a/src/libsystemd-bus/bus-internal.c b/src/libsystemd-bus/bus-internal.c
-index 0e66f3d..cac948e 100644
---- a/src/libsystemd-bus/bus-internal.c
-+++ b/src/libsystemd-bus/bus-internal.c
-@@ -63,7 +63,7 @@ bool object_path_is_valid(const char *p) {
+         return session_activate(s->positions[num]);
+ }
+diff --git a/src/login/logind-session.c b/src/login/logind-session.c
+index 4ca6b5d..02a780d 100644
+--- a/src/login/logind-session.c
++++ b/src/login/logind-session.c
+@@ -213,7 +213,6 @@ int session_save(Session *s) {
+ 
+         if (s->scope)
+                 fprintf(f, "SCOPE=%s\n", s->scope);
+-
+         if (s->scope_job)
+                 fprintf(f, "SCOPE_JOB=%s\n", s->scope_job);
  
- bool interface_name_is_valid(const char *p) {
-         const char *q;
--        bool dot, found_dot;
-+        bool dot, found_dot = false;
+@@ -229,17 +228,54 @@ int session_save(Session *s) {
+         if (s->display)
+                 fprintf(f, "DISPLAY=%s\n", s->display);
  
-         if (isempty(p))
-                 return false;
-@@ -103,7 +103,7 @@ bool interface_name_is_valid(const char *p) {
+-        if (s->remote_host)
+-                fprintf(f, "REMOTE_HOST=%s\n", s->remote_host);
++        if (s->remote_host) {
++                _cleanup_free_ char *escaped;
++
++                escaped = cescape(s->remote_host);
++                if (!escaped) {
++                        r = -ENOMEM;
++                        goto finish;
++                }
++
++                fprintf(f, "REMOTE_HOST=%s\n", escaped);
++        }
++
++        if (s->remote_user) {
++                _cleanup_free_ char *escaped;
++
++                escaped = cescape(s->remote_user);
++                if (!escaped) {
++                        r = -ENOMEM;
++                        goto finish;
++                }
++
++                fprintf(f, "REMOTE_USER=%s\n", escaped);
++        }
++
++        if (s->service) {
++                _cleanup_free_ char *escaped;
+ 
+-        if (s->remote_user)
+-                fprintf(f, "REMOTE_USER=%s\n", s->remote_user);
++                escaped = cescape(s->service);
++                if (!escaped) {
++                        r = -ENOMEM;
++                        goto finish;
++                }
++
++                fprintf(f, "SERVICE=%s\n", escaped);
++        }
  
- bool service_name_is_valid(const char *p) {
-         const char *q;
--        bool dot, found_dot, unique;
-+        bool dot, found_dot = false, unique;
+-        if (s->service)
+-                fprintf(f, "SERVICE=%s\n", s->service);
++        if (s->desktop) {
++                _cleanup_free_ char *escaped;
  
-         if (isempty(p))
-                 return false;
-diff --git a/src/libsystemd-bus/sd-bus.c b/src/libsystemd-bus/sd-bus.c
-index 7d6d848..b0eb2f1 100644
---- a/src/libsystemd-bus/sd-bus.c
-+++ b/src/libsystemd-bus/sd-bus.c
-@@ -1088,11 +1088,11 @@ static int dispatch_rqueue(sd_bus *bus, sd_bus_message **m) {
-                 if (r == 0)
-                         return ret;
- 
--                r = 1;
-+                ret = 1;
-         } while (!z);
- 
-         *m = z;
--        return 1;
-+        return ret;
+-        if (s->desktop)
+-                fprintf(f, "DESKTOP=%s\n", s->desktop);
++
++                escaped = cescape(s->desktop);
++                if (!escaped) {
++                        r = -ENOMEM;
++                        goto finish;
++                }
++
++                fprintf(f, "DESKTOP=%s\n", escaped);
++        }
+ 
+         if (s->seat && seat_has_vts(s->seat))
+                 fprintf(f, "VTNR=%u\n", s->vtnr);
+@@ -972,6 +1008,10 @@ void session_mute_vt(Session *s) {
+         if (vt < 0)
+                 return;
+ 
++        r = fchown(vt, s->user->uid, -1);
++        if (r < 0)
++                goto error;
++
+         r = ioctl(vt, KDSKBMODE, K_OFF);
+         if (r < 0)
+                 goto error;
+@@ -1026,6 +1066,8 @@ void session_restore_vt(Session *s) {
+         mode.mode = VT_AUTO;
+         ioctl(vt, VT_SETMODE, &mode);
+ 
++        fchown(vt, 0, -1);
++
+         s->vtfd = safe_close(s->vtfd);
  }
  
- int sd_bus_send(sd_bus *bus, sd_bus_message *m, uint64_t *serial) {
-diff --git a/src/libudev/libudev-enumerate.c b/src/libudev/libudev-enumerate.c
-index 5ccaabd..100c1fb 100644
---- a/src/libudev/libudev-enumerate.c
-+++ b/src/libudev/libudev-enumerate.c
-@@ -299,7 +299,7 @@ _public_ struct udev_list_entry *udev_enumerate_get_list_entry(struct udev_enume
-                         /* skip to be delayed devices, and move the to
-                          * the point where the prefix changes. We can
-                          * only move one item at a time. */
--                        if (!move_later) {
-+                        if (move_later == -1) {
-                                 move_later_prefix = devices_delay_later(udev_enumerate->udev, entry->syspath);
- 
-                                 if (move_later_prefix > 0) {
-@@ -718,6 +718,8 @@ static bool match_subsystem(struct udev_enumerate *udev_enumerate, const char *s
- {
-         struct udev_list_entry *list_entry;
+diff --git a/src/login/org.freedesktop.login1.policy.in b/src/login/org.freedesktop.login1.policy.in
+index b96d32d..b8e90f1 100644
+--- a/src/login/org.freedesktop.login1.policy.in
++++ b/src/login/org.freedesktop.login1.policy.in
+@@ -254,7 +254,7 @@
+                 <defaults>
+                         <allow_any>auth_admin_keep</allow_any>
+                         <allow_inactive>auth_admin_keep</allow_inactive>
+-                        <allow_active>auth_admin_keep</allow_active>
++                        <allow_active>yes</allow_active>
+                 </defaults>
+                 <annotate key="org.freedesktop.policykit.imply">org.freedesktop.login1.hibernate</annotate>
+         </action>
+diff --git a/src/login/pam-module.c b/src/login/pam-module.c
+index 9873dd5..1259457 100644
+--- a/src/login/pam-module.c
++++ b/src/login/pam-module.c
+@@ -475,7 +475,7 @@ _public_ PAM_EXTERN int pam_sm_open_session(
+         }
  
-+        subsystem = subsystem ? : "";
+         if (session_fd >= 0) {
+-                session_fd = dup(session_fd);
++                session_fd = fcntl(session_fd, F_DUPFD_CLOEXEC, 3);
+                 if (session_fd < 0) {
+                         pam_syslog(handle, LOG_ERR, "Failed to dup session fd: %m");
+                         return PAM_SESSION_ERR;
+diff --git a/src/machine/machine.c b/src/machine/machine.c
+index 9a5cc9a..de701ad 100644
+--- a/src/machine/machine.c
++++ b/src/machine/machine.c
+@@ -123,17 +123,42 @@ int machine_save(Machine *m) {
+                 "NAME=%s\n",
+                 m->name);
+ 
+-        if (m->unit)
+-                fprintf(f, "SCOPE=%s\n", m->unit); /* We continue to call this "SCOPE=" because it is internal only, and we want to stay compatible with old files */
++        if (m->unit) {
++                _cleanup_free_ char *escaped;
 +
-         udev_list_entry_foreach(list_entry, udev_list_get_entry(&udev_enumerate->subsystem_nomatch_list)) {
-                 if (fnmatch(udev_list_entry_get_name(list_entry), subsystem, 0) == 0)
-                         return false;
-@@ -826,23 +828,27 @@ nomatch:
- static int parent_add_child(struct udev_enumerate *enumerate, const char *path)
- {
-         struct udev_device *dev;
-+        int r = 0;
++                escaped = cescape(m->unit);
++                if (!escaped) {
++                        r = -ENOMEM;
++                        goto finish;
++                }
++
++                fprintf(f, "SCOPE=%s\n", escaped); /* We continue to call this "SCOPE=" because it is internal only, and we want to stay compatible with old files */
++        }
+ 
+         if (m->scope_job)
+                 fprintf(f, "SCOPE_JOB=%s\n", m->scope_job);
+ 
+-        if (m->service)
+-                fprintf(f, "SERVICE=%s\n", m->service);
++        if (m->service) {
++                _cleanup_free_ char *escaped;
+ 
+-        if (m->root_directory)
+-                fprintf(f, "ROOT=%s\n", m->root_directory);
++                escaped = cescape(m->service);
++                if (!escaped) {
++                        r = -ENOMEM;
++                        goto finish;
++                }
++                fprintf(f, "SERVICE=%s\n", escaped);
++        }
++
++        if (m->root_directory) {
++                _cleanup_free_ char *escaped;
++
++                escaped = cescape(m->root_directory);
++                if (!escaped) {
++                        r = -ENOMEM;
++                        goto finish;
++                }
++                fprintf(f, "ROOT=%s\n", escaped);
++        }
+ 
+         if (!sd_id128_equal(m->id, SD_ID128_NULL))
+                 fprintf(f, "ID=" SD_ID128_FORMAT_STR "\n", SD_ID128_FORMAT_VAL(m->id));
+@@ -330,16 +355,18 @@ static int machine_stop_scope(Machine *m) {
+         if (!m->unit)
+                 return 0;
+ 
+-        r = manager_stop_unit(m->manager, m->unit, &error, &job);
+-        if (r < 0) {
+-                log_error("Failed to stop machine scope: %s", bus_error_message(&error, r));
+-                return r;
++        if (!m->registered) {
++                r = manager_stop_unit(m->manager, m->unit, &error, &job);
++                if (r < 0) {
++                        log_error("Failed to stop machine scope: %s", bus_error_message(&error, r));
++                        return r;
++                }
+         }
  
-         dev = udev_device_new_from_syspath(enumerate->udev, path);
-         if (dev == NULL)
-                 return -ENODEV;
+         free(m->scope_job);
+         m->scope_job = job;
  
-         if (!match_subsystem(enumerate, udev_device_get_subsystem(dev)))
--                return 0;
-+                goto nomatch;
-         if (!match_sysname(enumerate, udev_device_get_sysname(dev)))
--                return 0;
-+                goto nomatch;
-         if (!match_property(enumerate, dev))
--                return 0;
-+                goto nomatch;
-         if (!match_sysattr(enumerate, dev))
--                return 0;
-+                goto nomatch;
+-        return r;
++        return 0;
+ }
  
-         syspath_add(enumerate, udev_device_get_syspath(dev));
-+        r = 1;
+ int machine_stop(Machine *m) {
+@@ -415,6 +442,8 @@ int machine_kill(Machine *m, KillWho who, int signo) {
+ 
+                 if (kill(m->leader, signo) < 0)
+                         return -errno;
 +
-+nomatch:
-         udev_device_unref(dev);
--        return 1;
-+        return r;
++                return 0;
+         }
+ 
+         /* Otherwise make PID 1 do it for us, for the entire cgroup */
+diff --git a/src/machine/machine.h b/src/machine/machine.h
+index f4aefc5..de3536d 100644
+--- a/src/machine/machine.h
++++ b/src/machine/machine.h
+@@ -72,6 +72,7 @@ struct Machine {
+ 
+         bool in_gc_queue:1;
+         bool started:1;
++        bool registered:1;
+ 
+         sd_bus_message *create_message;
+ 
+diff --git a/src/machine/machined-dbus.c b/src/machine/machined-dbus.c
+index 9473105..154a335 100644
+--- a/src/machine/machined-dbus.c
++++ b/src/machine/machined-dbus.c
+@@ -241,6 +241,7 @@ static int method_create_or_register_machine(Manager *manager, sd_bus_message *m
+         m->leader = leader;
+         m->class = c;
+         m->id = id;
++        m->registered = true;
+ 
+         if (!isempty(service)) {
+                 m->service = strdup(service);
+diff --git a/src/nspawn/nspawn.c b/src/nspawn/nspawn.c
+index 9a9ed9d..c3e6d23 100644
+--- a/src/nspawn/nspawn.c
++++ b/src/nspawn/nspawn.c
+@@ -769,6 +769,15 @@ static int setup_resolv_conf(const char *dest) {
+         return 0;
  }
  
- static int parent_crawl_children(struct udev_enumerate *enumerate, const char *path, int maxdepth)
-diff --git a/src/libudev/libudev.sym b/src/libudev/libudev.sym
-index 8e09430..1e6f885 100644
---- a/src/libudev/libudev.sym
-+++ b/src/libudev/libudev.sym
-@@ -109,5 +109,6 @@ global:
- } LIBUDEV_189;
- 
- LIBUDEV_199 {
-+global:
-         udev_device_set_sysattr_value;
- } LIBUDEV_196;
-diff --git a/src/modules-load/modules-load.c b/src/modules-load/modules-load.c
-index 7b19ee0..49ee420 100644
---- a/src/modules-load/modules-load.c
-+++ b/src/modules-load/modules-load.c
-@@ -302,8 +302,8 @@ int main(int argc, char *argv[]) {
- 
-                 STRV_FOREACH(i, arg_proc_cmdline_modules) {
-                         k = load_module(ctx, *i);
--                        if (k < 0)
--                                r = EXIT_FAILURE;
-+                        if (k < 0 && r == 0)
-+                                r = k;
++static char* id128_format_as_uuid(sd_id128_t id, char s[37]) {
++
++        snprintf(s, 37,
++                 "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
++                 SD_ID128_FORMAT_VAL(id));
++
++        return s;
++}
++
+ static int setup_boot_id(const char *dest) {
+         _cleanup_free_ char *from = NULL, *to = NULL;
+         sd_id128_t rnd = {};
+@@ -794,10 +803,7 @@ static int setup_boot_id(const char *dest) {
+                 return r;
+         }
+ 
+-        snprintf(as_uuid, sizeof(as_uuid),
+-                 "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
+-                 SD_ID128_FORMAT_VAL(rnd));
+-        char_array_0(as_uuid);
++        id128_format_as_uuid(rnd, as_uuid);
+ 
+         r = write_string_file(from, as_uuid);
+         if (r < 0) {
+@@ -2378,7 +2384,7 @@ static int change_uid_gid(char **_home) {
+         _cleanup_fclose_ FILE *f = NULL;
+         _cleanup_close_ int fd = -1;
+         unsigned n_uids = 0;
+-        size_t sz, l;
++        size_t sz = 0, l;
+         uid_t uid;
+         gid_t gid;
+         pid_t pid;
+@@ -2667,6 +2673,7 @@ int main(int argc, char *argv[]) {
+                                 goto finish;
+                         }
+                 } else {
++#if 0
+                         const char *p;
+ 
+                         p = strappenda(arg_directory,
+@@ -2676,6 +2683,7 @@ int main(int argc, char *argv[]) {
+                                 goto finish;
+ 
+                         }
++#endif
                  }
+         } else {
+                 char template[] = "/tmp/nspawn-root-XXXXXX";
+@@ -2748,8 +2756,6 @@ int main(int argc, char *argv[]) {
+                 goto finish;
+         }
  
-                 r = conf_files_list_nulstr(&files, ".conf", NULL, conf_file_dirs);
+-        sd_notify(0, "READY=1");
+-
+         assert_se(sigemptyset(&mask) == 0);
+         sigset_add_many(&mask, SIGCHLD, SIGWINCH, SIGTERM, SIGINT, -1);
+         assert_se(sigprocmask(SIG_BLOCK, &mask, NULL) == 0);
+@@ -2966,7 +2972,9 @@ int main(int argc, char *argv[]) {
+                         }
+ 
+                         if (!sd_id128_equal(arg_uuid, SD_ID128_NULL)) {
+-                                if (asprintf((char**)(envp + n_env++), "container_uuid=" SD_ID128_FORMAT_STR, SD_ID128_FORMAT_VAL(arg_uuid)) < 0) {
++                                char as_uuid[37];
++
++                                if (asprintf((char**)(envp + n_env++), "container_uuid=%s", id128_format_as_uuid(arg_uuid, as_uuid)) < 0) {
+                                         log_oom();
+                                         goto child_fail;
+                                 }
+@@ -3086,6 +3094,8 @@ int main(int argc, char *argv[]) {
+                 if (r < 0)
+                         goto finish;
+ 
++                sd_notify(0, "READY=1");
++
+                 /* Notify the child that the parent is ready with all
+                  * its setup, and thtat the child can now hand over
+                  * control to the code to run inside the container. */
+@@ -3136,6 +3146,10 @@ int main(int argc, char *argv[]) {
+ 
+                         if (!arg_quiet)
+                                 log_info("Container %s is being rebooted.", arg_machine);
++                        if (getenv("EXIT_ON_REBOOT") != 0) {
++                                r = 10;
++                                break;
++                        }
+                         continue;
+                 } else if (status.si_code == CLD_KILLED ||
+                            status.si_code == CLD_DUMPED) {
 diff --git a/src/nss-myhostname/netlink.c b/src/nss-myhostname/netlink.c
-index b1ef912..4f2ab5c 100644
+index d61ecdf..228a3a4 100644
 --- a/src/nss-myhostname/netlink.c
 +++ b/src/nss-myhostname/netlink.c
-@@ -113,6 +113,10 @@ static int read_reply(int fd, struct address **list, unsigned *n_list) {
+@@ -112,6 +112,10 @@ static int read_reply(int fd, struct address **list, unsigned *n_list) {
                      ifaddrmsg->ifa_scope == RT_SCOPE_NOWHERE)
                          continue;
  
@@ -507,174 +1655,1006 @@ index b1ef912..4f2ab5c 100644
                  if (ifaddrmsg->ifa_flags & IFA_F_DEPRECATED)
                          continue;
  
-diff --git a/src/shared/efivars.c b/src/shared/efivars.c
-index 8d004ba..99340c9 100644
---- a/src/shared/efivars.c
-+++ b/src/shared/efivars.c
-@@ -383,7 +383,8 @@ int efi_get_boot_options(uint16_t **options) {
-                 list[count ++] = id;
+diff --git a/src/python-systemd/_reader.c b/src/python-systemd/_reader.c
+index 059b904..9a19a10 100644
+--- a/src/python-systemd/_reader.c
++++ b/src/python-systemd/_reader.c
+@@ -902,7 +902,6 @@ static PyObject* get_catalog(PyObject *self, PyObject *args) {
+         sd_id128_t id;
+         _cleanup_free_ char *msg = NULL;
+ 
+-        assert(!self);
+         assert(args);
+ 
+         if (!PyArg_ParseTuple(args, "z:get_catalog", &id_))
+diff --git a/src/python-systemd/journal.py b/src/python-systemd/journal.py
+index 9c7e004..dd1f229 100644
+--- a/src/python-systemd/journal.py
++++ b/src/python-systemd/journal.py
+@@ -293,7 +293,7 @@ class Reader(_Reader):
+             monotonic = monotonic.totalseconds()
+         monotonic = int(monotonic * 1000000)
+         if isinstance(bootid, _uuid.UUID):
+-            bootid = bootid.get_hex()
++            bootid = bootid.hex
+         return super(Reader, self).seek_monotonic(monotonic, bootid)
+ 
+     def log_level(self, level):
+@@ -314,7 +314,7 @@ class Reader(_Reader):
+         Equivalent to add_match(MESSAGE_ID=`messageid`).
+         """
+         if isinstance(messageid, _uuid.UUID):
+-            messageid = messageid.get_hex()
++            messageid = messageid.hex
+         self.add_match(MESSAGE_ID=messageid)
+ 
+     def this_boot(self, bootid=None):
+@@ -346,7 +346,7 @@ class Reader(_Reader):
+ 
+ def get_catalog(mid):
+     if isinstance(mid, _uuid.UUID):
+-        mid = mid.get_hex()
++        mid = mid.hex
+     return _get_catalog(mid)
+ 
+ def _make_line(field, value):
+diff --git a/src/readahead/readahead-common.c b/src/readahead/readahead-common.c
+index 5ffa88b..49679fc 100644
+--- a/src/readahead/readahead-common.c
++++ b/src/readahead/readahead-common.c
+@@ -75,7 +75,7 @@ int fs_on_ssd(const char *p) {
+         if (major(st.st_dev) == 0) {
+                 _cleanup_fclose_ FILE *f = NULL;
+                 int mount_id;
+-                struct file_handle *h;
++                union file_handle_union h = { .handle.handle_bytes = MAX_HANDLE_SZ, };
+ 
+                 /* Might be btrfs, which exposes "ssd" as mount flag if it is on ssd.
+                  *
+@@ -83,9 +83,7 @@ int fs_on_ssd(const char *p) {
+                  * and then lookup the mount ID in mountinfo to find
+                  * the mount options. */
+ 
+-                h = alloca(MAX_HANDLE_SZ);
+-                h->handle_bytes = MAX_HANDLE_SZ;
+-                r = name_to_handle_at(AT_FDCWD, p, h, &mount_id, AT_SYMLINK_FOLLOW);
++                r = name_to_handle_at(AT_FDCWD, p, &h.handle, &mount_id, AT_SYMLINK_FOLLOW);
+                 if (r < 0)
+                         return false;
+ 
+diff --git a/src/shared/conf-parser.c b/src/shared/conf-parser.c
+index d27b1b7..905a2e1 100644
+--- a/src/shared/conf-parser.c
++++ b/src/shared/conf-parser.c
+@@ -336,8 +336,8 @@ int config_parse(const char *unit,
+         if (!f) {
+                 f = ours = fopen(filename, "re");
+                 if (!f) {
+-                        log_error("Failed to open configuration file '%s': %m", filename);
+-                        return -errno;
++                        log_full(errno == ENOENT ? LOG_DEBUG : LOG_ERR, "Failed to open configuration file '%s': %m", filename);
++                        return errno == ENOENT ? 0 : -errno;
+                 }
          }
  
--        qsort(list, count, sizeof(uint16_t), cmp_uint16);
-+        if (list)
-+                qsort(list, count, sizeof(uint16_t), cmp_uint16);
+diff --git a/src/shared/generator.c b/src/shared/generator.c
+index 6110303..e679cb1 100644
+--- a/src/shared/generator.c
++++ b/src/shared/generator.c
+@@ -48,7 +48,7 @@ int generator_write_fsck_deps(
+                 const char *checker;
+                 int r;
+ 
+-                checker = strappenda("/sbin/fsck.", fstype);
++                checker = strappenda("/run/current-system/sw/sbin/fsck.", fstype);
+                 r = access(checker, X_OK);
+                 if (r < 0) {
+                         log_warning("Checking was requested for %s, but %s cannot be used: %m", what, checker);
+diff --git a/src/shared/install.c b/src/shared/install.c
+index 7409046..4517c9c 100644
+--- a/src/shared/install.c
++++ b/src/shared/install.c
+@@ -560,7 +560,7 @@ int unit_file_mask(
+                 unsigned *n_changes) {
+ 
+         char **i;
+-        _cleanup_free_ char *prefix;
++        _cleanup_free_ char *prefix = NULL;
+         int r;
+ 
+         assert(scope >= 0);
+diff --git a/src/shared/log.c b/src/shared/log.c
+index a4b3b68..890a9fa 100644
+--- a/src/shared/log.c
++++ b/src/shared/log.c
+@@ -878,6 +878,9 @@ void log_parse_environment(void) {
+                         if (l == 5 && startswith(w, "debug")) {
+                                 log_set_max_level(LOG_DEBUG);
+                                 break;
++                        } else if (l == 5 && startswith(w, "quiet")) {
++                                log_set_max_level(LOG_WARNING);
++                                break;
+                         }
+                 }
+         }
+diff --git a/src/shared/logs-show.c b/src/shared/logs-show.c
+index 9d14933..b0b66f6 100644
+--- a/src/shared/logs-show.c
++++ b/src/shared/logs-show.c
+@@ -547,7 +547,9 @@ static int output_export(
+                     startswith(data, "_BOOT_ID="))
+                         continue;
  
-         *options = list;
-         return count;
-diff --git a/src/shared/env-util.c b/src/shared/env-util.c
-index 6a52fb9..598222c 100644
---- a/src/shared/env-util.c
-+++ b/src/shared/env-util.c
-@@ -406,7 +406,9 @@ char **strv_env_clean_log(char **e, const char *message) {
-                 e[k++] = *p;
+-                if (!utf8_is_printable(data, length)) {
++                if (utf8_is_printable_newline(data, length, false))
++                        fwrite(data, length, 1, f);
++                else {
+                         const char *c;
+                         uint64_t le64;
+ 
+@@ -562,8 +564,7 @@ static int output_export(
+                         le64 = htole64(length - (c - (const char*) data) - 1);
+                         fwrite(&le64, sizeof(le64), 1, f);
+                         fwrite(c + 1, length - (c - (const char*) data) - 1, 1, f);
+-                } else
+-                        fwrite(data, length, 1, f);
++                }
+ 
+                 fputc('\n', f);
          }
+diff --git a/src/shared/unit-name.c b/src/shared/unit-name.c
+index 6c167b4..d0e71f2 100644
+--- a/src/shared/unit-name.c
++++ b/src/shared/unit-name.c
+@@ -332,7 +332,7 @@ char *unit_name_path_unescape(const char *f) {
+ }
+ 
+ bool unit_name_is_template(const char *n) {
+-        const char *p;
++        const char *p, *e;
  
--        e[k] = NULL;
-+        if (e)
-+                e[k] = NULL;
+         assert(n);
+ 
+@@ -340,11 +340,15 @@ bool unit_name_is_template(const char *n) {
+         if (!p)
+                 return false;
+ 
+-        return p[1] == '.';
++        e = strrchr(p+1, '.');
++        if (!e)
++                return false;
 +
-         return e;
++        return e == p + 1;
  }
  
-diff --git a/src/shared/log.c b/src/shared/log.c
-index 27317f7..8f4995a 100644
---- a/src/shared/log.c
-+++ b/src/shared/log.c
-@@ -115,16 +115,20 @@ void log_close_syslog(void) {
+ bool unit_name_is_instance(const char *n) {
+-        const char *p;
++        const char *p, *e;
+ 
+         assert(n);
+ 
+@@ -352,7 +356,11 @@ bool unit_name_is_instance(const char *n) {
+         if (!p)
+                 return false;
+ 
+-        return p[1] != '.';
++        e = strrchr(p+1, '.');
++        if (!e)
++                return false;
++
++        return e > p + 1;
+ }
  
- static int create_log_socket(int type) {
-         int fd;
-+        struct timeval tv;
+ char *unit_name_replace_instance(const char *f, const char *i) {
+diff --git a/src/shared/utf8.c b/src/shared/utf8.c
+index 0b524d8..c559c13 100644
+--- a/src/shared/utf8.c
++++ b/src/shared/utf8.c
+@@ -136,7 +136,7 @@ int utf8_encoded_to_unichar(const char *str) {
+         return unichar;
+ }
+ 
+-bool utf8_is_printable(const char* str, size_t length) {
++bool utf8_is_printable_newline(const char* str, size_t length, bool newline) {
+         const uint8_t *p;
  
--        /* All output to the syslog/journal fds we do asynchronously,
--         * and if the buffers are full we just drop the messages */
+         assert(str);
+@@ -145,7 +145,8 @@ bool utf8_is_printable(const char* str, size_t length) {
+                 int encoded_len = utf8_encoded_valid_unichar((const char *)p);
+                 int val = utf8_encoded_to_unichar((const char*)p);
+ 
+-                if (encoded_len < 0 || val < 0 || is_unicode_control(val))
++                if (encoded_len < 0 || val < 0 || is_unicode_control(val) ||
++                    (!newline && val == '\n'))
+                         return false;
+ 
+                 length -= encoded_len;
+diff --git a/src/shared/utf8.h b/src/shared/utf8.h
+index c0eb73a..c087995 100644
+--- a/src/shared/utf8.h
++++ b/src/shared/utf8.h
+@@ -31,7 +31,10 @@ const char *utf8_is_valid(const char *s) _pure_;
+ char *ascii_is_valid(const char *s) _pure_;
+ char *utf8_escape_invalid(const char *s);
+ 
+-bool utf8_is_printable(const char* str, size_t length) _pure_;
++bool utf8_is_printable_newline(const char* str, size_t length, bool newline) _pure_;
++_pure_ static inline bool utf8_is_printable(const char* str, size_t length) {
++        return utf8_is_printable_newline(str, length, true);
++}
+ 
+ char *utf16_to_utf8(const void *s, size_t length);
+ 
+diff --git a/src/shared/util.c b/src/shared/util.c
+index ffe6624..2a2b2b2 100644
+--- a/src/shared/util.c
++++ b/src/shared/util.c
+@@ -166,19 +166,19 @@ int close_nointr(int fd) {
+ 
+         assert(fd >= 0);
+         r = close(fd);
 -
--        fd = socket(AF_UNIX, type|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
-+        fd = socket(AF_UNIX, type|SOCK_CLOEXEC, 0);
-         if (fd < 0)
+-        /* Just ignore EINTR; a retry loop is the wrong
+-         * thing to do on Linux.
+-         *
+-         * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
+-         * https://bugzilla.gnome.org/show_bug.cgi?id=682819
+-         * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
+-         * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
+-         */
+-        if (_unlikely_(r < 0 && errno == EINTR))
+-                return 0;
+-        else if (r >= 0)
++        if (r >= 0)
+                 return r;
++        else if (errno == EINTR)
++                /*
++                 * Just ignore EINTR; a retry loop is the wrong
++                 * thing to do on Linux.
++                 *
++                 * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
++                 * https://bugzilla.gnome.org/show_bug.cgi?id=682819
++                 * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
++                 * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
++                 */
++                return 0;
+         else
                  return -errno;
+ }
+@@ -195,7 +195,13 @@ int safe_close(int fd) {
  
-         fd_inc_sndbuf(fd, SNDBUF_SIZE);
- 
-+        /* We need a blocking fd here since we'd otherwise lose
-+        messages way too early. However, let's not hang forever in the
-+        unlikely case of a deadlock. */
-+        timeval_store(&tv, 1*USEC_PER_MINUTE);
-+        setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
+         if (fd >= 0) {
+                 PROTECT_ERRNO;
+-                assert_se(close_nointr(fd) == 0);
 +
-         return fd;
++                /* The kernel might return pretty much any error code
++                 * via close(), but the fd will be closed anyway. The
++                 * only condition we want to check for here is whether
++                 * the fd was invalid at all... */
++
++                assert_se(close_nointr(fd) != -EBADF);
+         }
+ 
+         return -1;
+@@ -1365,7 +1371,7 @@ bool ignore_file(const char *filename) {
+         assert(filename);
+ 
+         if (endswith(filename, "~"))
+-                return false;
++                return true;
+ 
+         return ignore_file_allow_backup(filename);
  }
+@@ -1495,6 +1501,7 @@ bool fstype_is_network(const char *fstype) {
+         static const char table[] =
+                 "cifs\0"
+                 "smbfs\0"
++                "sshfs\0"
+                 "ncpfs\0"
+                 "ncp\0"
+                 "nfs\0"
+@@ -1581,8 +1588,9 @@ int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
+                 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
+                         return -ETIMEDOUT;
+ 
++        errno = 0;
+         if (!fgets(line, sizeof(line), f))
+-                return -EIO;
++                return errno ? -errno : -EIO;
+ 
+         truncate_nl(line);
+ 
+@@ -5327,6 +5335,9 @@ bool string_is_safe(const char *p) {
+                 if (*t > 0 && *t < ' ')
+                         return false;
  
-diff --git a/src/shared/polkit.c b/src/shared/polkit.c
-index cea7074..1c5e9e3 100644
---- a/src/shared/polkit.c
-+++ b/src/shared/polkit.c
-@@ -38,12 +38,8 @@ int verify_polkit(
- 
- #ifdef ENABLE_POLKIT
-         DBusMessage *m = NULL, *reply = NULL;
--        const char *unix_process = "unix-process", *pid = "pid", *starttime = "start-time", *cancel_id = "";
-+        const char *system_bus_name = "system-bus-name", *name = "name", *cancel_id = "";
-         uint32_t flags = interactive ? 1 : 0;
--        pid_t pid_raw;
--        uint32_t pid_u32;
--        unsigned long long starttime_raw;
--        uint64_t starttime_u64;
-         DBusMessageIter iter_msg, iter_struct, iter_array, iter_dict, iter_variant;
-         int r;
-         dbus_bool_t authorized = FALSE, challenge = FALSE;
-@@ -68,14 +64,6 @@ int verify_polkit(
++                if (*t == 127)
++                        return false;
++
+                 if (strchr("\\\"\'", *t))
+                         return false;
+         }
+@@ -5343,10 +5354,14 @@ bool string_has_cc(const char *p) {
  
- #ifdef ENABLE_POLKIT
+         assert(p);
  
--        pid_raw = bus_get_unix_process_id(c, sender, error);
--        if (pid_raw == 0)
--                return -EINVAL;
--
--        r = get_starttime_of_pid(pid_raw, &starttime_raw);
--        if (r < 0)
--                return r;
--
-         m = dbus_message_new_method_call(
-                         "org.freedesktop.PolicyKit1",
-                         "/org/freedesktop/PolicyKit1/Authority",
-@@ -86,22 +74,13 @@ int verify_polkit(
+-        for (t = p; *t; t++)
++        for (t = p; *t; t++) {
+                 if (*t > 0 && *t < ' ' && *t != '\t')
+                         return true;
  
-         dbus_message_iter_init_append(m, &iter_msg);
++                if (*t == 127)
++                        return true;
++        }
++
+         return false;
+ }
  
--        pid_u32 = (uint32_t) pid_raw;
--        starttime_u64 = (uint64_t) starttime_raw;
--
-         if (!dbus_message_iter_open_container(&iter_msg, DBUS_TYPE_STRUCT, NULL, &iter_struct) ||
--            !dbus_message_iter_append_basic(&iter_struct, DBUS_TYPE_STRING, &unix_process) ||
-+            !dbus_message_iter_append_basic(&iter_struct, DBUS_TYPE_STRING, &system_bus_name) ||
-             !dbus_message_iter_open_container(&iter_struct, DBUS_TYPE_ARRAY, "{sv}", &iter_array) ||
-             !dbus_message_iter_open_container(&iter_array, DBUS_TYPE_DICT_ENTRY, NULL, &iter_dict) ||
--            !dbus_message_iter_append_basic(&iter_dict, DBUS_TYPE_STRING, &pid) ||
--            !dbus_message_iter_open_container(&iter_dict, DBUS_TYPE_VARIANT, "u", &iter_variant) ||
--            !dbus_message_iter_append_basic(&iter_variant, DBUS_TYPE_UINT32, &pid_u32) ||
--            !dbus_message_iter_close_container(&iter_dict, &iter_variant) ||
--            !dbus_message_iter_close_container(&iter_array, &iter_dict) ||
--            !dbus_message_iter_open_container(&iter_array, DBUS_TYPE_DICT_ENTRY, NULL, &iter_dict) ||
--            !dbus_message_iter_append_basic(&iter_dict, DBUS_TYPE_STRING, &starttime) ||
--            !dbus_message_iter_open_container(&iter_dict, DBUS_TYPE_VARIANT, "t", &iter_variant) ||
--            !dbus_message_iter_append_basic(&iter_variant, DBUS_TYPE_UINT64, &starttime_u64) ||
-+            !dbus_message_iter_append_basic(&iter_dict, DBUS_TYPE_STRING, &name) ||
-+            !dbus_message_iter_open_container(&iter_dict, DBUS_TYPE_VARIANT, "s", &iter_variant) ||
-+            !dbus_message_iter_append_basic(&iter_variant, DBUS_TYPE_STRING, &sender) ||
-             !dbus_message_iter_close_container(&iter_dict, &iter_variant) ||
-             !dbus_message_iter_close_container(&iter_array, &iter_dict) ||
-             !dbus_message_iter_close_container(&iter_struct, &iter_array) ||
+@@ -6391,3 +6406,19 @@ void hexdump(FILE *f, const void *p, size_t s) {
+                 s -= 16;
+         }
+ }
++
++int update_reboot_param_file(const char *param)
++{
++        int r = 0;
++
++        if (param) {
++
++                r = write_string_file(REBOOT_PARAM_FILE, param);
++                if (r < 0)
++                        log_error("Failed to write reboot param to "
++                                  REBOOT_PARAM_FILE": %s", strerror(-r));
++        } else
++                unlink(REBOOT_PARAM_FILE);
++
++        return r;
++}
+diff --git a/src/shared/util.h b/src/shared/util.h
+index 90464c9..122ac91 100644
+--- a/src/shared/util.h
++++ b/src/shared/util.h
+@@ -22,6 +22,7 @@
+ ***/
+ 
+ #include <alloca.h>
++#include <fcntl.h>
+ #include <inttypes.h>
+ #include <time.h>
+ #include <sys/time.h>
+@@ -922,3 +923,10 @@ uint64_t physical_memory(void);
+ char* mount_test_option(const char *haystack, const char *needle);
+ 
+ void hexdump(FILE *f, const void *p, size_t s);
++
++union file_handle_union {
++        struct file_handle handle;
++        char padding[sizeof(struct file_handle) + MAX_HANDLE_SZ];
++};
++
++int update_reboot_param_file(const char *param);
+diff --git a/src/shared/virt.c b/src/shared/virt.c
+index ec2ddcf..f03e790 100644
+--- a/src/shared/virt.c
++++ b/src/shared/virt.c
+@@ -149,7 +149,7 @@ static int detect_vm_dmi(const char **_id) {
+ 
+ /* Returns a short identifier for the various VM implementations */
+ int detect_vm(const char **id) {
+-        _cleanup_free_ char *hvtype = NULL, *cpuinfo_contents = NULL;
++        _cleanup_free_ char *domcap = NULL, *cpuinfo_contents = NULL;
+         static thread_local int cached_found = -1;
+         static thread_local const char *cached_id = NULL;
+         const char *_id = NULL;
+@@ -163,17 +163,37 @@ int detect_vm(const char **id) {
+                 return cached_found;
+         }
+ 
+-        /* Try high-level hypervisor sysfs file first:
++        /* Try xen capabilities file first, if not found try high-level hypervisor sysfs file:
+          *
+-         * https://bugs.freedesktop.org/show_bug.cgi?id=61491 */
+-        r = read_one_line_file("/sys/hypervisor/type", &hvtype);
++         * https://bugs.freedesktop.org/show_bug.cgi?id=77271 */
++        r = read_one_line_file("/proc/xen/capabilities", &domcap);
+         if (r >= 0) {
+-                if (streq(hvtype, "xen")) {
++                char *cap, *i = domcap;
++
++                while ((cap = strsep(&i, ",")))
++                        if (streq(cap, "control_d"))
++                                break;
++
++                if (!i)  {
+                         _id = "xen";
+                         r = 1;
+-                        goto finish;
+                 }
+-        } else if (r != -ENOENT)
++
++                goto finish;
++
++        } else if (r == -ENOENT) {
++                _cleanup_free_ char *hvtype = NULL;
++
++                r = read_one_line_file("/sys/hypervisor/type", &hvtype);
++                if (r >= 0) {
++                        if (streq(hvtype, "xen")) {
++                                _id = "xen";
++                                r = 1;
++                                goto finish;
++                        }
++                } else if (r != -ENOENT)
++                        return r;
++        } else
+                 return r;
+ 
+         /* this will set _id to "other" and return 0 for unknown hypervisors */
 diff --git a/src/systemctl/systemctl.c b/src/systemctl/systemctl.c
-index 3cca861..f6052dd 100644
+index 0887bc3..d02ee2b 100644
 --- a/src/systemctl/systemctl.c
 +++ b/src/systemctl/systemctl.c
-@@ -1482,7 +1482,7 @@ static DBusHandlerResult wait_filter(DBusConnection *connection, DBusMessage *me
- 
-         } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Manager", "JobRemoved")) {
-                 uint32_t id;
--                const char *path, *result, *unit;
-+                const char *path, *result, *unit, *r;
- 
-                 if (dbus_message_get_args(message, &error,
-                                           DBUS_TYPE_UINT32, &id,
-@@ -1491,7 +1491,11 @@ static DBusHandlerResult wait_filter(DBusConnection *connection, DBusMessage *me
-                                           DBUS_TYPE_STRING, &result,
-                                           DBUS_TYPE_INVALID)) {
- 
--                        free(set_remove(d->set, (char*) path));
-+                        r = set_remove(d->set, (char*) path);
-+                        if (!r)
-+                                return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
-+
-+                        free(r);
- 
-                         if (!isempty(result))
-                                 d->result = strdup(result);
-@@ -1511,7 +1515,11 @@ static DBusHandlerResult wait_filter(DBusConnection *connection, DBusMessage *me
-                         /* Compatibility with older systemd versions <
-                          * 183 during upgrades. This should be dropped
-                          * one day. */
--                        free(set_remove(d->set, (char*) path));
-+                        r = set_remove(d->set, (char*) path);
-+                        if (!r)
-+                                return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
-+
-+                        free(r);
- 
-                         if (*result)
-                                 d->result = strdup(result);
-@@ -1867,7 +1875,7 @@ static int start_unit_one(
-                         return log_oom();
+@@ -461,7 +461,7 @@ static int output_units_list(const UnitInfo *unit_infos, unsigned c) {
+                 }
+ 
+                 if (circle_len > 0)
+-                        printf("%s%s%s", on_circle, circle ? draw_special_char(DRAW_BLACK_CIRCLE) : "  ", off_circle);
++                        printf("%s%s%s ", on_circle, circle ? draw_special_char(DRAW_BLACK_CIRCLE) : " ", off_circle);
+ 
+                 printf("%s%-*s%s %s%-*s%s %s%-*s %-*s%s %-*s",
+                        on_active, id_len, id, off_active,
+@@ -2561,7 +2561,7 @@ static int start_unit_one(
  
+                 log_debug("Adding %s to the set", p);
                  r = set_consume(s, p);
+-                if (r < 0)
++                if (r < 0 && r != -EEXIST)
+                         return log_oom();
+         }
+ 
+@@ -4240,7 +4240,7 @@ static int show_all(
+         _cleanup_free_ UnitInfo *unit_infos = NULL;
+         const UnitInfo *u;
+         unsigned c;
+-        int r;
++        int r, ret = 0;
+ 
+         r = get_unit_list(bus, NULL, NULL, &unit_infos, 0, &reply);
+         if (r < 0)
+@@ -4262,9 +4262,11 @@ static int show_all(
+                 r = show_one(verb, bus, p, show_properties, new_line, ellipsized);
+                 if (r < 0)
+                         return r;
++                else if (r > 0 && ret == 0)
++                        ret = r;
+         }
+ 
+-        return 0;
++        return ret;
+ }
+ 
+ static int show_system_status(sd_bus *bus) {
+@@ -4386,7 +4388,12 @@ static int show(sd_bus *bus, char **args) {
+                                 }
+                         }
+ 
+-                        show_one(args[0], bus, unit, show_properties, &new_line, &ellipsized);
++                        r = show_one(args[0], bus, unit, show_properties,
++                                     &new_line, &ellipsized);
++                        if (r < 0)
++                                return r;
++                        else if (r > 0 && ret == 0)
++                                ret = r;
+                 }
+ 
+                 if (!strv_isempty(patterns)) {
+@@ -4403,7 +4410,12 @@ static int show(sd_bus *bus, char **args) {
+                                 if (!unit)
+                                         return log_oom();
+ 
+-                                show_one(args[0], bus, unit, show_properties, &new_line, &ellipsized);
++                                r = show_one(args[0], bus, unit, show_properties,
++                                             &new_line, &ellipsized);
++                                if (r < 0)
++                                        return r;
++                                else if (r > 0 && ret == 0)
++                                        ret = r;
+                         }
+                 }
+         }
+@@ -5403,15 +5415,15 @@ static int systemctl_help(void) {
+                "                                  otherwise restart if active\n"
+                "  isolate NAME                    Start one unit and stop all others\n"
+                "  kill NAME...                    Send signal to processes of a unit\n"
+-               "  is-active NAME...               Check whether units are active\n"
+-               "  is-failed NAME...               Check whether units are failed\n"
+-               "  status [NAME...|PID...]         Show runtime status of one or more units\n"
+-               "  show [NAME...|JOB...]           Show properties of one or more\n"
++               "  is-active PATTERN...            Check whether units are active\n"
++               "  is-failed PATTERN...            Check whether units are failed\n"
++               "  status [PATTERN...|PID...]      Show runtime status of one or more units\n"
++               "  show [PATTERN...|JOB...]        Show properties of one or more\n"
+                "                                  units/jobs or the manager\n"
+-               "  cat NAME...                     Show files and drop-ins of one or more units\n"
++               "  cat PATTERN...                  Show files and drop-ins of one or more units\n"
+                "  set-property NAME ASSIGNMENT... Sets one or more properties of a unit\n"
+-               "  help NAME...|PID...             Show manual for one or more units\n"
+-               "  reset-failed [NAME...]          Reset failed state for all, one, or more\n"
++               "  help PATTERN...|PID...          Show manual for one or more units\n"
++               "  reset-failed [PATTERN...]       Reset failed state for all, one, or more\n"
+                "                                  units\n"
+                "  list-dependencies [NAME]        Recursively show units which are required\n"
+                "                                  or wanted by this unit or by which this\n"
+@@ -5973,13 +5985,10 @@ static int halt_parse_argv(int argc, char *argv[]) {
+                 }
+         }
+ 
+-        if (arg_action == ACTION_REBOOT && argc == optind + 1) {
+-                r = write_string_file(REBOOT_PARAM_FILE, argv[optind]);
 -                if (r < 0) {
-+                if (r < 0 && r != -EEXIST) {
-                         log_error("Failed to add path to set.");
+-                        log_error("Failed to write reboot param to "
+-                                  REBOOT_PARAM_FILE": %s", strerror(-r));
++        if (arg_action == ACTION_REBOOT && (argc == optind || argc == optind + 1)) {
++                r = update_reboot_param_file(argc == optind + 1 ? argv[optind] : NULL);
++                if (r < 0)
                          return r;
+-                }
+         } else if (optind < argc) {
+                 log_error("Too many arguments.");
+                 return -EINVAL;
+diff --git a/src/test/test-udev.c b/src/test/test-udev.c
+index b064744..b057cc8 100644
+--- a/src/test/test-udev.c
++++ b/src/test/test-udev.c
+@@ -155,9 +155,8 @@ int main(int argc, char *argv[]) {
                  }
+         }
+ 
+-        err = udev_event_execute_rules(event, rules, &sigmask_orig);
+-        if (err == 0)
+-                udev_event_execute_run(event, NULL);
++        udev_event_execute_rules(event, rules, &sigmask_orig);
++        udev_event_execute_run(event, NULL);
+ out:
+         if (event != NULL && event->fd_signal >= 0)
+                 close(event->fd_signal);
+diff --git a/src/tmpfiles/tmpfiles.c b/src/tmpfiles/tmpfiles.c
+index 33e7cbc..04b472d 100644
+--- a/src/tmpfiles/tmpfiles.c
++++ b/src/tmpfiles/tmpfiles.c
+@@ -217,19 +217,16 @@ static bool unix_socket_alive(const char *fn) {
+ }
+ 
+ static int dir_is_mount_point(DIR *d, const char *subdir) {
+-        struct file_handle *h;
++        union file_handle_union h = { .handle.handle_bytes = MAX_HANDLE_SZ };
+         int mount_id_parent, mount_id;
+         int r_p, r;
+ 
+-        h = alloca(MAX_HANDLE_SZ);
+-
+-        h->handle_bytes = MAX_HANDLE_SZ;
+-        r_p = name_to_handle_at(dirfd(d), ".", h, &mount_id_parent, 0);
++        r_p = name_to_handle_at(dirfd(d), ".", &h.handle, &mount_id_parent, 0);
+         if (r_p < 0)
+                 r_p = -errno;
+ 
+-        h->handle_bytes = MAX_HANDLE_SZ;
+-        r = name_to_handle_at(dirfd(d), subdir, h, &mount_id, 0);
++        h.handle.handle_bytes = MAX_HANDLE_SZ;
++        r = name_to_handle_at(dirfd(d), subdir, &h.handle, &mount_id, 0);
+         if (r < 0)
+                 r = -errno;
+ 
+diff --git a/src/tty-ask-password-agent/tty-ask-password-agent.c b/src/tty-ask-password-agent/tty-ask-password-agent.c
+index 1d067af..3203474 100644
+--- a/src/tty-ask-password-agent/tty-ask-password-agent.c
++++ b/src/tty-ask-password-agent/tty-ask-password-agent.c
+@@ -432,7 +432,7 @@ static int wall_tty_block(void) {
+ 
+         r = get_ctty_devnr(0, &devnr);
+         if (r < 0)
+-                return -r;
++                return r;
+ 
+         if (asprintf(&p, "/run/systemd/ask-password-block/%u:%u", major(devnr), minor(devnr)) < 0)
+                 return -ENOMEM;
+diff --git a/src/udev/accelerometer/accelerometer.c b/src/udev/accelerometer/accelerometer.c
+index 925d38d..32adf27 100644
+--- a/src/udev/accelerometer/accelerometer.c
++++ b/src/udev/accelerometer/accelerometer.c
+@@ -180,7 +180,7 @@ get_prev_orientation(struct udev_device *dev)
+         return string_to_orientation(value);
+ }
+ 
+-#define SET_AXIS(axis, code_) if (ev[i].code == code_) { if (got_##axis == 0) { axis = ev[i].value; got_##axis = true; } }
++#define READ_AXIS(axis, var) { memzero(&abs_info, sizeof(abs_info)); r = ioctl(fd, EVIOCGABS(axis), &abs_info); if (r < 0) return; var = abs_info.value; }
+ 
+ /* accelerometers */
+ static void test_orientation(struct udev *udev,
+@@ -189,10 +189,9 @@ static void test_orientation(struct udev *udev,
+ {
+         OrientationUp old, new;
+         _cleanup_close_ int fd = -1;
+-        struct input_event ev[64];
+-        bool got_syn = false;
+-        bool got_x = false, got_y = false, got_z = false;
++        struct input_absinfo abs_info;
+         int x = 0, y = 0, z = 0;
++        int r;
+         char text[64];
+ 
+         old = get_prev_orientation(dev);
+@@ -201,30 +200,10 @@ static void test_orientation(struct udev *udev,
+         if (fd < 0)
+                 return;
+ 
+-        while (1) {
+-                int i, r;
+-
+-                r = read(fd, ev, sizeof(struct input_event) * 64);
+-
+-                if (r < (int) sizeof(struct input_event))
+-                        return;
+-
+-                for (i = 0; i < r / (int) sizeof(struct input_event); i++) {
+-                        if (got_syn) {
+-                                if (ev[i].type == EV_ABS) {
+-                                        SET_AXIS(x, ABS_X);
+-                                        SET_AXIS(y, ABS_Y);
+-                                        SET_AXIS(z, ABS_Z);
+-                                }
+-                        }
+-                        if (ev[i].type == EV_SYN && ev[i].code == SYN_REPORT)
+-                                got_syn = true;
+-                        if (got_x && got_y && got_z)
+-                                goto read_dev;
+-                }
+-        }
++        READ_AXIS(ABS_X, x);
++        READ_AXIS(ABS_Y, y);
++        READ_AXIS(ABS_Z, z);
+ 
+-read_dev:
+         new = orientation_calc(old, x, y, z);
+         snprintf(text, sizeof(text),
+                  "ID_INPUT_ACCELEROMETER_ORIENTATION=%s", orientation_to_string(new));
+diff --git a/src/udev/net/link-config.c b/src/udev/net/link-config.c
+index 5bb6b02..b31ad80 100644
+--- a/src/udev/net/link-config.c
++++ b/src/udev/net/link-config.c
+@@ -184,7 +184,7 @@ failure:
+ }
+ 
+ static bool enable_name_policy(void) {
+-        _cleanup_free_ char *line;
++        _cleanup_free_ char *line = NULL;
+         char *w, *state;
+         int r;
+         size_t l;
+@@ -391,7 +391,9 @@ int link_config_apply(link_config_ctx *ctx, link_config *config, struct udev_dev
+                 case MACPOLICY_PERSISTENT:
+                         if (!mac_is_permanent(device)) {
+                                 r = get_mac(device, false, &generated_mac);
+-                                if (r < 0)
++                                if (r == -ENOENT)
++                                        break;
++                                else if (r < 0)
+                                         return r;
+                                 mac = &generated_mac;
+                         }
+@@ -399,7 +401,9 @@ int link_config_apply(link_config_ctx *ctx, link_config *config, struct udev_dev
+                 case MACPOLICY_RANDOM:
+                         if (!mac_is_random(device)) {
+                                 r = get_mac(device, true, &generated_mac);
+-                                if (r < 0)
++                                if (r == -ENOENT)
++                                        break;
++                                else if (r < 0)
+                                         return r;
+                                 mac = &generated_mac;
+                         }
+diff --git a/src/udev/udev-event.c b/src/udev/udev-event.c
+index 5998be2..5213a4a 100644
+--- a/src/udev/udev-event.c
++++ b/src/udev/udev-event.c
+@@ -771,18 +771,17 @@ static int rename_netif(struct udev_event *event)
+                 log_error("error changing net interface name %s to %s: %s",
+                           oldname, name, strerror(-r));
+         else
+-                print_kmsg("renamed network interface %s to %s", oldname, name);
++                print_kmsg("renamed network interface %s to %s\n", oldname, name);
+ 
+         return r;
+ }
+ 
+-int udev_event_execute_rules(struct udev_event *event, struct udev_rules *rules, const sigset_t *sigmask)
++void udev_event_execute_rules(struct udev_event *event, struct udev_rules *rules, const sigset_t *sigmask)
+ {
+         struct udev_device *dev = event->dev;
+-        int err = 0;
+ 
+         if (udev_device_get_subsystem(dev) == NULL)
+-                return -1;
++                return;
+ 
+         if (streq(udev_device_get_action(dev), "remove")) {
+                 udev_device_read_db(dev, NULL);
+@@ -816,9 +815,10 @@ int udev_event_execute_rules(struct udev_event *event, struct udev_rules *rules,
+                     event->name != NULL && !streq(event->name, udev_device_get_sysname(dev))) {
+                         char syspath[UTIL_PATH_SIZE];
+                         char *pos;
++                        int r;
+ 
+-                        err = rename_netif(event);
+-                        if (err == 0) {
++                        r = rename_netif(event);
++                        if (r >= 0) {
+                                 log_debug("renamed netif to '%s'", event->name);
+ 
+                                 /* remember old name */
+@@ -881,7 +881,6 @@ int udev_event_execute_rules(struct udev_event *event, struct udev_rules *rules,
+                 udev_device_unref(event->dev_db);
+                 event->dev_db = NULL;
+         }
+-        return err;
+ }
+ 
+ void udev_event_execute_run(struct udev_event *event, const sigset_t *sigmask)
+diff --git a/src/udev/udev-rules.c b/src/udev/udev-rules.c
+index 2630264..17f47f2 100644
+--- a/src/udev/udev-rules.c
++++ b/src/udev/udev-rules.c
+@@ -2555,10 +2555,15 @@ int udev_rules_apply_static_dev_perms(struct udev_rules *rules)
+                         struct stat stats;
+ 
+                         /* we assure, that the permissions tokens are sorted before the static token */
++
+                         if (mode == 0 && uid == 0 && gid == 0 && tags == NULL)
+                                 goto next;
+ 
+                         strscpyl(device_node, sizeof(device_node), "/dev/", rules_str(rules, cur->key.value_off), NULL);
++                        if (stat(device_node, &stats) != 0)
++                                break;
++                        if (!S_ISBLK(stats.st_mode) && !S_ISCHR(stats.st_mode))
++                                break;
+ 
+                         /* export the tags to a directory as symlinks, allowing otherwise dead nodes to be tagged */
+                         if (tags) {
+@@ -2588,11 +2593,6 @@ int udev_rules_apply_static_dev_perms(struct udev_rules *rules)
+                         if (mode == 0 && uid == 0 && gid == 0)
+                                 break;
+ 
+-                        if (stat(device_node, &stats) != 0)
+-                                break;
+-                        if (!S_ISBLK(stats.st_mode) && !S_ISCHR(stats.st_mode))
+-                                break;
+-
+                         if (mode == 0) {
+                                 if (gid > 0)
+                                         mode = 0660;
+diff --git a/src/udev/udev.h b/src/udev/udev.h
+index 936adfb..62538bc 100644
+--- a/src/udev/udev.h
++++ b/src/udev/udev.h
+@@ -84,7 +84,7 @@ int udev_event_apply_subsys_kernel(struct udev_event *event, const char *string,
+ int udev_event_spawn(struct udev_event *event,
+                      const char *cmd, char **envp, const sigset_t *sigmask,
+                      char *result, size_t ressize);
+-int udev_event_execute_rules(struct udev_event *event, struct udev_rules *rules, const sigset_t *sigset);
++void udev_event_execute_rules(struct udev_event *event, struct udev_rules *rules, const sigset_t *sigset);
+ void udev_event_execute_run(struct udev_event *event, const sigset_t *sigset);
+ int udev_build_argv(struct udev *udev, char *cmd, int *argc, char *argv[]);
+ 
+diff --git a/src/udev/udevadm-test.c b/src/udev/udevadm-test.c
+index 6cd311b..6a2f548 100644
+--- a/src/udev/udevadm-test.c
++++ b/src/udev/udevadm-test.c
+@@ -43,7 +43,6 @@ static int adm_test(struct udev *udev, int argc, char *argv[])
+         _cleanup_udev_device_unref_ struct udev_device *dev = NULL;
+         _cleanup_udev_event_unref_ struct udev_event *event = NULL;
+         sigset_t mask, sigmask_orig;
+-        int err;
+         int rc = 0, c;
+ 
+         static const struct option options[] = {
+@@ -139,18 +138,16 @@ static int adm_test(struct udev *udev, int argc, char *argv[])
+                 goto out;
+         }
+ 
+-        err = udev_event_execute_rules(event, rules, &sigmask_orig);
++        udev_event_execute_rules(event, rules, &sigmask_orig);
+ 
+         udev_list_entry_foreach(entry, udev_device_get_properties_list_entry(dev))
+                 printf("%s=%s\n", udev_list_entry_get_name(entry), udev_list_entry_get_value(entry));
+ 
+-        if (err == 0) {
+-                udev_list_entry_foreach(entry, udev_list_get_entry(&event->run_list)) {
+-                        char program[UTIL_PATH_SIZE];
++        udev_list_entry_foreach(entry, udev_list_get_entry(&event->run_list)) {
++                char program[UTIL_PATH_SIZE];
+ 
+-                        udev_event_apply_format(event, udev_list_entry_get_name(entry), program, sizeof(program));
+-                        printf("run: '%s'\n", program);
+-                }
++                udev_event_apply_format(event, udev_list_entry_get_name(entry), program, sizeof(program));
++                printf("run: '%s'\n", program);
+         }
+ out:
+         if (event != NULL && event->fd_signal >= 0)
+diff --git a/src/udev/udevd.c b/src/udev/udevd.c
+index f21c227..93afca1 100644
+--- a/src/udev/udevd.c
++++ b/src/udev/udevd.c
+@@ -288,10 +288,9 @@ static void worker_new(struct event *event)
+                                 udev_event->exec_delay = exec_delay;
+ 
+                         /* apply rules, create node, symlinks */
+-                        err = udev_event_execute_rules(udev_event, rules, &sigmask_orig);
++                        udev_event_execute_rules(udev_event, rules, &sigmask_orig);
+ 
+-                        if (err == 0)
+-                                udev_event_execute_run(udev_event, &sigmask_orig);
++                        udev_event_execute_run(udev_event, &sigmask_orig);
+ 
+                         /* apply/restore inotify watch */
+                         if (err == 0 && udev_event->inotify_watch) {
+diff --git a/src/vconsole/vconsole-setup.c b/src/vconsole/vconsole-setup.c
+index 0f2b706..645b1e6 100644
+--- a/src/vconsole/vconsole-setup.c
++++ b/src/vconsole/vconsole-setup.c
+@@ -180,6 +180,10 @@ static int font_load(const char *vc, const char *font, const char *map, const ch
+  */
+ static void font_copy_to_all_vcs(int fd) {
+         struct vt_stat vcs = {};
++        unsigned char map8[E_TABSZ];
++        unsigned short map16[E_TABSZ];
++        struct unimapdesc unimapd;
++        struct unipair unipairs[USHRT_MAX];
+         int i, r;
+ 
+         /* get active, and 16 bit mask of used VT numbers */
+@@ -209,17 +213,35 @@ static void font_copy_to_all_vcs(int fd) {
+                 cfo.op = KD_FONT_OP_COPY;
+                 cfo.height = vcs.v_active-1; /* tty1 == index 0 */
+                 ioctl(vcfd, KDFONTOP, &cfo);
++
++                /* copy map of 8bit chars */
++                if (ioctl(fd, GIO_SCRNMAP, map8) >= 0)
++                    ioctl(vcfd, PIO_SCRNMAP, map8);
++
++                /* copy map of 8bit chars -> 16bit Unicode values */
++                if (ioctl(fd, GIO_UNISCRNMAP, map16) >= 0)
++                    ioctl(vcfd, PIO_UNISCRNMAP, map16);
++
++                /* copy unicode translation table */
++                /* unimapd is a ushort count and a pointer to an
++                   array of struct unipair { ushort, ushort } */
++                unimapd.entries  = unipairs;
++                unimapd.entry_ct = USHRT_MAX;
++                if (ioctl(fd, GIO_UNIMAP, &unimapd) >= 0) {
++                        struct unimapinit adv = { 0, 0, 0 };
++
++                        ioctl(vcfd, PIO_UNIMAPCLR, &adv);
++                        ioctl(vcfd, PIO_UNIMAP, &unimapd);
++                }
+         }
+ }
+ 
+ int main(int argc, char **argv) {
+         const char *vc;
+-        char *vc_keymap = NULL;
+-        char *vc_keymap_toggle = NULL;
+-        char *vc_font = NULL;
+-        char *vc_font_map = NULL;
+-        char *vc_font_unimap = NULL;
+-        int fd = -1;
++        _cleanup_free_ char
++                *vc_keymap = NULL, *vc_keymap_toggle = NULL,
++                *vc_font = NULL, *vc_font_map = NULL, *vc_font_unimap = NULL;
++        _cleanup_close_ int fd = -1;
+         bool utf8;
+         pid_t font_pid = 0, keymap_pid = 0;
+         bool font_copy = false;
+@@ -241,12 +263,12 @@ int main(int argc, char **argv) {
+         fd = open_terminal(vc, O_RDWR|O_CLOEXEC);
+         if (fd < 0) {
+                 log_error("Failed to open %s: %m", vc);
+-                goto finish;
++                return EXIT_FAILURE;
+         }
+ 
+         if (!is_vconsole(fd)) {
+                 log_error("Device %s is not a virtual console.", vc);
+-                goto finish;
++                return EXIT_FAILURE;
+         }
+ 
+         utf8 = is_locale_utf8();
+@@ -281,27 +303,27 @@ int main(int argc, char **argv) {
+         else
+                 disable_utf8(fd);
+ 
+-        r = EXIT_FAILURE;
+-        if (keymap_load(vc, vc_keymap, vc_keymap_toggle, utf8, &keymap_pid) >= 0 &&
+-            font_load(vc, vc_font, vc_font_map, vc_font_unimap, &font_pid) >= 0)
+-                r = EXIT_SUCCESS;
+-
+-finish:
+-        if (keymap_pid > 0)
+-                wait_for_terminate_and_warn(KBD_LOADKEYS, keymap_pid);
++        r = font_load(vc, vc_font, vc_font_map, vc_font_unimap, &font_pid);
++        if (r < 0) {
++                log_error("Failed to start " KBD_SETFONT ": %s", strerror(-r));
++                return EXIT_FAILURE;
++        }
+ 
+-        if (font_pid > 0) {
++        if (font_pid > 0)
+                 wait_for_terminate_and_warn(KBD_SETFONT, font_pid);
+-                if (font_copy)
+-                        font_copy_to_all_vcs(fd);
++
++        r = keymap_load(vc, vc_keymap, vc_keymap_toggle, utf8, &keymap_pid);
++        if (r < 0) {
++                log_error("Failed to start " KBD_LOADKEYS ": %s", strerror(-r));
++                return EXIT_FAILURE;
+         }
+ 
+-        free(vc_keymap);
+-        free(vc_font);
+-        free(vc_font_map);
+-        free(vc_font_unimap);
++        if (keymap_pid > 0)
++                wait_for_terminate_and_warn(KBD_LOADKEYS, keymap_pid);
+ 
+-        safe_close(fd);
++        /* Only copy the font when we started setfont successfully */
++        if (font_copy && font_pid > 0)
++                font_copy_to_all_vcs(fd);
+ 
+-        return r;
++        return EXIT_SUCCESS;
+ }
+diff --git a/tmpfiles.d/systemd.conf b/tmpfiles.d/systemd.conf
+index 7c6d6b9..c470045 100644
+--- a/tmpfiles.d/systemd.conf
++++ b/tmpfiles.d/systemd.conf
+@@ -23,6 +23,6 @@ d /run/systemd/machines 0755 root root -
+ d /run/systemd/shutdown 0755 root root -
+ 
+ m /var/log/journal 2755 root systemd-journal - -
+-m /var/log/journal/%m 2755 root systemd-journal - -
++Z /var/log/journal/%m 2755 root systemd-journal - -
+ m /run/log/journal 2755 root systemd-journal - -
+-m /run/log/journal/%m 2755 root systemd-journal - -
++Z /run/log/journal/%m 2755 root systemd-journal - -
+diff --git a/units/console-getty.service.m4.in b/units/console-getty.service.m4.in
+index 8ac51a4..cae9fb5 100644
+--- a/units/console-getty.service.m4.in
++++ b/units/console-getty.service.m4.in
+@@ -15,7 +15,6 @@ After=rc-local.service
+ Before=getty.target
+ 
+ [Service]
+-ExecStart=-/sbin/agetty --noclear --keep-baud console 115200,38400,9600 $TERM
+ Type=idle
+ Restart=always
+ RestartSec=0
+diff --git a/units/container-getty@.service.m4.in b/units/container-getty@.service.m4.in
+index 4f7794b..bad2a9a 100644
+--- a/units/container-getty@.service.m4.in
++++ b/units/container-getty@.service.m4.in
+@@ -16,7 +16,6 @@ Before=getty.target
+ IgnoreOnIsolate=yes
+ 
+ [Service]
+-ExecStart=-/sbin/agetty --noclear --keep-baud pts/%I 115200,38400,9600 $TERM
+ Type=idle
+ Restart=always
+ RestartSec=0
 diff --git a/units/emergency.service.in b/units/emergency.service.in
-index 442f0e0..6b7eafd 100644
+index 94c090f..0d20640 100644
 --- a/units/emergency.service.in
 +++ b/units/emergency.service.in
 @@ -15,7 +15,6 @@ Before=shutdown.target
@@ -685,30 +2665,61 @@ index 442f0e0..6b7eafd 100644
  ExecStartPre=-/bin/echo -e 'Welcome to emergency mode! After logging in, type "journalctl -xb" to view\\nsystem logs, "systemctl reboot" to reboot, "systemctl default" to try again\\nto boot into default mode.'
  ExecStart=-/sbin/sulogin
  ExecStopPost=@SYSTEMCTL@ --fail --no-block default
+diff --git a/units/getty@.service.m4 b/units/getty@.service.m4
+index aa853b8..8bcc647 100644
+--- a/units/getty@.service.m4
++++ b/units/getty@.service.m4
+@@ -23,11 +23,12 @@ IgnoreOnIsolate=yes
+ # On systems without virtual consoles, don't start any getty. Note
+ # that serial gettys are covered by serial-getty@.service, not this
+ # unit.
+-ConditionPathExists=/dev/tty0
++ConditionPathExists=|/dev/tty0
++ConditionVirtualization=|lxc
++ConditionVirtualization=|lxc-libvirt
+ 
+ [Service]
+ # the VT is cleared by TTYVTDisallocate
+-ExecStart=-/sbin/agetty --noclear %I $TERM
+ Type=idle
+ Restart=always
+ RestartSec=0
+diff --git a/units/kmod-static-nodes.service.in b/units/kmod-static-nodes.service.in
+index 368f980..d0c1bd2 100644
+--- a/units/kmod-static-nodes.service.in
++++ b/units/kmod-static-nodes.service.in
+@@ -10,7 +10,6 @@ Description=Create list of required static device nodes for the current kernel
+ DefaultDependencies=no
+ Before=sysinit.target systemd-tmpfiles-setup-dev.service
+ ConditionCapability=CAP_MKNOD
+-ConditionPathExists=/lib/modules/%v/modules.devname
+ 
+ [Service]
+ Type=oneshot
 diff --git a/units/local-fs.target b/units/local-fs.target
-index 18c3d74..a09054c 100644
+index ae3cedc..0e36840 100644
 --- a/units/local-fs.target
 +++ b/units/local-fs.target
-@@ -11,3 +11,5 @@ Documentation=man:systemd.special(7)
- After=local-fs-pre.target
+@@ -13,3 +13,5 @@ DefaultDependencies=no
+ Conflicts=shutdown.target
  OnFailure=emergency.target
- OnFailureIsolate=no
+ OnFailureJobMode=replace-irreversibly
 +
 +X-StopOnReconfiguration=yes
 diff --git a/units/remote-fs.target b/units/remote-fs.target
-index 09213e8..47b4cf5 100644
+index 43ffa5c..156a681 100644
 --- a/units/remote-fs.target
 +++ b/units/remote-fs.target
-@@ -10,5 +10,7 @@ Description=Remote File Systems
- Documentation=man:systemd.special(7)
- After=remote-fs-pre.target
+@@ -12,5 +12,7 @@ After=remote-fs-pre.target
+ DefaultDependencies=no
+ Conflicts=shutdown.target
  
 +X-StopOnReconfiguration=yes
 +
  [Install]
  WantedBy=multi-user.target
 diff --git a/units/rescue.service.m4.in b/units/rescue.service.m4.in
-index 269797a..2c640f4 100644
+index 552ef89..af3915f 100644
 --- a/units/rescue.service.m4.in
 +++ b/units/rescue.service.m4.in
 @@ -16,7 +16,6 @@ Before=shutdown.target
@@ -719,6 +2730,21 @@ index 269797a..2c640f4 100644
  ExecStartPre=-/bin/echo -e 'Welcome to rescue mode! Type "systemctl default" or ^D to enter default mode.\\nType "journalctl -xb" to view system logs. Type "systemctl reboot" to reboot.'
  ExecStart=-/sbin/sulogin
  ExecStopPost=-@SYSTEMCTL@ --fail --no-block default
+diff --git a/units/serial-getty@.service.m4 b/units/serial-getty@.service.m4
+index 4ac51e7..96daa5c 100644
+--- a/units/serial-getty@.service.m4
++++ b/units/serial-getty@.service.m4
+@@ -22,10 +22,8 @@ Before=getty.target
+ IgnoreOnIsolate=yes
+ 
+ [Service]
+-ExecStart=-/sbin/agetty --keep-baud 115200,38400,9600 %I $TERM
+ Type=idle
+ Restart=always
+-RestartSec=0
+ UtmpIdentifier=%I
+ TTYPath=/dev/%I
+ TTYReset=yes
 diff --git a/units/sysinit.target b/units/sysinit.target
 index 8f4fb8f..e0f0147 100644
 --- a/units/sysinit.target
@@ -731,11 +2757,35 @@ index 8f4fb8f..e0f0147 100644
 -After=local-fs.target swap.target emergency.service emergency.target
 +After=emergency.service emergency.target
  RefuseManualStart=yes
+diff --git a/units/systemd-backlight@.service.in b/units/systemd-backlight@.service.in
+index e945d87..77728f2 100644
+--- a/units/systemd-backlight@.service.in
++++ b/units/systemd-backlight@.service.in
+@@ -19,3 +19,4 @@ Type=oneshot
+ RemainAfterExit=yes
+ ExecStart=@rootlibexecdir@/systemd-backlight load %i
+ ExecStop=@rootlibexecdir@/systemd-backlight save %i
++X-RestartIfChanged=false
+diff --git a/units/systemd-journal-flush.service.in b/units/systemd-journal-flush.service.in
+index 503e8a6..fe23b8b 100644
+--- a/units/systemd-journal-flush.service.in
++++ b/units/systemd-journal-flush.service.in
+@@ -10,8 +10,9 @@ Description=Trigger Flushing of Journal to Persistent Storage
+ Documentation=man:systemd-journald.service(8) man:journald.conf(5)
+ DefaultDependencies=no
+ Requires=systemd-journald.service
+-After=systemd-journald.service local-fs.target remote-fs.target
++After=systemd-journald.service
+ Before=systemd-user-sessions.service
++RequiresMountsFor=/var/log/journal
+ 
+ [Service]
+ ExecStart=@rootbindir@/systemctl kill --kill-who=main --signal=SIGUSR1 systemd-journald.service
 diff --git a/units/systemd-journald.service.in b/units/systemd-journald.service.in
-index ab2e50c..9563a7d 100644
+index de93879..c9a49f3 100644
 --- a/units/systemd-journald.service.in
 +++ b/units/systemd-journald.service.in
-@@ -24,3 +24,8 @@ CapabilityBoundingSet=CAP_SYS_ADMIN CAP_DAC_OVERRIDE CAP_SYS_PTRACE CAP_SYSLOG C
+@@ -25,3 +25,8 @@ WatchdogSec=1min
  # Increase the default a bit in order to allow many simultaneous
  # services being run since we keep one fd open per service.
  LimitNOFILE=16384
@@ -744,6 +2794,67 @@ index ab2e50c..9563a7d 100644
 +# journald to stop logging (see
 +# https://bugs.freedesktop.org/show_bug.cgi?id=56043).
 +X-RestartIfChanged=no
+diff --git a/units/systemd-nspawn@.service.in b/units/systemd-nspawn@.service.in
+index ff36e90..e373628 100644
+--- a/units/systemd-nspawn@.service.in
++++ b/units/systemd-nspawn@.service.in
+@@ -11,6 +11,7 @@ Documentation=man:systemd-nspawn(1)
+ 
+ [Service]
+ ExecStart=@bindir@/systemd-nspawn --quiet --keep-unit --boot --link-journal=guest --directory=/var/lib/container/%i
++KillMode=mixed
+ Type=notify
+ 
+ [Install]
+diff --git a/units/systemd-random-seed.service.in b/units/systemd-random-seed.service.in
+index 1879b2f..9b895b9 100644
+--- a/units/systemd-random-seed.service.in
++++ b/units/systemd-random-seed.service.in
+@@ -19,3 +19,4 @@ Type=oneshot
+ RemainAfterExit=yes
+ ExecStart=@rootlibexecdir@/systemd-random-seed load
+ ExecStop=@rootlibexecdir@/systemd-random-seed save
++X-RestartIfChanged=false
+diff --git a/units/systemd-rfkill@.service.in b/units/systemd-rfkill@.service.in
+index 9d264a2..c505535 100644
+--- a/units/systemd-rfkill@.service.in
++++ b/units/systemd-rfkill@.service.in
+@@ -19,3 +19,4 @@ Type=oneshot
+ RemainAfterExit=yes
+ ExecStart=@rootlibexecdir@/systemd-rfkill load %I
+ ExecStop=@rootlibexecdir@/systemd-rfkill save %I
++X-RestartIfChanged=false
+diff --git a/units/systemd-tmpfiles-setup.service.in b/units/systemd-tmpfiles-setup.service.in
+index 01043b7..507f820 100644
+--- a/units/systemd-tmpfiles-setup.service.in
++++ b/units/systemd-tmpfiles-setup.service.in
+@@ -12,7 +12,7 @@ DefaultDependencies=no
+ Wants=local-fs.target
+ Conflicts=shutdown.target
+ After=systemd-readahead-collect.service systemd-readahead-replay.service local-fs.target
+-Before=sysinit.target shutdown.target
++Before=shutdown.target
+ ConditionDirectoryNotEmpty=|/usr/lib/tmpfiles.d
+ ConditionDirectoryNotEmpty=|/lib/tmpfiles.d
+ ConditionDirectoryNotEmpty=|/usr/local/lib/tmpfiles.d
+diff --git a/units/systemd-update-utmp.service.in b/units/systemd-update-utmp.service.in
+index da7dda7..e638145 100644
+--- a/units/systemd-update-utmp.service.in
++++ b/units/systemd-update-utmp.service.in
+@@ -11,7 +11,7 @@ Documentation=man:systemd-update-utmp.service(8) man:utmp(5)
+ DefaultDependencies=no
+ RequiresMountsFor=/var/log/wtmp
+ Conflicts=shutdown.target
+-After=systemd-readahead-collect.service systemd-readahead-replay.service systemd-remount-fs.service systemd-tmpfiles-setup.service auditd.service
++After=systemd-readahead-collect.service systemd-readahead-replay.service systemd-remount-fs.service auditd.service
+ Before=sysinit.target shutdown.target
+ 
+ [Service]
+@@ -19,3 +19,4 @@ Type=oneshot
+ RemainAfterExit=yes
+ ExecStart=@rootlibexecdir@/systemd-update-utmp reboot
+ ExecStop=@rootlibexecdir@/systemd-update-utmp shutdown
++X-RestartIfChanged=false
 diff --git a/units/systemd-user-sessions.service.in b/units/systemd-user-sessions.service.in
 index 0869e73..b6ed958 100644
 --- a/units/systemd-user-sessions.service.in
diff --git a/pkgs/os-specific/linux/systemd/libc-bug-accept4-arm.patch b/pkgs/os-specific/linux/systemd/libc-bug-accept4-arm.patch
deleted file mode 100644
index 7cde2260189..00000000000
--- a/pkgs/os-specific/linux/systemd/libc-bug-accept4-arm.patch
+++ /dev/null
@@ -1,81 +0,0 @@
-Based on a patch for udev in
-nixpkgs(upstart)/pkgs/os-specific/linux/udev/pre-accept4-kernel.patch
-
-It was taken from:
-https://github.com/archlinuxarm/PKGBUILDs/blob/master/core/udev-oxnas/pre-accept4-kernel.patch
-
-Basically, ARM implemented accept4() only in 2.6.36. Nixpkgs now uses
-linux headers from 2.6.35. And the particular nixpkgs glibc version had a bug,
-not checking about 2.6.36 for accept4 on arm.
-
-diff --git a/src/journal/journald-stream.c b/src/journal/journald-stream.c
-index 7b88f74..a9f7b62 100644
---- a/src/journal/journald-stream.c
-+++ b/src/journal/journald-stream.c
-@@ -347,10 +347,12 @@ int stdout_stream_new(Server *s) {
-         int fd, r;
-         socklen_t len;
-         struct epoll_event ev;
-+        int flgs;
- 
-         assert(s);
- 
--        fd = accept4(s->stdout_fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC);
-+        //fd = accept4(s->stdout_fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC);
-+        fd = accept(s->stdout_fd, NULL, NULL);
-         if (fd < 0) {
-                 if (errno == EAGAIN)
-                         return 0;
-@@ -359,6 +361,11 @@ int stdout_stream_new(Server *s) {
-                 return -errno;
-         }
- 
-+        // Since we don't have accept4
-+        flgs = fcntl(fd, F_GETFL, NULL);
-+        if(flgs >= 0) fcntl(fd, F_SETFL, flgs | O_NONBLOCK);
-+        fcntl(fd, F_SETFD, FD_CLOEXEC);
-+
-         if (s->n_stdout_streams >= STDOUT_STREAMS_MAX) {
-                 log_warning("Too many stdout streams, refusing connection.");
-                 close_nointr_nofail(fd);
-diff --git a/src/udev/udev-ctrl.c b/src/udev/udev-ctrl.c
-index a235912..c05e4b4 100644
---- a/src/udev/udev-ctrl.c
-+++ b/src/udev/udev-ctrl.c
-@@ -15,6 +15,7 @@
- #include <stddef.h>
- #include <string.h>
- #include <unistd.h>
-+#include <fcntl.h>
- #include <sys/types.h>
- #include <sys/poll.h>
- #include <sys/socket.h>
-@@ -181,6 +182,7 @@ struct udev_ctrl_connection *udev_ctrl_get_connection(struct udev_ctrl *uctrl)
-         struct ucred ucred;
-         socklen_t slen;
-         const int on = 1;
-+        int flgs;
- 
-         conn = calloc(1, sizeof(struct udev_ctrl_connection));
-         if (conn == NULL)
-@@ -188,13 +190,19 @@ struct udev_ctrl_connection *udev_ctrl_get_connection(struct udev_ctrl *uctrl)
-         conn->refcount = 1;
-         conn->uctrl = uctrl;
- 
--        conn->sock = accept4(uctrl->sock, NULL, NULL, SOCK_CLOEXEC|SOCK_NONBLOCK);
-+        //conn->sock = accept4(uctrl->sock, NULL, NULL, SOCK_CLOEXEC|SOCK_NONBLOCK);
-+        conn->sock = accept(uctrl->sock, NULL, NULL);
-         if (conn->sock < 0) {
-                 if (errno != EINTR)
-                         log_error("unable to receive ctrl connection: %m\n");
-                 goto err;
-         }
- 
-+        // Since we don't have accept4
-+        flgs = fcntl(conn->sock, F_GETFL, NULL);
-+        if(flgs >= 0) fcntl(conn->sock, F_SETFL, flgs | O_NONBLOCK);
-+        fcntl(conn->sock, F_SETFD, FD_CLOEXEC);
-+
-         /* check peer credential of connection */
-         slen = sizeof(ucred);
-         if (getsockopt(conn->sock, SOL_SOCKET, SO_PEERCRED, &ucred, &slen) < 0) {
diff --git a/pkgs/os-specific/linux/tp_smapi/default.nix b/pkgs/os-specific/linux/tp_smapi/default.nix
index 140021605ea..40d9e7c1068 100644
--- a/pkgs/os-specific/linux/tp_smapi/default.nix
+++ b/pkgs/os-specific/linux/tp_smapi/default.nix
@@ -1,23 +1,21 @@
-{stdenv, fetchurl, kernelDev}:
+{stdenv, fetchurl, kernel}:
 
 stdenv.mkDerivation {
-  name = "tp_smapi-0.41-${kernelDev.version}";
+  name = "tp_smapi-0.41-${kernel.version}";
 
   src = fetchurl {
     url = "https://github.com/downloads/evgeni/tp_smapi/tp_smapi-0.41.tar.gz";
     sha256 = "6aef02b92d10360ac9be0db29ae390636be55017990063a092a285c70b54e666";
   };
 
-  buildInputs = [ kernelDev ];
-
   makeFlags = [
-    "KBASE=${kernelDev}/lib/modules/${kernelDev.modDirVersion}"
+    "KBASE=${kernel.dev}/lib/modules/${kernel.modDirVersion}"
     "SHELL=/bin/sh"
   ];
 
   installPhase = ''
-    install -v -D -m 644 thinkpad_ec.ko "$out/lib/modules/${kernelDev.modDirVersion}/kernel/drivers/firmware/thinkpad_ec.ko"
-    install -v -D -m 644 tp_smapi.ko "$out/lib/modules/${kernelDev.modDirVersion}/kernel/drivers/firmware/tp_smapi.ko"
+    install -v -D -m 644 thinkpad_ec.ko "$out/lib/modules/${kernel.modDirVersion}/kernel/drivers/firmware/thinkpad_ec.ko"
+    install -v -D -m 644 tp_smapi.ko "$out/lib/modules/${kernel.modDirVersion}/kernel/drivers/firmware/tp_smapi.ko"
   '';
 
   dontStrip = true;
diff --git a/pkgs/os-specific/linux/tunctl/default.nix b/pkgs/os-specific/linux/tunctl/default.nix
index 8ea3599ff19..fe79c23dc44 100644
--- a/pkgs/os-specific/linux/tunctl/default.nix
+++ b/pkgs/os-specific/linux/tunctl/default.nix
@@ -16,6 +16,6 @@ stdenv.mkDerivation {
   meta = {
     homepage = http://tunctl.sourceforge.net/;
     description = "Utility to set up and maintain TUN/TAP network interfaces";
-    license = "GPLv2";
+    license = stdenv.lib.licenses.gpl2;
   };
 }
diff --git a/pkgs/os-specific/linux/uclibc/default.nix b/pkgs/os-specific/linux/uclibc/default.nix
index e7cce315e8c..a0df3d526f5 100644
--- a/pkgs/os-specific/linux/uclibc/default.nix
+++ b/pkgs/os-specific/linux/uclibc/default.nix
@@ -96,6 +96,6 @@ stdenv.mkDerivation {
   meta = {
     homepage = http://www.uclibc.org/;
     description = "A small implementation of the C library";
-    license = "LGPLv2";
+    license = stdenv.lib.licenses.lgpl2;
   };
 }
diff --git a/pkgs/os-specific/linux/udisks/1-default.nix b/pkgs/os-specific/linux/udisks/1-default.nix
index b53af52755f..09731d54ab7 100644
--- a/pkgs/os-specific/linux/udisks/1-default.nix
+++ b/pkgs/os-specific/linux/udisks/1-default.nix
@@ -10,7 +10,7 @@ stdenv.mkDerivation rec {
     sha256 = "1xgqifddwaavmjc8c30i0mdffyirsld7c6qhfyjw7f9khwv8jjw5";
   };
 
-  patches = [ ./purity.patch ./no-pci-db.patch ];
+  patches = [ ./purity.patch ./no-pci-db.patch ./cve-2014-0004.patch ];
 
   postPatch =
     ''
diff --git a/pkgs/os-specific/linux/udisks/2-default.nix b/pkgs/os-specific/linux/udisks/2-default.nix
index 28cdbe18978..6c9b743fe17 100644
--- a/pkgs/os-specific/linux/udisks/2-default.nix
+++ b/pkgs/os-specific/linux/udisks/2-default.nix
@@ -4,11 +4,11 @@
 }:
 
 stdenv.mkDerivation rec {
-  name = "udisks-2.1.0";
+  name = "udisks-2.1.3";
 
   src = fetchurl {
     url = "http://udisks.freedesktop.org/releases/${name}.tar.bz2";
-    sha256 = "1a0mipihilscv9jwy59xrqn2kkri9p12a09anpjdld83l7jhh0ii";
+    sha256 = "0bb3403pa23j317b7z9ikdigr6ll5cl93l4hiy4afjgfa7b2zjaw";
   };
 
   patches = [ ./force-path.patch ];
@@ -30,7 +30,7 @@ stdenv.mkDerivation rec {
 
   configureFlags = [
     "--localstatedir=/var"
-    "--with-systemdsystemunitdir=$(out)/etc/systemd/systemd"
+    "--with-systemdsystemunitdir=$(out)/etc/systemd/system"
     "--with-udevdir=$(out)/lib/udev"
   ];
 
diff --git a/pkgs/os-specific/linux/udisks/cve-2014-0004.patch b/pkgs/os-specific/linux/udisks/cve-2014-0004.patch
new file mode 100644
index 00000000000..ce907507538
--- /dev/null
+++ b/pkgs/os-specific/linux/udisks/cve-2014-0004.patch
@@ -0,0 +1,82 @@
+commit ebf61ed8471a45cf8bce7231de00cb1bbc140708
+Author: Martin Pitt <martin.pitt@ubuntu.com>
+Date:   Wed Mar 5 14:07:44 2014 +0100
+
+    Fix buffer overflow in mount path parsing
+    
+    In the mount monitor we parse mount points from /proc/self/mountinfo.  Ensure
+    that we don't overflow the buffers on platforms where mount paths could be
+    longer than PATH_MAX (unknown if that can actually happen), as at least the
+    mount paths for hotpluggable devices are somewhat user-controlled.
+    
+    Thanks to Florian Weimer for discovering this bug, and to David Zeuthen
+    for his initial patch!
+    
+    CVE-2014-0004
+
+Index: udisks-1.0.4/src/mount-monitor.c
+===================================================================
+--- udisks-1.0.4.orig/src/mount-monitor.c	2011-08-25 20:27:33.000000000 +0200
++++ udisks-1.0.4/src/mount-monitor.c	2014-03-10 13:38:18.309406561 +0100
+@@ -39,6 +39,11 @@
+ #include "mount.h"
+ #include "private.h"
+ 
++/* build a %Ns format string macro with N == PATH_MAX */
++#define xstr(s) str(s)
++#define str(s) #s
++#define PATH_MAX_FMT "%" xstr(PATH_MAX) "s"
++
+ /*--------------------------------------------------------------------------------------------------------------*/
+ 
+ enum
+@@ -320,8 +325,8 @@ mount_monitor_ensure (MountMonitor *moni
+       guint mount_id;
+       guint parent_id;
+       guint major, minor;
+-      gchar encoded_root[PATH_MAX];
+-      gchar encoded_mount_point[PATH_MAX];
++      gchar encoded_root[PATH_MAX + 1];
++      gchar encoded_mount_point[PATH_MAX + 1];
+       gchar *mount_point;
+       dev_t dev;
+ 
+@@ -329,7 +334,7 @@ mount_monitor_ensure (MountMonitor *moni
+         continue;
+ 
+       if (sscanf (lines[n],
+-                  "%d %d %d:%d %s %s",
++                  "%d %d %d:%d " PATH_MAX_FMT " " PATH_MAX_FMT,
+                   &mount_id,
+                   &parent_id,
+                   &major,
+@@ -340,6 +345,8 @@ mount_monitor_ensure (MountMonitor *moni
+           g_warning ("Error parsing line '%s'", lines[n]);
+           continue;
+         }
++      encoded_root[sizeof encoded_root - 1] = '\0';
++      encoded_mount_point[sizeof encoded_mount_point - 1] = '\0';
+ 
+       /* ignore mounts where only a subtree of a filesystem is mounted */
+       if (g_strcmp0 (encoded_root, "/") != 0)
+@@ -358,15 +365,17 @@ mount_monitor_ensure (MountMonitor *moni
+           sep = strstr (lines[n], " - ");
+           if (sep != NULL)
+             {
+-              gchar fstype[PATH_MAX];
+-              gchar mount_source[PATH_MAX];
++              gchar fstype[PATH_MAX + 1];
++              gchar mount_source[PATH_MAX + 1];
+               struct stat statbuf;
+ 
+-              if (sscanf (sep + 3, "%s %s", fstype, mount_source) != 2)
++              if (sscanf (sep + 3, PATH_MAX_FMT " " PATH_MAX_FMT, fstype, mount_source) != 2)
+                 {
+                   g_warning ("Error parsing things past - for '%s'", lines[n]);
+                   continue;
+                 }
++              fstype[sizeof fstype - 1] = '\0';
++              mount_source[sizeof mount_source - 1] = '\0';
+ 
+               if (g_strcmp0 (fstype, "btrfs") != 0)
+                 continue;
diff --git a/pkgs/os-specific/linux/upower/0.99.nix b/pkgs/os-specific/linux/upower/0.99.nix
new file mode 100644
index 00000000000..c42fea16d35
--- /dev/null
+++ b/pkgs/os-specific/linux/upower/0.99.nix
@@ -0,0 +1,51 @@
+{ stdenv, fetchurl, pkgconfig, glib, dbus, dbus_glib, dbus_tools, polkit
+, intltool, libxslt, docbook_xsl, udev, libusb1, pmutils
+, useSystemd ? true, systemd, gobjectIntrospection
+}:
+
+assert stdenv.isLinux;
+
+stdenv.mkDerivation rec {
+  name = "upower-0.99.0";
+
+  src = fetchurl {
+    url = "http://upower.freedesktop.org/releases/${name}.tar.xz";
+    sha256 = "189rd8j5czy4fs7imxvr38icjh9vlgdz6ki2h08v530h96clndaz";
+  };
+
+  buildInputs =
+    [ dbus_glib polkit intltool libxslt docbook_xsl udev libusb1 gobjectIntrospection ]
+    ++ stdenv.lib.optional useSystemd systemd;
+
+  nativeBuildInputs = [ pkgconfig ];
+
+  preConfigure =
+    ''
+      substituteInPlace src/linux/up-backend.c \
+        --replace /usr/bin/pm- ${pmutils}/bin/pm- \
+        --replace /usr/sbin/pm- ${pmutils}/sbin/pm-
+      substituteInPlace src/notify-upower.sh \
+        --replace /usr/bin/dbus-send ${dbus_tools}/bin/dbus-send
+    '';
+
+  configureFlags =
+    [ "--with-backend=linux" "--localstatedir=/var"
+      "--enable-deprecated" # needed for Xfce (Nov 2013)
+    ]
+    ++ stdenv.lib.optional useSystemd
+    [ "--enable-systemd"
+      "--with-systemdsystemunitdir=$(out)/etc/systemd/system"
+      "--with-systemdutildir=$(out)/lib/systemd/system-sleep"
+      "--with-udevrulesdir=$(out)/lib/udev/rules.d"
+    ];
+
+  NIX_CFLAGS_LINK = "-lgcc_s";
+
+  installFlags = "historydir=$(TMPDIR)/foo";
+
+  meta = {
+    homepage = http://upower.freedesktop.org/;
+    description = "A D-Bus service for power management";
+    platforms = stdenv.lib.platforms.linux;
+  };
+}
diff --git a/pkgs/os-specific/linux/upower/default.nix b/pkgs/os-specific/linux/upower/default.nix
index d5dc292ac33..605d3d7adc5 100644
--- a/pkgs/os-specific/linux/upower/default.nix
+++ b/pkgs/os-specific/linux/upower/default.nix
@@ -1,32 +1,38 @@
-{ stdenv, fetchurl, pkgconfig, glib, dbus, dbus_glib, dbus_tools, polkit
+{ stdenv, fetchurl, fetchpatch, pkgconfig, glib, dbus, dbus_glib, dbus_tools, polkit
 , intltool, libxslt, docbook_xsl, udev, libusb1, pmutils
-, useSystemd ? true, systemd
+, useSystemd ? true, systemd, gobjectIntrospection
 }:
 
 assert stdenv.isLinux;
 
 stdenv.mkDerivation rec {
-  name = "upower-0.9.19";
+  name = "upower-0.9.23";
 
   src = fetchurl {
     url = "http://upower.freedesktop.org/releases/${name}.tar.xz";
-    sha256 = "053yahks5c7nwdxwx8q6nqp3mxbqldmc844mzyvc3ws9635zmisl";
+    sha256 = "06wqhab2mn0j4biiwh7mn4kxbxnfnzjkxvhpgvnlpaz9m2q54cj3";
   };
 
+  patches = [
+    (fetchpatch rec {
+      url = "http://anonscm.debian.org/gitweb/?p=pkg-utopia/upower.git;"
+        + "a=blob_plain;f=debian/patches/${name};hb=b424b2763fbbba95df8c6ab3feeb57d072a9ddf7";
+      sha256 = "0iq991abrn745icyz6x0wyixrjli01vbmbd9lnwwgyil58h3z8sp";
+      name = "no_deprecation_define.patch";
+    })
+    (fetchpatch {
+      url = "http://cgit.freedesktop.org/upower/patch/?id=22da1a0bc5943b683189418d8b0f766e91b2bdbe";
+      sha256 = "0yfgg6pw4bwskannvdwjxr75lgdrjpxhsskwlzm0frp8v5jy4k4z";
+      name = "clamp-battery-percentages.patch";
+    })
+  ];
+
   buildInputs =
-    [ dbus_glib polkit intltool libxslt docbook_xsl udev libusb1 ]
+    [ dbus_glib polkit intltool libxslt docbook_xsl udev libusb1 gobjectIntrospection ]
     ++ stdenv.lib.optional useSystemd systemd;
 
   nativeBuildInputs = [ pkgconfig ];
 
-  configureFlags =
-    [ "--with-backend=linux" "--localstatedir=/var" ]
-    ++ stdenv.lib.optional useSystemd
-    [ "--enable-systemd"
-      "--with-systemdsystemunitdir=$(out)/etc/systemd/system"
-      "--with-systemdutildir=$(out)/lib/systemd/system-sleep"
-    ];
-
   preConfigure =
     ''
       substituteInPlace src/linux/up-backend.c \
@@ -36,6 +42,17 @@ stdenv.mkDerivation rec {
         --replace /usr/bin/dbus-send ${dbus_tools}/bin/dbus-send
     '';
 
+  configureFlags =
+    [ "--with-backend=linux" "--localstatedir=/var"
+      "--enable-deprecated" # needed for Xfce (Nov 2013)
+    ]
+    ++ stdenv.lib.optional useSystemd
+    [ "--enable-systemd"
+      "--with-systemdsystemunitdir=$(out)/etc/systemd/system"
+      "--with-systemdutildir=$(out)/lib/systemd/system-sleep"
+      "--with-udevrulesdir=$(out)/lib/udev/rules.d"
+    ];
+
   NIX_CFLAGS_LINK = "-lgcc_s";
 
   installFlags = "historydir=$(TMPDIR)/foo";
diff --git a/pkgs/os-specific/linux/usermount/default.nix b/pkgs/os-specific/linux/usermount/default.nix
new file mode 100644
index 00000000000..9bf8692d1ce
--- /dev/null
+++ b/pkgs/os-specific/linux/usermount/default.nix
@@ -0,0 +1,28 @@
+{ stdenv, fetchgit, pkgconfig, dbus, libnotify, udisks2, gdk_pixbuf }:
+
+stdenv.mkDerivation {
+  name = "usermount-0.1";
+
+  src = fetchgit {
+    url = "https://github.com/tom5760/usermount.git";
+    rev = "0d6aba3c1f8fec80de502f5b92fd8b28041cc8e4";
+    sha256 = "1bzxwq83ikljnv0f55siyd6rd0gs9v7jl9947lw6s1npa63x3b55";
+  };
+
+  buildInputs = [ pkgconfig dbus libnotify udisks2 gdk_pixbuf ];
+
+  NIX_CFLAGS_COMPILE = [ "-DENABLE_NOTIFICATIONS" ];
+
+  installPhase = ''
+    mkdir -p $out/bin
+    mv usermount $out/bin/
+  '';
+
+  meta = {
+    homepage = https://github.com/tom5760/usermount;
+    description = "A simple tool to automatically mount removable drives using UDisks2 and D-Bus.";
+    license = stdenv.lib.licenses.mit;
+    platforms = stdenv.lib.platforms.linux;
+    maintainers = with stdenv.lib.maintainers; [ the-kenny ];
+  };
+}
diff --git a/pkgs/os-specific/linux/util-linux/default.nix b/pkgs/os-specific/linux/util-linux/default.nix
index 84cb42693f1..03b4f2a894a 100644
--- a/pkgs/os-specific/linux/util-linux/default.nix
+++ b/pkgs/os-specific/linux/util-linux/default.nix
@@ -1,11 +1,11 @@
 { stdenv, fetchurl, zlib, ncurses ? null, perl ? null, pam }:
 
 stdenv.mkDerivation rec {
-  name = "util-linux-2.22.2";
+  name = "util-linux-2.24.2";
 
   src = fetchurl {
-    url = "http://www.kernel.org/pub/linux/utils/util-linux/v2.22/${name}.tar.bz2";
-    sha256 = "0vf3ifb45gr4cd27pmmxk8y5b3r0920mv16fv0vfwz5705xa2qvl";
+    url = "http://www.kernel.org/pub/linux/utils/util-linux/v2.24/${name}.tar.xz";
+    sha256 = "1w0g8q5aj5pjdf8l52g0mxyvlk62f4dch51q9jm3hnqwgz0dchqj";
   };
 
   outputs = [ "dev" "out" "bin" ];
@@ -19,8 +19,6 @@ stdenv.mkDerivation rec {
   # (/sbin/mount.*) through an environment variable, but that's
   # somewhat risky because we have to consider that mount can setuid
   # root...
-  # --enable-libmount-mount  fixes the behaviour being /etc/mtab a symlink to /proc/monunts
-  #     http://pl.digipedia.org/usenet/thread/19513/1924/
   configureFlags = ''
     --enable-write
     --enable-last
@@ -38,6 +36,10 @@ stdenv.mkDerivation rec {
     ++ stdenv.lib.optional (ncurses != null) ncurses
     ++ stdenv.lib.optional (perl != null) perl;
 
+  postInstall = ''
+    rm $out/bin/su # su should be supplied by the su package (shadow)
+  '';
+
   enableParallelBuilding = true;
 
   meta = {
diff --git a/pkgs/os-specific/linux/v4l-utils/default.nix b/pkgs/os-specific/linux/v4l-utils/default.nix
index 8e6584465d0..c220d2d2dd0 100644
--- a/pkgs/os-specific/linux/v4l-utils/default.nix
+++ b/pkgs/os-specific/linux/v4l-utils/default.nix
@@ -4,11 +4,11 @@
 assert withQt4 -> qt4 != null;
 
 stdenv.mkDerivation rec {
-  name = "v4l-utils-0.9.3";
+  name = "v4l-utils-1.0.0";
 
   src = fetchurl {
     url = "http://linuxtv.org/downloads/v4l-utils/${name}.tar.bz2";
-    sha256 = "0gaag38x47wlvmp4j60wgf9ma1rxzfyg7i12zxxxi4m3cpcb0bah";
+    sha256 = "0c2z500ijxr1ldzb4snasfpwi2icp04f8pk7akiqjkp0k4h8iqqx";
   };
 
   buildInputs = [ which ];
diff --git a/pkgs/os-specific/linux/v4l2loopback/default.nix b/pkgs/os-specific/linux/v4l2loopback/default.nix
new file mode 100644
index 00000000000..5b88d4c7556
--- /dev/null
+++ b/pkgs/os-specific/linux/v4l2loopback/default.nix
@@ -0,0 +1,32 @@
+{ stdenv, fetchurl, kernel, kmod }:
+
+stdenv.mkDerivation rec {
+  name = "v4l2loopback-${version}-${kernel.version}";
+  version = "0.8.0";
+
+  src = fetchurl {
+    url = "https://github.com/umlaeute/v4l2loopback/archive/v${version}.tar.gz";
+    sha256 = "1rhsgc4prrj8s6njixic7fs5m3gs94v9hhf3am6lnfh5yv6yab9h";
+  };
+  
+  preBuild = ''
+    substituteInPlace Makefile --replace "modules_install" "INSTALL_MOD_PATH=$out modules_install"
+    sed -i '/depmod/d' Makefile
+    export PATH=${kmod}/sbin:$PATH
+  '';
+  
+  buildInputs = [ kmod ];
+  
+  makeFlags = [
+    "KERNELRELEASE=${kernel.modDirVersion}"
+    "KERNEL_DIR=${kernel.dev}/lib/modules/${kernel.modDirVersion}/build"
+  ];
+
+  meta = with stdenv.lib; {
+    description = "A kernel module to create V4L2 loopback devices";
+    homepage = https://github.com/umlaeute/v4l2loopback;
+    license = licenses.gpl2;
+    maintainers = [ maintainers.iElectric ];
+    platforms = platforms.linux;
+  };
+}
diff --git a/pkgs/os-specific/linux/v86d/default.nix b/pkgs/os-specific/linux/v86d/default.nix
index 698a7ab4ec8..2ad3087d6a1 100644
--- a/pkgs/os-specific/linux/v86d/default.nix
+++ b/pkgs/os-specific/linux/v86d/default.nix
@@ -1,7 +1,7 @@
-{stdenv, fetchurl, klibc, kernelDev, withKlibc ? true}:
+{stdenv, fetchurl, klibc, kernel, withKlibc ? true}:
 
 stdenv.mkDerivation rec {
-  name = "v86d-${version}-${kernelDev.version}";
+  name = "v86d-${version}-${kernel.version}";
   version = "0.1.10";
 
   src = fetchurl {
@@ -18,7 +18,7 @@ stdenv.mkDerivation rec {
   configureFlags = if withKlibc then [ "--with-klibc" ] else [ "--default" ];
 
   makeFlags = [
-    "KDIR=${kernelDev}/lib/modules/${kernelDev.modDirVersion}/source"
+    "KDIR=${kernel.dev}/lib/modules/${kernel.modDirVersion}/source"
     "DESTDIR=$(out)"
   ];
 
diff --git a/pkgs/os-specific/linux/wis-go7007/default.nix b/pkgs/os-specific/linux/wis-go7007/default.nix
index 7f27196ba6b..53868672025 100644
--- a/pkgs/os-specific/linux/wis-go7007/default.nix
+++ b/pkgs/os-specific/linux/wis-go7007/default.nix
@@ -1,4 +1,4 @@
-{stdenv, fetchurl, kernelDev, ncurses, fxload}:
+{stdenv, fetchurl, kernel, ncurses, fxload}:
 
 let
 
@@ -12,7 +12,7 @@ let
 in   
 
 stdenv.mkDerivation {
-  name = "wis-go7007-0.9.8-${kernelDev.version}";
+  name = "wis-go7007-0.9.8-${kernel.version}";
 
   src = fetchurl {
     url = http://gentoo.osuosl.org/distfiles/wis-go7007-linux-0.9.8.tar.bz2;
@@ -47,16 +47,6 @@ stdenv.mkDerivation {
   '';
 
   preBuild = ''
-    # Urgh, we need the complete kernel sources for some header
-    # files.  So unpack the original kernel source tarball and copy
-    # the configured include directory etc. on top of it.
-    kernelVersion=$(cd ${kernelDev}/lib/modules && ls)
-    kernelBuild=$(echo ${kernelDev}/lib/modules/$kernelVersion/source)
-    tar xvfj ${kernelDev.src}
-    kernelSource=$(echo $(pwd)/linux-*)
-    cp -prd $kernelBuild/* $kernelSource
-
-    #includeDir=$out/lib/modules/$kernelVersion/source/include/linux
     includeDir=$TMPDIR/scratch
     substituteInPlace Makefile \
         --replace '$(DESTDIR)$(KSRC)/include/linux' $includeDir \
@@ -65,7 +55,7 @@ stdenv.mkDerivation {
     mkdir -p $out/etc/hotplug/usb
     mkdir -p $out/etc/udev/rules.d
  
-    makeFlagsArray=(KERNELSRC=$kernelSource \
+    makeFlagsArray=(KERNELSRC=${kernel.dev}/lib/modules/${kernel.modDirVersion}/source \
         FIRMWARE_DIR=$out/firmware FXLOAD=${fxload}/sbin/fxload \
         DESTDIR=$out SKIP_DEPMOD=1 \
         USE_UDEV=y)
@@ -79,5 +69,6 @@ stdenv.mkDerivation {
   meta = {
     description = "Kernel module for the Micronas GO7007, used in a number of USB TV devices";
     homepage = http://oss.wischip.com/;
+    broken = true;
   };
 }
diff --git a/pkgs/os-specific/linux/wpa_supplicant/default.nix b/pkgs/os-specific/linux/wpa_supplicant/default.nix
index ec2c704cfb5..937f65089e9 100644
--- a/pkgs/os-specific/linux/wpa_supplicant/default.nix
+++ b/pkgs/os-specific/linux/wpa_supplicant/default.nix
@@ -5,13 +5,13 @@
 assert readlineSupport -> readline != null;
 
 stdenv.mkDerivation rec {
-  version = "2.0";
+  version = "2.2";
 
   name = "wpa_supplicant-${version}";
 
   src = fetchurl {
     url = "http://hostap.epitest.fi/releases/${name}.tar.gz";
-    sha256 = "02cy6wrs4nzm7wbq9mc1vby8lnj58k4sb10h718ks8mmzc4mc49c";
+    sha256 = "1vf8jc4yyksbxf86narvsli3vxfbm8nbnim2mdp66nd6d3yvin70";
   };
 
   extraConfig =
@@ -42,14 +42,14 @@ stdenv.mkDerivation rec {
 
   postInstall = ''
     mkdir -p $out/share/man/man5 $out/share/man/man8
-    cp -v doc/docbook/*.5 $out/share/man/man5/
-    cp -v doc/docbook/*.8 $out/share/man/man8/
+    cp -v "doc/docbook/"*.5 $out/share/man/man5/
+    cp -v "doc/docbook/"*.8 $out/share/man/man8/
     mkdir -p $out/etc/dbus-1/system.d $out/share/dbus-1/system-services $out/etc/systemd/system
-    cp -v dbus/*service $out/share/dbus-1/system-services
-    sed -e "s@/sbin/wpa_supplicant@$out&@" -i $out/share/dbus-1/system-services/*
+    cp -v "dbus/"*service $out/share/dbus-1/system-services
+    sed -e "s@/sbin/wpa_supplicant@$out&@" -i "$out/share/dbus-1/system-services/"*
     cp -v dbus/dbus-wpa_supplicant.conf $out/etc/dbus-1/system.d
-    cp -v systemd/*.service $out/etc/systemd/system
-  ''; # */
+    cp -v "systemd/"*.service $out/etc/systemd/system
+  '';
 
   meta = {
     homepage = http://hostap.epitest.fi/wpa_supplicant/;
diff --git a/pkgs/os-specific/linux/wpa_supplicant/gui.nix b/pkgs/os-specific/linux/wpa_supplicant/gui.nix
index 29591bf0335..59a3c51c4d6 100644
--- a/pkgs/os-specific/linux/wpa_supplicant/gui.nix
+++ b/pkgs/os-specific/linux/wpa_supplicant/gui.nix
@@ -37,6 +37,6 @@ stdenv.mkDerivation {
 
   meta = {
     description = "Qt-based GUI for wpa_supplicant";
-    inherit (qt4.meta) platforms;
+    platforms = stdenv.lib.platforms.linux;
   };
 }
diff --git a/pkgs/os-specific/linux/wvdial/default.nix b/pkgs/os-specific/linux/wvdial/default.nix
index eb9d09d2a11..7decd42b376 100644
--- a/pkgs/os-specific/linux/wvdial/default.nix
+++ b/pkgs/os-specific/linux/wvdial/default.nix
@@ -15,6 +15,8 @@ stdenv.mkDerivation rec {
     export makeFlags="prefix=$out"
     # not sure about this line
     sed -i 's@/etc/ppp/peers@$out/etc/ppp/peers@' Makefile.in
+
+    sed -e '1i#include <unistd.h>' -i $(find . -name '*.cc')
   '';
 
   meta = {
diff --git a/pkgs/os-specific/linux/x86info/default.nix b/pkgs/os-specific/linux/x86info/default.nix
index 6cd2a431a60..eaec63f98bf 100644
--- a/pkgs/os-specific/linux/x86info/default.nix
+++ b/pkgs/os-specific/linux/x86info/default.nix
@@ -14,7 +14,7 @@ stdenv.mkDerivation rec {
   buildInputs = [ pciutils python ];
 
   installPhase = ''
-    ensureDir $out/bin
+    mkdir -p $out/bin
     cp x86info lsmsr $out/bin
   '';
 
diff --git a/pkgs/os-specific/linux/xf86-input-mtrack/default.nix b/pkgs/os-specific/linux/xf86-input-mtrack/default.nix
index 4f74ce57ea8..a4fd00e4911 100644
--- a/pkgs/os-specific/linux/xf86-input-mtrack/default.nix
+++ b/pkgs/os-specific/linux/xf86-input-mtrack/default.nix
@@ -44,9 +44,6 @@ stdenv.mkDerivation {
 
     description = "An Xorg driver for multitouch trackpads";
 
-    license = "gplv2";
-
-    maintainers = [ stdenv.lib.maintainers.shlevy ];
+    license = stdenv.lib.licenses.gpl2;
   };
 }
-
diff --git a/pkgs/os-specific/linux/xf86-input-multitouch/default.nix b/pkgs/os-specific/linux/xf86-input-multitouch/default.nix
index c5cc5f3b68f..7abf6d7c828 100644
--- a/pkgs/os-specific/linux/xf86-input-multitouch/default.nix
+++ b/pkgs/os-specific/linux/xf86-input-multitouch/default.nix
@@ -45,9 +45,6 @@ stdenv.mkDerivation {
 
     description = "Brings multitouch gestures to the Linux desktop";
 
-    license = "gplv2";
-
-    maintainers = [ stdenv.lib.maintainers.shlevy ];
+    license = stdenv.lib.licenses.gpl2;
   };
 }
-
diff --git a/pkgs/os-specific/linux/xf86-input-wacom/default.nix b/pkgs/os-specific/linux/xf86-input-wacom/default.nix
index 4350694c13a..d4786037b5a 100644
--- a/pkgs/os-specific/linux/xf86-input-wacom/default.nix
+++ b/pkgs/os-specific/linux/xf86-input-wacom/default.nix
@@ -3,11 +3,11 @@
 , ncurses, pkgconfig, randrproto, xorgserver, xproto, udev, libXinerama, pixman }:
 
 stdenv.mkDerivation rec {
-  name = "xf86-input-wacom-0.20.0";
+  name = "xf86-input-wacom-0.25.0";
 
   src = fetchurl {
     url = "mirror://sourceforge/linuxwacom/${name}.tar.bz2";
-    sha256 = "1408zjqsakcyx6v81qwh4q7m49cc6vcaad54jaw8ycw4i832jvjq";
+    sha256 = "06kwcxmgja0xwc5glzwmxm237bsv9fk52k2d6ffq4naqfzn2k31k";
   };
 
   buildInputs = [ inputproto libX11 libXext libXi libXrandr libXrender
diff --git a/pkgs/os-specific/linux/xf86-video-nouveau/default.nix b/pkgs/os-specific/linux/xf86-video-nouveau/default.nix
deleted file mode 100644
index 8ac5cdb6969..00000000000
--- a/pkgs/os-specific/linux/xf86-video-nouveau/default.nix
+++ /dev/null
@@ -1,37 +0,0 @@
-{ stdenv
-, fetchurl
-, autoconf
-, automake
-, libtool
-, xorgserver, xproto, fontsproto, xf86driproto, renderproto, videoproto, pixman
-, utilmacros
-, libdrm
-, pkgconfig }:
-
-stdenv.mkDerivation rec {
-  name = "xf86-video-nouveau-1.0.7";
-
-  src = fetchurl {
-    url = "mirror://xorg/individual/driver/${name}.tar.bz2";
-    sha256 = "0cg1q9dz9ksfp593x707gr10s8p7z00zdws1r4lshg42w5ccd1yi";
-  };
-
-
-  buildInputs = [
-    xorgserver xproto fontsproto xf86driproto renderproto videoproto pixman
-    utilmacros
-    libdrm
-    pkgconfig
-  ];
-
-
-  meta = {
-    homepage = http://nouveau.freedesktop.org/wiki/;
-
-    description = "The xorg driver for nouveau-driven video cards";
-
-    license = "gplv2";
-
-    maintainers = [ stdenv.lib.maintainers.shlevy ];
-  };
-}
diff --git a/pkgs/os-specific/linux/zfs/default.nix b/pkgs/os-specific/linux/zfs/default.nix
index 06615d170a1..0242c586cea 100644
--- a/pkgs/os-specific/linux/zfs/default.nix
+++ b/pkgs/os-specific/linux/zfs/default.nix
@@ -1,16 +1,16 @@
-{ stdenv, fetchurl, kernelDev, spl, perl, autoconf, automake, libtool, zlib, libuuid, coreutils, utillinux }:
+{ stdenv, fetchurl, kernel, spl, perl, autoconf, automake, libtool, zlib, libuuid, coreutils, utillinux }:
 
 stdenv.mkDerivation {
-  name = "zfs-0.6.2-${kernelDev.version}";
+  name = "zfs-0.6.3-${kernel.version}";
 
   src = fetchurl {
-    url = http://archive.zfsonlinux.org/downloads/zfsonlinux/zfs/zfs-0.6.2.tar.gz;
-    sha256 = "18b5f18k8mwb17r5ippsilmp1a2sqjw9fwn0z82159dkhsadg33b";
+    url = http://archive.zfsonlinux.org/downloads/zfsonlinux/zfs/zfs-0.6.3.tar.gz;
+    sha256 = "06rrip9fxn13x6qnyp6br68r9pcygb95lld25hnnj88m2vagvg19";
   };
 
   patches = [ ./mount_zfs_prefix.patch ./nix-build.patch ];
 
-  buildInputs = [ kernelDev spl perl autoconf automake libtool zlib libuuid coreutils ];
+  buildInputs = [ spl perl autoconf automake libtool zlib libuuid coreutils ];
 
   # for zdb to get the rpath to libgcc_s, needed for pthread_cancel to work
   NIX_CFLAGS_LINK = "-lgcc_s";
@@ -27,11 +27,14 @@ stdenv.mkDerivation {
     substituteInPlace ./cmd/ztest/ztest.c          --replace "/usr/sbin/zdb"     "$out/sbin/zdb"
   '';
 
-  configureFlags = ''
-    --with-linux=${kernelDev}/lib/modules/${kernelDev.modDirVersion}/build 
-    --with-linux-obj=${kernelDev}/lib/modules/${kernelDev.modDirVersion}/build 
-    --with-spl=${spl}/libexec/spl
-  '';
+  configureFlags = [
+    "--disable-systemd"
+    "--with-linux=${kernel.dev}/lib/modules/${kernel.modDirVersion}/source"
+    "--with-linux-obj=${kernel.dev}/lib/modules/${kernel.modDirVersion}/build"
+    "--with-spl=${spl}/libexec/spl"
+    "--with-dracutdir=$(out)/lib/dracut"
+    "--with-udevdir=$(out)/lib/udev"
+  ];
 
   enableParallelBuilding = true;
 
@@ -45,6 +48,6 @@ stdenv.mkDerivation {
     homepage = http://zfsonlinux.org/;
     license = stdenv.lib.licenses.cddl;
     platforms = stdenv.lib.platforms.linux;
-    maintainers = with stdenv.lib.maintainers; [ jcumming ];
+    maintainers = with stdenv.lib.maintainers; [ jcumming wizeman ];
   };
 }
diff --git a/pkgs/os-specific/linux/zfs/git.nix b/pkgs/os-specific/linux/zfs/git.nix
new file mode 100644
index 00000000000..e88cb9d6130
--- /dev/null
+++ b/pkgs/os-specific/linux/zfs/git.nix
@@ -0,0 +1,54 @@
+{ stdenv, fetchgit, kernel, spl_git, perl, autoconf, automake, libtool, zlib, libuuid, coreutils, utillinux }:
+
+stdenv.mkDerivation {
+  name = "zfs-0.6.3-${kernel.version}";
+
+  src = fetchgit {
+    url = git://github.com/zfsonlinux/zfs.git;
+    rev = "07dabd234dd51a1e5adc5bd21cddf5b5fdc70732";
+    sha256 = "1yqsfdhyzh33aisfvwqd692n5kfgnlz7yjixd2gqn8vx9bv0dz0b";
+  };
+
+  patches = [ ./mount_zfs_prefix.patch ./nix-build.patch ];
+
+  buildInputs = [ spl_git perl autoconf automake libtool zlib libuuid coreutils ];
+
+  # for zdb to get the rpath to libgcc_s, needed for pthread_cancel to work
+  NIX_CFLAGS_LINK = "-lgcc_s";
+
+  preConfigure = ''
+    ./autogen.sh
+
+    substituteInPlace ./module/zfs/zfs_ctldir.c    --replace "umount -t zfs"     "${utillinux}/bin/umount -t zfs"
+    substituteInPlace ./module/zfs/zfs_ctldir.c    --replace "mount -t zfs"      "${utillinux}/bin/mount -t zfs"
+    substituteInPlace ./lib/libzfs/libzfs_mount.c  --replace "/bin/umount"       "${utillinux}/bin/umount"
+    substituteInPlace ./lib/libzfs/libzfs_mount.c  --replace "/bin/mount"        "${utillinux}/bin/mount"
+    substituteInPlace ./udev/rules.d/*             --replace "/lib/udev/vdev_id" "$out/lib/udev/vdev_id"
+    substituteInPlace ./cmd/ztest/ztest.c          --replace "/usr/sbin/ztest"   "$out/sbin/ztest"
+    substituteInPlace ./cmd/ztest/ztest.c          --replace "/usr/sbin/zdb"     "$out/sbin/zdb"
+  '';
+
+  configureFlags = [
+    "--disable-systemd"
+    "--with-linux=${kernel.dev}/lib/modules/${kernel.modDirVersion}/source"
+    "--with-linux-obj=${kernel.dev}/lib/modules/${kernel.modDirVersion}/build"
+    "--with-spl=${spl_git}/libexec/spl"
+    "--with-dracutdir=$(out)/lib/dracut"
+    "--with-udevdir=$(out)/lib/udev"
+  ];
+
+  enableParallelBuilding = true;
+
+  meta = {
+    description = "ZFS Filesystem Linux Kernel module";
+    longDescription = ''
+      ZFS is a filesystem that combines a logical volume manager with a
+      Copy-On-Write filesystem with data integrity detection and repair,
+      snapshotting, cloning, block devices, deduplication, and more.
+      '';
+    homepage = http://zfsonlinux.org/;
+    license = stdenv.lib.licenses.cddl;
+    platforms = stdenv.lib.platforms.linux;
+    maintainers = with stdenv.lib.maintainers; [ wizeman ];
+  };
+}
diff --git a/pkgs/os-specific/windows/cygwin-setup/default.nix b/pkgs/os-specific/windows/cygwin-setup/default.nix
new file mode 100644
index 00000000000..d0995ffc662
--- /dev/null
+++ b/pkgs/os-specific/windows/cygwin-setup/default.nix
@@ -0,0 +1,46 @@
+{ stdenv, fetchcvs, autoconf, automake, libtool, flex, bison, pkgconfig
+, zlib, bzip2, lzma, libgcrypt_1_6
+}:
+
+with stdenv.lib;
+
+stdenv.mkDerivation rec {
+  name = "cygwin-setup-${version}";
+  version = "20131101";
+
+  src = fetchcvs {
+    cvsRoot = ":pserver:anoncvs@cygwin.com:/cvs/cygwin-apps";
+    module = "setup";
+    date = version;
+    sha256 = "024wxaaxkf7p1i78bh5xrsqmfz7ss2amigbfl2r5w9h87zqn9aq3";
+  };
+
+  nativeBuildInputs = [ autoconf automake libtool flex bison pkgconfig ];
+
+  buildInputs = let
+    mkStatic = flip overrideDerivation (o: {
+      dontDisableStatic = true;
+      configureFlags = toList (o.configureFlags or []) ++ [ "--enable-static" ];
+      buildInputs = map mkStatic (o.buildInputs or []);
+      propagatedBuildInputs = map mkStatic (o.propagatedBuildInputs or []);
+    });
+  in map mkStatic [ zlib bzip2 lzma libgcrypt_1_6 ];
+
+  configureFlags = "--disable-shared";
+
+  dontDisableStatic = true;
+
+  preConfigure = ''
+    autoreconf -vfi
+  '';
+
+  installPhase = ''
+    install -vD setup.exe "$out/bin/setup.exe"
+  '';
+
+  meta = {
+    homepage = https://sourceware.org/cygwin-apps/setup.html;
+    description = "A tool for installing Cygwin";
+    license = licenses.gpl2Plus;
+  };
+}
diff --git a/pkgs/os-specific/windows/jom/default.nix b/pkgs/os-specific/windows/jom/default.nix
index 8f8477d1864..4b118a5a7cd 100644
--- a/pkgs/os-specific/windows/jom/default.nix
+++ b/pkgs/os-specific/windows/jom/default.nix
@@ -31,6 +31,6 @@ stdenv.mkDerivation {
   meta = {
     homepage = http://qt-project.org/wiki/jom;
     description = "Clone of nmake supporting multiple independent commands in parallel";
-    license = "GPLv2+"; # Explicitly, GPLv2 or GPLv3, but not later.
+    license = stdenv.lib.licenses.gpl2Plus; # Explicitly, GPLv2 or GPLv3, but not later.
   };
 }
diff --git a/pkgs/os-specific/windows/mingw-w64/default.nix b/pkgs/os-specific/windows/mingw-w64/default.nix
index c358565c455..bf15b208e1a 100644
--- a/pkgs/os-specific/windows/mingw-w64/default.nix
+++ b/pkgs/os-specific/windows/mingw-w64/default.nix
@@ -1,30 +1,30 @@
-{stdenv, fetchurl, binutilsCross ? null, gccCross ? null, onlyHeaders ? false}:
+{ stdenv, fetchurl, binutilsCross ? null, gccCross ? null
+, onlyHeaders ? false
+, onlyPthreads ? false
+}:
 
 let
-  name = "mingw-w64-2.0.3";
+  name = "mingw-w64-3.1.0";
 in
 stdenv.mkDerivation (rec {
   inherit name;
 
   src = fetchurl {
-    url = "mirror://sourceforge/mingw-w64/mingw-w64-v2.0.3.tar.gz";
-    sha256 = "043jk6z90f9pxs9kfn6ckh2vlnbgcv6yfbp5ybahrj3z58dcijp5";
+    url = "mirror://sourceforge/mingw-w64/mingw-w64-v3.1.0.tar.bz2";
+    sha256 = "1lhpw381gc59w8b1r9zzdwa9cdi2wx6qx7s6rvajapmbw7ksgrzc";
   };
-
-  # I don't know what's that $host directory about, I put the
-  # files inside include as usual.
-  postInstall = ''
-    rmdir $out/include
-    mv $out/x86_64-w64-mingw32/* $out
-    rm -R $out/x86_64-w64-mingw32
-  '';
 } //
 (if onlyHeaders then {
   name = name + "-headers";
-  preConfingure = ''
+  preConfigure = ''
     cd mingw-w64-headers
   '';
-  configureFlags = "--without-crt --host=x86_64-w64-mingw32";
+  configureFlags = "--without-crt";
+} else if onlyPthreads then {
+  name = name + "-pthreads";
+  preConfigure = ''
+    cd mingw-w64-libraries/winpthreads
+  '';
 } else {
   buildInputs = [ gccCross binutilsCross ];
 
diff --git a/pkgs/os-specific/windows/pthread-w32/default.nix b/pkgs/os-specific/windows/pthread-w32/default.nix
index cd417eb9ad0..dde4f5d7371 100644
--- a/pkgs/os-specific/windows/pthread-w32/default.nix
+++ b/pkgs/os-specific/windows/pthread-w32/default.nix
@@ -56,6 +56,6 @@ stdenv.mkDerivation {
 
     homepage = http://sourceware.org/pthreads-win32/;
 
-    license = "LGPLv2.1+";
+    license = stdenv.lib.licenses.lgpl21Plus;
   };
 }