sctp: Fix list corruption resulting from freeing an association on a list
Subsystems (81)
PATCH 139/180 dccp: check ccid before dereferencing
In reply to a message not in the archive2.6.32-longterm review patch. If anyone has any objections, please let me know.
------------------
From: Mathias Krause <[email protected]>
commit 276bdb82dedb290511467a5a4fdbe9f0b52dce6f upstream.
ccid_hc_rx_getsockopt() and ccid_hc_tx_getsockopt() might be called with a NULL ccid pointer leading to a NULL pointer dereference. This could lead to a privilege escalation if the attacker is able to map page 0 and prepare it with a fake ccid_ops pointer.
--- net/dccp/ccid.h | 4 ++-- 1 files changed, 2 insertions(+), 2 deletions(-)
net/dccp/ccid.h +2 -2
@@ -214,7 +214,7 @@ static inline int ccid_hc_rx_getsockopt(struct ccid *ccid, struct sock *sk, u32 __user *optval, int __user *optlen) {int rc = -ENOPROTOOPT ; -if (ccid->ccid_ops->ccid_hc_rx_getsockopt !=NULL ) +if (ccid !=NULL && ccid->ccid_ops->ccid_hc_rx_getsockopt !=NULL ) rc = ccid->ccid_ops->ccid_hc_rx_getsockopt (sk, optname, len, optval, optlen);return rc;
@@ -225,7 +225,7 @@ static inline int ccid_hc_tx_getsockopt(struct ccid *ccid, struct sock *sk, u32 __user *optval, int __user *optlen) {int rc = -ENOPROTOOPT ; -if (ccid->ccid_ops->ccid_hc_tx_getsockopt !=NULL ) +if (ccid !=NULL && ccid->ccid_ops->ccid_hc_tx_getsockopt !=NULL ) rc = ccid->ccid_ops->ccid_hc_tx_getsockopt (sk, optname, len, optval, optlen);return rc;
Signature · 1 line
1.7.2.1.45.g54fbc
PATCH 140/180 ia64: Add accept4() syscall
In reply to a message not in the archive2.6.32-longterm review patch. If anyone has any objections, please let me know.
------------------
From: =?latin1?q?=C3=89meric=20Maschino?= <[email protected]>
commit 65cc21b4523e94d5640542a818748cd3be8cd6b4 upstream.
While debugging udev > 170 failure on Debian Wheezy
(http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=648325), it appears that the issue was in fact due to missing accept4() in ia64.
This patch simply adds accept4() to ia64.
--- arch/ia64/include/asm/unistd.h | 3 ++- arch/ia64/kernel/entry.S | 13 +++++++++++++ 2 files changed, 15 insertions(+), 1 deletions(-)
arch/ia64/include/asm/unistd.h +2 -1
@@ -311,11 +311,12 @@#define __NR_preadv 1319#define __NR_pwritev 1320#define __NR_rt_tgsigqueueinfo 1321 +#define __NR_accept4 1334#ifdef __KERNEL__ -#define NR_syscalls 298/* length of syscall table */ +#define NR_syscalls 311/* length of syscall table */ /* * The following defines stop scripts/checksyscalls.sh from complaining about
arch/ia64/kernel/entry.S +13 -0
@@ -1806,6 +1806,19 @@ sys_call_table: data8 sys_preadv data8 sys_pwritev // 1320 data8 sys_rt_tgsigqueueinfo + data8 sys_ni_syscall + data8 sys_ni_syscall + data8 sys_ni_syscall + data8 sys_ni_syscall // 1325 + data8 sys_ni_syscall + data8 sys_ni_syscall + data8 sys_ni_syscall + data8 sys_ni_syscall + data8 sys_ni_syscall // 1330 + data8 sys_ni_syscall + data8 sys_ni_syscall + data8 sys_ni_syscall + data8 sys_accept4 .org sys_call_table + 8*NR_syscalls // guard against failures to increase NR_syscalls #endif /* __IA64_ASM_PARAVIRTUALIZED_NATIVE */
Signature · 1 line
1.7.2.1.45.g54fbc
PATCH 141/180 tcp: do_tcp_sendpages() must try to push data out on oom conditions
In reply to a message not in the archive2.6.32-longterm review patch. If anyone has any objections, please let me know.
------------------
From: Willy Tarreau <[email protected]>
commit bad115cfe5b509043b684d3a007ab54b80090aa1 upstream.
Since recent changes on TCP splicing (starting with commits 2f533844 "tcp: allow splice() to build full TSO packets" and 35f9c09f "tcp:tcp_sendpages() should call tcp_push() once"), I started seeing massive stalls when forwarding traffic between two sockets using splice() when pipe buffers were larger than socket buffers.
Latest changes (net: netdev_alloc_skb() use build_skb()) made the problem even more apparent.
The reason seems to be that if do_tcp_sendpages() fails on out of memory condition without being able to send at least one byte, tcp_push() is not called and the buffers cannot be flushed.
After applying the attached patch, I cannot reproduce the stalls at all and the data rate it perfectly stable and steady under any condition which previously caused the problem to be permanent.
The issue seems to have been there since before the kernel migrated to git, which makes me think that the stalls I occasionally experienced with tux during stress-tests years ago were probably related to the same issue.
This issue was first encountered on 3.0.31 and 3.2.17, so please backport to -stable.
--- net/ipv4/tcp.c | 3 +-- 1 files changed, 1 insertions(+), 2 deletions(-)
net/ipv4/tcp.c +1 -2
@@ -838,8 +838,7 @@ new_segment: wait_for_sndbuf:set_bit (SOCK_NOSPACE , &sk->sk_socket->flags); wait_for_memory: -if (copied) -tcp_push (sk, flags & ~MSG_MORE , mss_now,TCP_NAGLE_PUSH ); +tcp_push (sk, flags & ~MSG_MORE , mss_now,TCP_NAGLE_PUSH );if ((err =sk_stream_wait_memory (sk, &timeo)) !=0 ) goto do_error;
Signature · 1 line
1.7.2.1.45.g54fbc
PATCH 142/180 tcp: drop SYN+FIN messages
In reply to a message not in the archive2.6.32-longterm review patch. If anyone has any objections, please let me know.
------------------
From: Eric Dumazet <[email protected]>
commit fdf5af0daf8019cec2396cdef8fb042d80fe71fa upstream.
Denys Fedoryshchenko reported that SYN+FIN attacks were bringing his linux machines to their limits.
Dont call conn_request() if the TCP flags includes SYN flag
--- net/ipv4/tcp_input.c | 2 ++ 1 files changed, 2 insertions(+), 0 deletions(-)
net/ipv4/tcp_input.c +2 -0
@@ -5634,6 +5634,8 @@ int tcp_rcv_state_process(struct sock *sk, struct sk_buff *skb, goto discard;if (th->syn) { +if (th->fin) + goto discard;if (icsk->icsk_af_ops->conn_request (sk, skb) <0 )return 1 ;
Signature · 1 line
1.7.2.1.45.g54fbc
PATCH 143/180 xen: correctly check for pending events when restoring irq flags
In reply to a message not in the archive2.6.32-longterm review patch. If anyone has any objections, please let me know.
------------------
From: David Vrabel <[email protected]>
commit 7eb7ce4d2e8991aff4ecb71a81949a907ca755ac upstream.
In xen_restore_fl_direct(), xen_force_evtchn_callback() was being called even if no events were pending. This resulted in (depending on workload) about a 100 times as many xen_version hypercalls as necessary.
Fix this by correcting the sense of the conditional jump.
This seems to give a significant performance benefit for some workloads.
There is some subtle tricksy "..since the check here is trying to check both pending and masked in a single cmpw, but I think this is correct. It will call check_events now only when the combined mask+pending word is 0x0001 (aka unmasked, pending)." (Ian)
--- arch/x86/xen/xen-asm.S | 2 +- 1 files changed, 1 insertions(+), 1 deletions(-)
arch/x86/xen/xen-asm.S +1 -1
@@ -96,7 +96,7 @@ ENTRY(xen_restore_fl_direct) /* check for unmasked and pending */ cmpw $0x0001, PER_CPU_VAR(xen_vcpu_info) + XEN_vcpu_info_pending - jz 1f + jnz 1f 2: call check_events 1: ENDPATCH(xen_restore_fl_direct)
Signature · 1 line
1.7.2.1.45.g54fbc
PATCH 144/180 x86, amd, xen: Avoid NULL pointer paravirt references
In reply to a message not in the archive2.6.32-longterm review patch. If anyone has any objections, please let me know.
------------------
From: Konrad Rzeszutek Wilk <[email protected]>
commit 1ab46fd319bcf1fcd9fb6311727d532b580e4eba upstream.
Stub out MSR methods that aren't actually needed. This fixes a crash as Xen Dom0 on AMD Trinity systems. A bigger patch should be added to remove the paravirt machinery completely for the methods which apparently have no users!
--- arch/x86/xen/enlighten.c | 3 +++ 1 files changed, 3 insertions(+), 0 deletions(-)
arch/x86/xen/enlighten.c +3 -0
@@ -945,7 +945,10 @@ static const struct pv_cpu_ops xen_cpu_ops __initdata = { .wbinvd = native_wbinvd, .read_msr = native_read_msr_safe, + .rdmsr_regs = native_rdmsr_safe_regs, .write_msr = xen_write_msr_safe, + .wrmsr_regs = native_wrmsr_safe_regs, + .read_tsc = native_read_tsc, .read_pmc = native_read_pmc,
Signature · 1 line
1.7.2.1.45.g54fbc
PATCH 145/180 x86, tls: Off by one limit check
In reply to a message not in the archive2.6.32-longterm review patch. If anyone has any objections, please let me know.
------------------
From: Dan Carpenter <[email protected]>
commit 8f0750f19789cf352d7e24a6cc50f2ab1b4f1372 upstream.
These are used as offsets into an array of GDT_ENTRY_TLS_ENTRIES members so GDT_ENTRY_TLS_ENTRIES is one past the end of the array.
--- arch/x86/kernel/tls.c | 4 ++-- 1 files changed, 2 insertions(+), 2 deletions(-)
arch/x86/kernel/tls.c +2 -2
@@ -163,7 +163,7 @@ int regset_tls_get(struct task_struct *target, const struct user_regset *regset, {const struct desc_struct *tls; -if (pos >GDT_ENTRY_TLS_ENTRIES *sizeof (struct user_desc ) || +if (pos >=GDT_ENTRY_TLS_ENTRIES *sizeof (struct user_desc ) || (pos %sizeof (struct user_desc )) !=0 || (count %sizeof (struct user_desc )) !=0 )return -EINVAL ;
@@ -198,7 +198,7 @@ int regset_tls_set(struct task_struct *target, const struct user_regset *regset,struct user_desc infobuf[GDT_ENTRY_TLS_ENTRIES ];const struct user_desc *info; -if (pos >GDT_ENTRY_TLS_ENTRIES *sizeof (struct user_desc ) || +if (pos >=GDT_ENTRY_TLS_ENTRIES *sizeof (struct user_desc ) || (pos %sizeof (struct user_desc )) !=0 || (count %sizeof (struct user_desc )) !=0 )return -EINVAL ;
Signature · 1 line
1.7.2.1.45.g54fbc
PATCH 146/180 sparc64: Eliminate obsolete __handle_softirq() function
In reply to a message not in the archive2.6.32-longterm review patch. If anyone has any objections, please let me know.
------------------
From: Paul E. McKenney <[email protected]>
commit 3d3eeb2ef26112a200785e5fca58ec58dd33bf1e upstream.
The invocation of softirq is now handled by irq_exit(), so there is no need for sparc64 to invoke it on the trap-return path. In fact, doing so is a bug because if the trap occurred in the idle loop, this invocation can result in lockdep-RCU failures. The problem is that RCU ignores idle CPUs, and the sparc64 trap-return path to the softirq handlers fails to tell RCU that the CPU must be considered non-idle while those handlers are executing. This means that RCU is ignoring any RCU read-side critical sections in those handlers, which in turn means that RCU-protected data can be yanked out from under those read-side critical sections.
The shiny new lockdep-RCU ability to detect RCU read-side critical sections that RCU is ignoring located this problem.
The fix is straightforward: Make sparc64 stop manually invoking the softirq handlers.
--- arch/sparc/kernel/rtrap_64.S | 7 ------- 1 files changed, 0 insertions(+), 7 deletions(-)
arch/sparc/kernel/rtrap_64.S +0 -7
@@ -20,11 +20,6 @@ .text .align 32 -__handle_softirq: - call do_softirq - nop - ba,a,pt %xcc, __handle_softirq_continue - nop __handle_preemption: call schedule wrpr %g0, RTRAP_PSTATE, %pstate
@@ -159,9 +154,7 @@ rtrap: cmp %l1, 0 /* mm/ultra.S:xcall_report_regs KNOWS about this load. */ - bne,pn %icc, __handle_softirq ldx [%sp + PTREGS_OFF + PT_V9_TSTATE], %l1 -__handle_softirq_continue: rtrap_xcall: sethi %hi(0xf << 20), %l4 and %l1, %l4, %l4
Signature · 1 line
1.7.2.1.45.g54fbc
PATCH 147/180 udf: Fortify loading of sparing table
In reply to a message not in the archive2.6.32-longterm review patch. If anyone has any objections, please let me know.
------------------
From: Jan Kara <[email protected]>
commit 1df2ae31c724e57be9d7ac00d78db8a5dabdd050 upstream.
Add sanity checks when loading sparing table from disk to avoid accessing unallocated memory or writing to it.
--- fs/udf/super.c | 86 ++++++++++++++++++++++++++++++++++--------------------- 1 files changed, 53 insertions(+), 33 deletions(-)
fs/udf/super.c +53 -33
@@ -57,6 +57,7 @@#include <linux/seq_file.h> #include <linux/bitmap.h> #include <linux/crc-itu-t.h> +#include <linux/log2.h> #include <asm/byteorder.h> #include "udf_sb.h"
@@ -1239,11 +1240,59 @@ out_bh:return ret; } +static int udf_load_sparable_map (struct super_block *sb, +struct udf_part_map *map, +struct sparablePartitionMap *spm) +{ +uint32_t loc; +uint16_t ident; +struct sparingTable *st; +struct udf_sparing_data *sdata = &map->s_type_specific.s_sparing; +int i; +struct buffer_head *bh; + + map->s_partition_type =UDF_SPARABLE_MAP15 ; + sdata->s_packet_len =le16_to_cpu (spm->packetLength); +if (!is_power_of_2 (sdata->s_packet_len)) { +udf_error (sb, __func__,"error loading logical volume descriptor: " +"Invalid packet length %u\n" , + (unsigned )sdata->s_packet_len); +return -EIO ; + } +if (spm->numSparingTables >4 ) { +udf_error (sb, __func__,"error loading logical volume descriptor: " +"Too many sparing tables (%d)\n" , + (int )spm->numSparingTables); +return -EIO ; + } + +for (i =0 ; i < spm->numSparingTables; i++) { + loc =le32_to_cpu (spm->locSparingTable[i]); + bh =udf_read_tagged (sb, loc, loc, &ident); +if (!bh) +continue ; + + st = (struct sparingTable *)bh->b_data; +if (ident !=0 || +strncmp (st->sparingIdent.ident,UDF_ID_SPARING , +strlen (UDF_ID_SPARING )) || +sizeof (*st) +le16_to_cpu (st->reallocationTableLen) > + sb->s_blocksize) { +brelse (bh); +continue ; + } + + sdata->s_spar_map[i] = bh; + } + map->s_partition_func = udf_get_pblock_spar15; +return 0 ; +} +static int udf_load_logicalvol (struct super_block *sb,sector_t block,struct kernel_lb_addr *fileset) {struct logicalVolDesc *lvd; -int i, j, offset; +int i, offset;uint8_t type;struct udf_sb_info *sbi =UDF_SB (sb);struct genericPartitionMap *gpm;
@@ -1308,38 +1357,9 @@ static int udf_load_logicalvol(struct super_block *sb, sector_t block, }else if (!strncmp (upm2->partIdent.ident,UDF_ID_SPARABLE ,strlen (UDF_ID_SPARABLE ))) { -uint32_t loc; -struct sparingTable *st; -struct sparablePartitionMap *spm = - (struct sparablePartitionMap *)gpm; - - map->s_partition_type =UDF_SPARABLE_MAP15 ; - map->s_type_specific.s_sparing.s_packet_len = -le16_to_cpu (spm->packetLength); -for (j =0 ; j < spm->numSparingTables; j++) { -struct buffer_head *bh2; - - loc =le32_to_cpu ( - spm->locSparingTable[j]); - bh2 =udf_read_tagged (sb, loc, loc, - &ident); - map->s_type_specific.s_sparing. - s_spar_map[j] = bh2; - -if (bh2 ==NULL ) -continue ; - - st = (struct sparingTable *)bh2->b_data; -if (ident !=0 ||strncmp ( - st->sparingIdent.ident, -UDF_ID_SPARING , -strlen (UDF_ID_SPARING ))) { -brelse (bh2); - map->s_type_specific.s_sparing. - s_spar_map[j] =NULL ; - } - } - map->s_partition_func = udf_get_pblock_spar15; +if (udf_load_sparable_map (sb, map, + (struct sparablePartitionMap *)gpm) <0 ) + goto out_bh; }else if (!strncmp (upm2->partIdent.ident,UDF_ID_METADATA ,strlen (UDF_ID_METADATA ))) {
Signature · 1 line
1.7.2.1.45.g54fbc
Re: [ 147/180] udf: Fortify loading of sparing table
Quoted 10 lines · Willy Tarreau
2.6.32-longterm review patch. If anyone has any objections, please let me know.
------------------
From: Jan Kara <[email protected]>
commit
1df2ae31c724e57be9d7ac00d78db8a5dabdd050upstream.Add sanity checks when loading sparing table from disk to avoid accessing unallocated memory or writing to it.
[...]
It looks like commit 68766a2edcd5cd744262a70a2f67a320ac944760 should be added after this.
Ben.
Signature · 3 lines
Ben Hutchings
We get into the habit of living before acquiring the habit of thinking.
- Albert CamusRe: [ 147/180] udf: Fortify loading of sparing table
Quoted 7 lines · Ben Hutchings
Quoted 6 lines · Willy Tarreau
2.6.32-longterm review patch. If anyone has any objections, please let me know.
------------------
From: Jan Kara <[email protected]>
Quoted 8 lines
Quoted 4 lines
commit
1df2ae31c724e57be9d7ac00d78db8a5dabdd050upstream.Add sanity checks when loading sparing table from disk to avoid accessing unallocated memory or writing to it.
[...]
It looks like commit
68766a2edcd5cd744262a70a2f67a320ac944760should be added after this.
Thanks, queued!
Willy
PATCH 148/180 mtd: cafe_nand: fix an & vs | mistake
In reply to a message not in the archive2.6.32-longterm review patch. If anyone has any objections, please let me know.
------------------
From: Dan Carpenter <[email protected]>
commit 48f8b641297df49021093763a3271119a84990a2 upstream.
The intent here was clearly to set result to true if the 0x40000000 flag was set. But instead there was a | vs & typo and we always set result to true.
Artem: check the spec at wiki.laptop.org/images/5/5c/88ALP01_Datasheet_July_2007.pdf and this fix looks correct.
--- drivers/mtd/nand/cafe_nand.c | 2 +- 1 files changed, 1 insertions(+), 1 deletions(-)
drivers/mtd/nand/cafe_nand.c +1 -1
@@ -103,7 +103,7 @@ static const char *part_probes[] = { "cmdlinepart", "RedBoot", NULL };static int cafe_device_ready (struct mtd_info *mtd) {struct cafe_priv *cafe = mtd->priv; -int result = !!(cafe_readl (cafe,NAND_STATUS ) |0x40000000 ); +int result = !!(cafe_readl (cafe,NAND_STATUS ) &0x40000000 );uint32_t irqs =cafe_readl (cafe,NAND_IRQ );cafe_writel (cafe, irqs,NAND_IRQ );
Signature · 1 line
1.7.2.1.45.g54fbc
PATCH 149/180 epoll: introduce POLLFREE to flush ->signalfd_wqh before kfree()
In reply to a message not in the archive2.6.32-longterm review patch. If anyone has any objections, please let me know.
------------------
From: Oleg Nesterov <[email protected]>
commit d80e731ecab420ddcb79ee9d0ac427acbc187b4b upstream.
This patch is intentionally incomplete to simplify the review. It ignores ep_unregister_pollwait() which plays with the same wqh. See the next change.
epoll assumes that the EPOLL_CTL_ADD'ed file controls everything f_op->poll() needs. In particular it assumes that the wait queue can't go away until eventpoll_release(). This is not true in case of signalfd, the task which does EPOLL_CTL_ADD uses its ->sighand which is not connected to the file.
This patch adds the special event, POLLFREE, currently only for epoll. It expects that init_poll_funcptr()'ed hook should do the necessary cleanup. Perhaps it should be defined as EPOLLFREE in eventpoll.
__cleanup_sighand() is changed to do wake_up_poll(POLLFREE) if ->signalfd_wqh is not empty, we add the new signalfd_cleanup() helper.
ep_poll_callback(POLLFREE) simply does list_del_init(task_list). This make this poll entry inconsistent, but we don't care. If you share epoll fd which contains our sigfd with another process you should blame yourself. signalfd is "really special". I simply do not know how we can define the "right" semantics if it used with epoll.
The main problem is, epoll calls signalfd_poll() once to establish the connection with the wait queue, after that signalfd_poll(NULL) returns the different/inconsistent results depending on who does EPOLL_CTL_MOD/signalfd_read/etc. IOW: apart from sigmask, signalfd has nothing to do with the file, it works with the current thread.
In short: this patch is the hack which tries to fix the symptoms. It also assumes that nobody can take tasklist_lock under epoll locks, this seems to be true.
Note:
- we do not have wake_up_all_poll() but wake_up_poll() is fine, poll/epoll doesn't use WQ_FLAG_EXCLUSIVE.
- signalfd_cleanup() uses POLLHUP along with POLLFREE, we need a couple of simple changes in eventpoll.c to make sure it can't be "lost".
--- fs/eventpoll.c | 4 ++++ fs/signalfd.c | 11 +++++++++++ include/asm-generic/poll.h | 2 ++ include/linux/signalfd.h | 5 ++++- kernel/fork.c | 5 ++++- 5 files changed, 25 insertions(+), 2 deletions(-)
fs/eventpoll.c +4 -0
@@ -814,6 +814,10 @@ static int ep_poll_callback(wait_queue_t *wait, unsigned mode, int sync, void *kstruct epitem *epi =ep_item_from_wait (wait);struct eventpoll *ep = epi->ep; +/* the caller holds eppoll_entry->whead->lock */ +if ((unsigned long )key &POLLFREE ) +list_del_init (&wait->task_list); +spin_lock_irqsave (&ep->lock, flags);/*
fs/signalfd.c +11 -0
@@ -29,6 +29,17 @@#include <linux/signalfd.h> #include <linux/syscalls.h> +void signalfd_cleanup (struct sighand_struct *sighand) +{ +wait_queue_head_t *wqh = &sighand->signalfd_wqh; + +if (likely (!waitqueue_active (wqh))) +return ; + +/* wait_queue_t->func(POLLFREE) should do remove_wait_queue() */ +wake_up_poll (wqh,POLLHUP |POLLFREE ); +} +struct signalfd_ctx {sigset_t sigmask; };
include/asm-generic/poll.h +2 -0
@@ -28,6 +28,8 @@#define POLLRDHUP 0x2000#endif +#define POLLFREE 0x4000/* currently only for epoll */ +struct pollfd {int fd;short events;
include/linux/signalfd.h +4 -1
@@ -60,13 +60,16 @@ static inline void signalfd_notify(struct task_struct *tsk, int sig)wake_up (&tsk->sighand->signalfd_wqh); } +extern void signalfd_cleanup (struct sighand_struct *sighand); +#else /* CONFIG_SIGNALFD */ static inline void signalfd_notify (struct task_struct *tsk,int sig) { } +static inline void signalfd_cleanup (struct sighand_struct *sighand) { } +#endif /* CONFIG_SIGNALFD */ #endif /* __KERNEL__ */ #endif /* _LINUX_SIGNALFD_H */ -
kernel/fork.c +4 -1
@@ -64,6 +64,7 @@#include <linux/magic.h> #include <linux/perf_event.h> #include <linux/posix-timers.h> +#include <linux/signalfd.h> #include <asm/pgtable.h> #include <asm/pgalloc.h>
@@ -815,8 +816,10 @@ static int copy_sighand(unsigned long clone_flags, struct task_struct *tsk)void __cleanup_sighand (struct sighand_struct *sighand) { -if (atomic_dec_and_test (&sighand->count)) +if (atomic_dec_and_test (&sighand->count)) { +signalfd_cleanup (sighand);kmem_cache_free (sighand_cachep, sighand); + } }
Signature · 1 line
1.7.2.1.45.g54fbc
PATCH 150/180 epoll: ep_unregister_pollwait() can use the freed pwq->whead
In reply to a message not in the archive2.6.32-longterm review patch. If anyone has any objections, please let me know.
------------------
From: Oleg Nesterov <[email protected]>
commit 971316f0503a5c50633d07b83b6db2f15a3a5b00 upstream.
signalfd_cleanup() ensures that ->signalfd_wqh is not used, but this is not enough. eppoll_entry->whead still points to the memory we are going to free, ep_unregister_pollwait()->remove_wait_queue() is obviously unsafe.
Change ep_poll_callback(POLLFREE) to set eppoll_entry->whead = NULL, change ep_unregister_pollwait() to check pwq->whead != NULL under rcu_read_lock() before remove_wait_queue(). We add the new helper, ep_remove_wait_queue(), for this.
This works because sighand_cachep is SLAB_DESTROY_BY_RCU and because ->signalfd_wqh is initialized in sighand_ctor(), not in copy_sighand. ep_unregister_pollwait()->remove_wait_queue() can play with already freed and potentially reused ->sighand, but this is fine. This memory must have the valid ->signalfd_wqh until rcu_read_unlock().
--- fs/eventpoll.c | 30 +++++++++++++++++++++++++++--- fs/signalfd.c | 6 +++++- 2 files changed, 32 insertions(+), 4 deletions(-)
fs/eventpoll.c +27 -3
@@ -300,6 +300,11 @@ static inline int ep_is_linked(struct list_head *p)return !list_empty (p); } +static inline struct eppoll_entry *ep_pwq_from_wait (wait_queue_t *p) +{ + return container_of(p, struct eppoll_entry, wait); +} +/* Get the "struct epitem" from a wait queue pointer */ static inline struct epitem *ep_item_from_wait (wait_queue_t *p) {
@@ -434,6 +439,18 @@ static void ep_poll_safewake(wait_queue_head_t *wq)put_cpu (); } +static void ep_remove_wait_queue (struct eppoll_entry *pwq) +{ +wait_queue_head_t *whead; + +rcu_read_lock (); +/* If it is cleared by POLLFREE, it should be rcu-safe */ + whead =rcu_dereference (pwq->whead); +if (whead) +remove_wait_queue (whead, &pwq->wait); +rcu_read_unlock (); +} +/* * This function unregisters poll callbacks from the associated file * descriptor. Must be called with "mtx" held (or "epmutex" if called from
@@ -448,7 +465,7 @@ static void ep_unregister_pollwait(struct eventpoll *ep, struct epitem *epi) pwq = list_first_entry(lsthead, struct eppoll_entry, llink);list_del (&pwq->llink); -remove_wait_queue (pwq->whead, &pwq->wait); +ep_remove_wait_queue (pwq);kmem_cache_free (pwq_cache, pwq); } }
@@ -814,9 +831,16 @@ static int ep_poll_callback(wait_queue_t *wait, unsigned mode, int sync, void *kstruct epitem *epi =ep_item_from_wait (wait);struct eventpoll *ep = epi->ep; -/* the caller holds eppoll_entry->whead->lock */ -if ((unsigned long )key &POLLFREE ) +if ((unsigned long )key &POLLFREE ) { +ep_pwq_from_wait (wait)->whead =NULL ; +/* +* whead = NULL above can race with ep_remove_wait_queue() +* which can do another remove_wait_queue() after us, so we +* can't use __remove_wait_queue(). whead->lock is held by +* the caller. +*/ list_del_init (&wait->task_list); + }spin_lock_irqsave (&ep->lock, flags);
fs/signalfd.c +5 -1
@@ -32,7 +32,11 @@void signalfd_cleanup (struct sighand_struct *sighand) {wait_queue_head_t *wqh = &sighand->signalfd_wqh; - +/* +* The lockless check can race with remove_wait_queue() in progress, +* but in this case its caller should run under rcu_read_lock() and +* sighand_cachep is SLAB_DESTROY_BY_RCU, we can safely return. +*/ if (likely (!waitqueue_active (wqh)))return ;
Signature · 1 line
1.7.2.1.45.g54fbc
PATCH 151/180 epoll: limit paths
In reply to a message not in the archive2.6.32-longterm review patch. If anyone has any objections, please let me know.
------------------
From: Jason Baron <[email protected]>
commit 28d82dc1c4edbc352129f97f4ca22624d1fe61de upstream.
The current epoll code can be tickled to run basically indefinitely in both loop detection path check (on ep_insert()), and in the wakeup paths. The programs that tickle this behavior set up deeply linked networks of epoll file descriptors that cause the epoll algorithms to traverse them indefinitely. A couple of these sample programs have been previously posted in this thread: https://lkml.org/lkml/2011/2/25/297.
To fix the loop detection path check algorithms, I simply keep track of the epoll nodes that have been already visited. Thus, the loop detection becomes proportional to the number of epoll file descriptor and links. This dramatically decreases the run-time of the loop check algorithm. In one diabolical case I tried it reduced the run-time from 15 mintues (all in kernel time) to .3 seconds.
Fixing the wakeup paths could be done at wakeup time in a similar manner by keeping track of nodes that have already been visited, but the complexity is harder, since there can be multiple wakeups on different cpus...Thus, I've opted to limit the number of possible wakeup paths when the paths are created.
This is accomplished, by noting that the end file descriptor points that are found during the loop detection pass (from the newly added link), are actually the sources for wakeup events. I keep a list of these file descriptors and limit the number and length of these paths that emanate from these 'source file descriptors'. In the current implemetation I allow 1000 paths of length 1, 500 of length 2, 100 of length 3, 50 of length 4 and 10 of length 5. Note that it is sufficient to check the 'source file descriptors' reachable from the newly added link, since no other 'source file descriptors' will have newly added links. This allows us to check only the wakeup paths that may have gotten too long, and not re-check all possible wakeup paths on the system.
In terms of the path limit selection, I think its first worth noting that the most common case for epoll, is probably the model where you have 1 epoll file descriptor that is monitoring n number of 'source file descriptors'. In this case, each 'source file descriptor' has a 1 path of length 1. Thus, I believe that the limits I'm proposing are quite reasonable and in fact may be too generous. Thus, I'm hoping that the proposed limits will not prevent any workloads that currently work to fail.
In terms of locking, I have extended the use of the 'epmutex' to all epoll_ctl add and remove operations. Currently its only used in a subset of the add paths. I need to hold the epmutex, so that we can correctly traverse a coherent graph, to check the number of paths. I believe that this additional locking is probably ok, since its in the setup/teardown paths, and doesn't affect the running paths, but it certainly is going to add some extra overhead. Also, worth noting is that the epmuex was recently added to the ep_ctl add operations in the initial path loop detection code using the argument that it was not on a critical path.
Another thing to note here, is the length of epoll chains that is allowed. Currently, eventpoll.c defines:
/* Maximum number of nesting allowed inside epoll sets */
This basically means that I am limited to a graph depth of 5 (EP_MAX_NESTS
+ 1). However, this limit is currently only enforced during the loop check detection code, and only when the epoll file descriptors are added in a certain order. Thus, this limit is currently easily bypassed. The newly added check for wakeup paths, stricly limits the wakeup paths to a length of 5, regardless of the order in which ep's are linked together. Thus, a side-effect of the new code is a more consistent enforcement of the graph depth.
Thus far, I've tested this, using the sample programs previously mentioned, which now either return quickly or return -EINVAL. I've also testing using the piptest.c epoll tester, which showed no difference in performance. I've also created a number of different epoll networks and tested that they behave as expectded.
I believe this solves the original diabolical test cases, while still preserving the sane epoll nesting.
--- fs/eventpoll.c | 236 ++++++++++++++++++++++++++++++++++++++++----- include/linux/eventpoll.h | 1 + include/linux/fs.h | 1 + 3 files changed, 212 insertions(+), 26 deletions(-)
fs/eventpoll.c +210 -26
@@ -200,6 +200,12 @@ struct eventpoll {/* The user that created the eventpoll descriptor */ struct user_struct *user; + +struct file *file; + +/* used to optimize loop detection check */ +int visited; +struct list_head visited_list_link; };/* Wait structure used by the poll hooks */
@@ -258,6 +264,15 @@ static struct kmem_cache *epi_cache __read_mostly;/* Slab cache used to allocate "struct eppoll_entry" */ static struct kmem_cache *pwq_cache__read_mostly ; +/* Visited nodes during ep_loop_check(), so we can unset them when we finish */ +static LIST_HEAD (visited_list); + +/* +* List of files with newly added links, where we may need to limit the number +* of emanating paths. Protected by the epmutex. +*/ +static LIST_HEAD (tfile_check_list); +#ifdef CONFIG_SYSCTL #include <linux/sysctl.h>
@@ -277,6 +292,12 @@ ctl_table epoll_table[] = { };#endif /* CONFIG_SYSCTL */ +static const struct file_operations eventpoll_fops; + +static inline int is_file_epoll (struct file *f) +{ +return f->f_op == &eventpoll_fops; +}/* Setup the structure that is used as key for the RB tree */ static inline void ep_set_ffd(struct epoll_filefd *ffd,
@@ -715,12 +736,6 @@ static const struct file_operations eventpoll_fops = { .poll = ep_eventpoll_poll }; -/* Fast test to see if the file is an evenpoll file */ -static inline int is_file_epoll (struct file *f) -{ -return f->f_op == &eventpoll_fops; -} -/* * This is called from eventpoll_release() to unlink files from the eventpoll * interface. We need to have this facility to cleanup correctly files that are
@@ -941,6 +956,99 @@ static void ep_rbtree_insert(struct eventpoll *ep, struct epitem *epi)rb_insert_color (&epi->rbn, &ep->rbr); } + + +#define PATH_ARR_SIZE 5 +/* +* These are the number paths of length 1 to 5, that we are allowing to emanate +* from a single file of interest. For example, we allow 1000 paths of length +* 1, to emanate from each file of interest. This essentially represents the +* potential wakeup paths, which need to be limited in order to avoid massive +* uncontrolled wakeup storms. The common use case should be a single ep which +* is connected to n file sources. In this case each file source has 1 path +* of length 1. Thus, the numbers below should be more than sufficient. These +* path limits are enforced during an EPOLL_CTL_ADD operation, since a modify +* and delete can't add additional paths. Protected by the epmutex. +*/ +static const int path_limits[PATH_ARR_SIZE ] = {1000 ,500 ,100 ,50 ,10 }; +static int path_count[PATH_ARR_SIZE ]; + +static int path_count_inc (int nests) +{ +if (++path_count[nests] > path_limits[nests]) +return -1 ; +return 0 ; +} + +static void path_count_init (void ) +{ +int i; + +for (i =0 ; i <PATH_ARR_SIZE ; i++) + path_count[i] =0 ; +} + +static int reverse_path_check_proc (void *priv,void *cookie,int call_nests) +{ +int error =0 ; +struct file *file = priv; +struct file *child_file; +struct epitem *epi; + +list_for_each_entry (epi, &file->f_ep_links, fllink) { + child_file = epi->ep->file; +if (is_file_epoll (child_file)) { +if (list_empty (&child_file->f_ep_links)) { +if (path_count_inc (call_nests)) { + error =-1 ; +break ; + } + }else { + error =ep_call_nested (&poll_loop_ncalls, +EP_MAX_NESTS , + reverse_path_check_proc, + child_file, child_file, + current); + } +if (error !=0 ) +break ; + }else { +printk (KERN_ERR "reverse_path_check_proc: " +"file is not an ep!\n" ); + } + } +return error; +} + +/** +* reverse_path_check - The tfile_check_list is list of file *, which have +* links that are proposed to be newly added. We need to +* make sure that those added links don't add too many +* paths such that we will spend all our time waking up +* eventpoll objects. +* +* Returns: Returns zero if the proposed links don't create too many paths, +* -1 otherwise. +*/ +static int reverse_path_check (void ) +{ +int length =0 ; +int error =0 ; +struct file *current_file; + +/* let's call this for all tfiles */ +list_for_each_entry (current_file, &tfile_check_list, f_tfile_llink) { + length++; +path_count_init (); + error =ep_call_nested (&poll_loop_ncalls,EP_MAX_NESTS , + reverse_path_check_proc, current_file, + current_file, current); +if (error) +break ; + } +return error; +} +/* * Must be called with "mtx" held. */
@@ -1001,6 +1109,11 @@ static int ep_insert(struct eventpoll *ep, struct epoll_event *event,*/ ep_rbtree_insert (ep, epi); +/* now check if we've created too many backpaths */ + error = -EINVAL ; +if (reverse_path_check ()) + goto error_remove_epi; +/* We have to drop the new item inside our item list to keep track of it */ spin_lock_irqsave (&ep->lock, flags);
@@ -1025,6 +1138,14 @@ static int ep_insert(struct eventpoll *ep, struct epoll_event *event,return 0 ; +error_remove_epi: +spin_lock (&tfile->f_lock); +if (ep_is_linked (&epi->fllink)) +list_del_init (&epi->fllink); +spin_unlock (&tfile->f_lock); + +rb_erase (&epi->rbn, &ep->rbr); + error_unregister:ep_unregister_pollwait (ep, epi);
@@ -1251,18 +1372,36 @@ static int ep_loop_check_proc(void *priv, void *cookie, int call_nests)int error =0 ;struct file *file = priv;struct eventpoll *ep = file->private_data; +struct eventpoll *ep_tovisit;struct rb_node *rbp;struct epitem *epi;mutex_lock_nested (&ep->mtx, call_nests +1 ); + ep->visited =1 ; +list_add (&ep->visited_list_link, &visited_list);for (rbp =rb_first (&ep->rbr); rbp; rbp =rb_next (rbp)) { epi = rb_entry(rbp, struct epitem, rbn);if (unlikely (is_file_epoll (epi->ffd.file))) { + ep_tovisit = epi->ffd.file->private_data; +if (ep_tovisit->visited) +continue ; error =ep_call_nested (&poll_loop_ncalls,EP_MAX_NESTS , - ep_loop_check_proc, epi->ffd.file, - epi->ffd.file->private_data, current); + ep_loop_check_proc, epi->ffd.file, + ep_tovisit, current);if (error !=0 )break ; + }else { +/* +* If we've reached a file that is not associated with +* an ep, then we need to check if the newly added +* links are going to add too many wakeup paths. We do +* this by adding it to the tfile_check_list, if it's +* not already there, and calling reverse_path_check() +* during ep_insert(). +*/ +if (list_empty (&epi->ffd.file->f_tfile_llink)) +list_add (&epi->ffd.file->f_tfile_llink, + &tfile_check_list); } }mutex_unlock (&ep->mtx);
@@ -1283,8 +1422,31 @@ static int ep_loop_check_proc(void *priv, void *cookie, int call_nests)*/ static int ep_loop_check (struct eventpoll *ep,struct file *file) { -return ep_call_nested (&poll_loop_ncalls,EP_MAX_NESTS , +int ret; +struct eventpoll *ep_cur, *ep_next; + + ret =ep_call_nested (&poll_loop_ncalls,EP_MAX_NESTS , ep_loop_check_proc, file, ep, current); +/* clear visited list */ +list_for_each_entry_safe (ep_cur, ep_next, &visited_list, + visited_list_link) { + ep_cur->visited =0 ; +list_del (&ep_cur->visited_list_link); + } +return ret; +} + +static void clear_tfile_check_list (void ) +{ +struct file *file; + +/* first clear the tfile_check_list */ +while (!list_empty (&tfile_check_list)) { + file = list_first_entry(&tfile_check_list, struct file, + f_tfile_llink); +list_del_init (&file->f_tfile_llink); + } +INIT_LIST_HEAD (&tfile_check_list); }/*
@@ -1292,8 +1454,9 @@ static int ep_loop_check(struct eventpoll *ep, struct file *file)*/ SYSCALL_DEFINE1(epoll_create1, int, flags) { -int error; +int error, fd;struct eventpoll *ep =NULL ; +struct file *file;/* Check the EPOLL_* constant for consistency. */ BUILD_BUG_ON (EPOLL_CLOEXEC !=O_CLOEXEC );
@@ -1310,11 +1473,25 @@ SYSCALL_DEFINE1(epoll_create1, int, flags)* Creates all the items needed to setup an eventpoll file. That is, * a file structure and a free file descriptor. */ - error =anon_inode_getfd ("[eventpoll]" , &eventpoll_fops, ep, - flags &O_CLOEXEC ); -if (error <0 ) -ep_free (ep); - + fd =get_unused_fd_flags (O_RDWR | (flags &O_CLOEXEC )); +if (fd <0 ) { + error = fd; + goto out_free_ep; + } + file =anon_inode_getfile ("[eventpoll]" , &eventpoll_fops, ep, +O_RDWR | (flags &O_CLOEXEC )); +if (IS_ERR (file)) { + error =PTR_ERR (file); + goto out_free_fd; + } +fd_install (fd, file); + ep->file = file; +return fd; + +out_free_fd: +put_unused_fd (fd); +out_free_ep: +ep_free (ep);return error; }
@@ -1380,21 +1557,27 @@ SYSCALL_DEFINE4(epoll_ctl, int, epfd, int, op, int, fd,/* * When we insert an epoll file descriptor, inside another epoll file * descriptor, there is the change of creating closed loops, which are -* better be handled here, than in more critical paths. +* better be handled here, than in more critical paths. While we are +* checking for loops we also determine the list of files reachable +* and hang them on the tfile_check_list, so we can check that we +* haven't created too many possible wakeup paths. * -* We hold epmutex across the loop check and the insert in this case, in -* order to prevent two separate inserts from racing and each doing the -* insert "at the same time" such that ep_loop_check passes on both -* before either one does the insert, thereby creating a cycle. +* We need to hold the epmutex across both ep_insert and ep_remove +* b/c we want to make sure we are looking at a coherent view of +* epoll network. */ -if (unlikely (is_file_epoll (tfile) && op ==EPOLL_CTL_ADD )) { +if (op ==EPOLL_CTL_ADD || op ==EPOLL_CTL_DEL ) {mutex_lock (&epmutex); did_lock_epmutex =1 ; - error = -ELOOP ; -if (ep_loop_check (ep, tfile) !=0 ) - goto error_tgt_fput; } - +if (op ==EPOLL_CTL_ADD ) { +if (is_file_epoll (tfile)) { + error = -ELOOP ; +if (ep_loop_check (ep, tfile) !=0 ) + goto error_tgt_fput; + }else +list_add (&tfile->f_tfile_llink, &tfile_check_list); + }mutex_lock_nested (&ep->mtx,0 );
@@ -1413,6 +1596,7 @@ SYSCALL_DEFINE4(epoll_ctl, int, epfd, int, op, int, fd, error =ep_insert (ep, &epds, tfile, fd); }else error = -EEXIST ; +clear_tfile_check_list ();break ;case EPOLL_CTL_DEL :if (epi)
@@ -1431,7 +1615,7 @@ SYSCALL_DEFINE4(epoll_ctl, int, epfd, int, op, int, fd,mutex_unlock (&ep->mtx); error_tgt_fput: -if (unlikely (did_lock_epmutex)) +if (did_lock_epmutex)mutex_unlock (&epmutex);fput (tfile);
include/linux/eventpoll.h +1 -0
@@ -61,6 +61,7 @@ struct file;static inline void eventpoll_init_file (struct file *file) {INIT_LIST_HEAD (&file->f_ep_links); +INIT_LIST_HEAD (&file->f_tfile_llink); }
include/linux/fs.h +1 -0
@@ -941,6 +941,7 @@ struct file {#ifdef CONFIG_EPOLL /* Used by fs/eventpoll.c to link all the hooks to this file */ struct list_head f_ep_links; +struct list_head f_tfile_llink;#endif /* #ifdef CONFIG_EPOLL */ struct address_space *f_mapping;#ifdef CONFIG_DEBUG_WRITECOUNT
Signature · 1 line
1.7.2.1.45.g54fbc
PATCH 152/180 Dont limit non-nested epoll paths
In reply to a message not in the archive2.6.32-longterm review patch. If anyone has any objections, please let me know.
------------------
From: Jason Baron <[email protected]>
commit 93dc6107a76daed81c07f50215fa6ae77691634f upstream.
Commit 28d82dc1c4ed ("epoll: limit paths") that I did to limit the number of possible wakeup paths in epoll is causing a few applications to longer work (dovecot for one).
The original patch is really about limiting the amount of epoll nesting (since epoll fds can be attached to other fds). Thus, we probably can allow an unlimited number of paths of depth 1. My current patch limits it at 1000. And enforce the limits on paths that have a greater depth.
This is captured in: https://bugzilla.redhat.com/show_bug.cgi?id=681578
--- fs/eventpoll.c | 4 ++++ 1 files changed, 4 insertions(+), 0 deletions(-)
fs/eventpoll.c +4 -0
@@ -975,6 +975,10 @@ static int path_count[PATH_ARR_SIZE];static int path_count_inc (int nests) { +/* Allow an arbitrary number of depth 1 paths */ +if (nests ==0 ) +return 0 ; +if (++path_count[nests] > path_limits[nests])return -1 ;return 0 ;
Signature · 1 line
1.7.2.1.45.g54fbc
PATCH 153/180 epoll: clear the tfile_check_list on -ELOOP
In reply to a message not in the archive2.6.32-longterm review patch. If anyone has any objections, please let me know.
------------------
From: Jason Baron <[email protected]>
commit 13d518074a952d33d47c428419693f63389547e9 upstream.
An epoll_ctl(,EPOLL_CTL_ADD,,) operation can return '-ELOOP' to prevent circular epoll dependencies from being created. However, in that case we do not properly clear the 'tfile_check_list'. Thus, add a call to clear_tfile_check_list() for the -ELOOP case.
--- fs/eventpoll.c | 4 +++- 1 files changed, 3 insertions(+), 1 deletions(-)
fs/eventpoll.c +3 -1
@@ -1577,8 +1577,10 @@ SYSCALL_DEFINE4(epoll_ctl, int, epfd, int, op, int, fd,if (op ==EPOLL_CTL_ADD ) {if (is_file_epoll (tfile)) { error = -ELOOP ; -if (ep_loop_check (ep, tfile) !=0 ) +if (ep_loop_check (ep, tfile) !=0 ) { +clear_tfile_check_list (); goto error_tgt_fput; + } }else list_add (&tfile->f_tfile_llink, &tfile_check_list); }
Signature · 1 line
1.7.2.1.45.g54fbc
PATCH 154/180 random: Reorder struct entropy_store to remove padding on 64bits
In reply to a message not in the archive2.6.32-longterm review patch. If anyone has any objections, please let me know.
------------------
From: Richard Kennedy <[email protected]>
commit 4015d9a865e3bcc42d88bedc8ce1551000bab664 upstream.
Re-order structure entropy_store to remove 8 bytes of padding on 64 bit builds, so shrinking this structure from 72 to 64 bytes and allowing it to fit into one cache line.
--- drivers/char/random.c | 2 +- 1 files changed, 1 insertions(+), 1 deletions(-)
drivers/char/random.c +1 -1
@@ -406,8 +406,8 @@ struct entropy_store {struct poolinfo *poolinfo;__u32 *pool;const char *name; -int limit;struct entropy_store *pull; +int limit;/* read-write data: */ spinlock_t lock;
Signature · 1 line
1.7.2.1.45.g54fbc
PATCH 155/180 random: update interface comments to reflect reality
In reply to a message not in the archive2.6.32-longterm review patch. If anyone has any objections, please let me know.
------------------
From: Jarod Wilson <[email protected]>
commit 442a4fffffa26fc3080350b4d50172f7589c3ac2 upstream.
At present, the comment header in random.c makes no mention of add_disk_randomness, and instead, suggests that disk activity adds to the random pool by way of add_interrupt_randomness, which appears to not have been the case since sometime prior to the existence of git, and even prior to bitkeeper. Didn't look any further back. At least, as far as I can tell, there are no storage drivers setting IRQF_SAMPLE_RANDOM, which is a requirement for add_interrupt_randomness to trigger, so the only way for a disk to contribute entropy is by way of add_disk_randomness. Update comments accordingly, complete with special mention about solid state drives being a crappy source of entropy (see e2e1a148bc for reference).
--- drivers/char/random.c | 13 ++++++++++--- 1 files changed, 10 insertions(+), 3 deletions(-)
drivers/char/random.c +10 -3
@@ -128,6 +128,7 @@* void add_input_randomness(unsigned int type, unsigned int code, * unsigned int value); * void add_interrupt_randomness(int irq); +* void add_disk_randomness(struct gendisk *disk); * * add_input_randomness() uses the input layer interrupt timing, as well as * the event type information from the hardware.
@@ -136,9 +137,15 @@* inputs to the entropy pool. Note that not all interrupts are good * sources of randomness! For example, the timer interrupts is not a * good choice, because the periodicity of the interrupts is too -* regular, and hence predictable to an attacker. Disk interrupts are -* a better measure, since the timing of the disk interrupts are more -* unpredictable. +* regular, and hence predictable to an attacker. Network Interface +* Controller interrupts are a better measure, since the timing of the +* NIC interrupts are more unpredictable. +* +* add_disk_randomness() uses what amounts to the seek time of block +* layer request events, on a per-disk_devt basis, as input to the +* entropy pool. Note that high-speed solid state drives with very low +* seek times do not make for good sources of entropy, as their seek +* times are usually fairly consistent. * * All of these routines try to estimate how many bits of randomness a * particular randomness source. They do this by keeping track of the
Signature · 1 line
1.7.2.1.45.g54fbc
PATCH 156/180 random: simplify fips mode
In reply to a message not in the archive2.6.32-longterm review patch. If anyone has any objections, please let me know.
------------------
From: Matt Mackall <[email protected]>
commit e954bc91bdd4bb08b8325478c5004b24a23a3522 upstream.
Rather than dynamically allocate 10 bytes, move it to static allocation. This saves space and avoids the need for error checking.
--- drivers/char/random.c | 10 +++------- 1 files changed, 3 insertions(+), 7 deletions(-)
drivers/char/random.c +3 -7
@@ -264,6 +264,7 @@#define INPUT_POOL_WORDS 128#define OUTPUT_POOL_WORDS 32#define SEC_XFER_SIZE 512 +#define EXTRACT_SIZE 10/* * The minimum number of bits of entropy before we wake up a read on
@@ -421,7 +422,7 @@ struct entropy_store {unsigned add_ptr;int entropy_count;int input_rotate; -__u8 *last_data; +__u8 last_data[EXTRACT_SIZE ]; };static __u32 input_pool_data[INPUT_POOL_WORDS ];
@@ -721,8 +722,6 @@ void add_disk_randomness(struct gendisk *disk) }#endif -#define EXTRACT_SIZE 10 -/********************************************************************* * * Entropy extraction routines
@@ -869,7 +868,7 @@ static ssize_t extract_entropy(struct entropy_store *r, void *buf,while (nbytes) {extract_buf (r, tmp); -if (r->last_data) { +if (fips_enabled) {spin_lock_irqsave (&r->lock, flags);if (!memcmp (tmp, r->last_data,EXTRACT_SIZE ))panic ("Hardware RNG duplicated output!\n" );
@@ -958,9 +957,6 @@ static void init_std_data(struct entropy_store *r) now =ktime_get_real ();mix_pool_bytes (r, &now,sizeof (now));mix_pool_bytes (r,utsname (),sizeof (*(utsname ()))); -/* Enable continuous test in fips mode */ -if (fips_enabled) - r->last_data =kmalloc (EXTRACT_SIZE ,GFP_KERNEL ); }static int rand_initialize (void )
Signature · 1 line
1.7.2.1.45.g54fbc
PATCH 157/180 x86, cpu: Add CPU flags for F16C and RDRND
In reply to a message not in the archive2.6.32-longterm review patch. If anyone has any objections, please let me know.
------------------
From: H. Peter Anvin <[email protected]>
commit 24da9c26f3050aee9314ec09930a24c80fe76352 upstream.
Add support for the newly documented F16C (16-bit floating point conversions) and RDRND (RDRAND instruction) CPU feature flags.
--- arch/x86/include/asm/cpufeature.h | 2 ++ 1 files changed, 2 insertions(+), 0 deletions(-)
arch/x86/include/asm/cpufeature.h +2 -0
@@ -124,6 +124,8 @@#define X86_FEATURE_XSAVE (4*32+26)/* XSAVE/XRSTOR/XSETBV/XGETBV */ #define X86_FEATURE_OSXSAVE (4*32+27)/* "" XSAVE enabled in the OS */ #define X86_FEATURE_AVX (4*32+28)/* Advanced Vector Extensions */ +#define X86_FEATURE_F16C (4*32+29)/* 16-bit fp conversions */ +#define X86_FEATURE_RDRND (4*32+30)/* The RDRAND instruction */ #define X86_FEATURE_HYPERVISOR (4*32+31)/* Running on a hypervisor */ /* VIA/Cyrix/Centaur-defined CPU features, CPUID level 0xC0000001, word 5 */
Signature · 1 line
1.7.2.1.45.g54fbc
PATCH 158/180 x86, cpufeature: Update CPU feature RDRND to RDRAND
In reply to a message not in the archive2.6.32-longterm review patch. If anyone has any objections, please let me know.
------------------
From: Kees Cook <[email protected]>
commit 7ccafc5f75c87853f3c49845d5a884f2376e03ce upstream.
The Intel manual changed the name of the CPUID bit to match the instruction name. We should follow suit for sanity's sake. (See Intel SDM Volume 2, Table 3-20 "Feature Information Returned in the ECX Register".)
[ hpa: we can only do this at this time because there are currently no CPUs
with this feature on the market, hence this is pre-hardware enabling. However, Cc:'ing stable so that stable can present a consistent ABI. ]
--- arch/x86/include/asm/cpufeature.h | 2 +- 1 files changed, 1 insertions(+), 1 deletions(-)
arch/x86/include/asm/cpufeature.h +1 -1
@@ -125,7 +125,7 @@#define X86_FEATURE_OSXSAVE (4*32+27)/* "" XSAVE enabled in the OS */ #define X86_FEATURE_AVX (4*32+28)/* Advanced Vector Extensions */ #define X86_FEATURE_F16C (4*32+29)/* 16-bit fp conversions */ -#define X86_FEATURE_RDRND (4*32+30)/* The RDRAND instruction */ +#define X86_FEATURE_RDRAND (4*32+30)/* The RDRAND instruction */ #define X86_FEATURE_HYPERVISOR (4*32+31)/* Running on a hypervisor */ /* VIA/Cyrix/Centaur-defined CPU features, CPUID level 0xC0000001, word 5 */
Signature · 1 line
1.7.2.1.45.g54fbc
PATCH 159/180 random: Add support for architectural random hooks
In reply to a message not in the archive2.6.32-longterm review patch. If anyone has any objections, please let me know.
------------------
From: H. Peter Anvin <[email protected]>
commit 63d77173266c1791f1553e9e8ccea65dc87c4485 upstream.
Add support for architecture-specific hooks into the kernel-directed random number generator interfaces. This patchset does not use the architecture random number generator interfaces for the userspace-directed interfaces (/dev/random and /dev/urandom), thus eliminating the need to distinguish between them based on a pool pointer.
Changes in version 3:
- Moved the hooks from extract_entropy() to get_random_bytes().
- Changes the hooks to inlines.
[PG: .34 already had "unsigned int ret" in get_random_int, so the
diffstat here is slightly smaller than that of 63d7717. ]
--- drivers/char/random.c | 23 +++++++++++++++++++++-- include/linux/random.h | 13 +++++++++++++ 2 files changed, 34 insertions(+), 2 deletions(-)
drivers/char/random.c +21 -2
@@ -932,7 +932,21 @@ static ssize_t extract_entropy_user(struct entropy_store *r, void __user *buf,*/ void get_random_bytes (void *buf,int nbytes) { -extract_entropy (&nonblocking_pool, buf, nbytes,0 ,0 ); +char *p = buf; + +while (nbytes) { +unsigned long v; +int chunk =min (nbytes, (int )sizeof (unsigned long )); + +if (!arch_get_random_long (&v)) +break ; + +memcpy (buf, &v, chunk); + p += chunk; + nbytes -= chunk; + } + +extract_entropy (&nonblocking_pool, p, nbytes,0 ,0 ); }EXPORT_SYMBOL (get_random_bytes);
@@ -1360,9 +1374,14 @@ late_initcall(random_int_secret_init);DEFINE_PER_CPU (__u32 [MD5_DIGEST_WORDS ], get_random_int_hash);unsigned int get_random_int (void ) { -__u32 *hash =get_cpu_var (get_random_int_hash); +__u32 *hash;unsigned int ret; +if (arch_get_random_int (&ret)) +return ret; + + hash =get_cpu_var (get_random_int_hash); + hash[0 ] += current->pid + jiffies +get_cycles ();md5_transform (hash, random_int_secret); ret = hash[0 ];
include/linux/random.h +13 -0
@@ -63,6 +63,19 @@ unsigned long randomize_range(unsigned long start, unsigned long end, unsigned lu32 random32 (void );void srandom32 (u32 seed); +#ifdef CONFIG_ARCH_RANDOM +# include <asm/archrandom.h> +#else +static inline int arch_get_random_long (unsigned long *v) +{ +return 0 ; +} +static inline int arch_get_random_int (unsigned int *v) +{ +return 0 ; +} +#endif +#endif /* __KERNEL___ */ #endif /* _LINUX_RANDOM_H */
Signature · 1 line
1.7.2.1.45.g54fbc
PATCH 160/180 x86, random: Architectural inlines to get random integers with RDRAND
In reply to a message not in the archive2.6.32-longterm review patch. If anyone has any objections, please let me know.
------------------
From: H. Peter Anvin <[email protected]>
commit 628c6246d47b85f5357298601df2444d7f4dd3fd upstream.
Architectural inlines to get random ints and longs using the RDRAND instruction.
Intel has introduced a new RDRAND instruction, a Digital Random Number Generator (DRNG), which is functionally an high bandwidth entropy source, cryptographic whitener, and integrity monitor all built into hardware. This enables RDRAND to be used directly, bypassing the kernel random number pool.
For technical documentation, see:
In this patch, this is *only* used for the nonblocking random number pool. RDRAND is a nonblocking source, similar to our /dev/urandom, and is therefore not a direct replacement for /dev/random. The architectural hooks presented in the previous patch only feed the kernel internal users, which only use the nonblocking pool, and so this is not a problem.
Since this instruction is available in userspace, there is no reason to have a /dev/hw_rng device driver for the purpose of feeding rngd. This is especially so since RDRAND is a nonblocking source, and needs additional whitening and reduction (see the above technical documentation for details) in order to be of "pure entropy source" quality.
The CONFIG_EXPERT compile-time option can be used to disable this use of RDRAND.
--- arch/x86/Kconfig | 9 +++++ arch/x86/include/asm/archrandom.h | 73 +++++++++++++++++++++++++++++++++++++ 2 files changed, 82 insertions(+), 0 deletions(-) create mode 100644 arch/x86/include/asm/archrandom.h
arch/x86/Kconfig +9 -0
@@ -1428,6 +1428,15 @@ config ARCH_USES_PG_UNCACHED def_bool y depends on X86_PAT +config ARCH_RANDOM + def_bool y + prompt "x86 architectural random number generator" if EXPERT + ---help--- + Enable the x86 architectural RDRAND instruction + (Intel Bull Mountain technology) to generate random numbers. + If supported, this is a high bandwidth, cryptographically + secure hardware random number generator. + config EFI bool "EFI runtime service support" depends on ACPI
arch/x86/include/asm/archrandom.h new file +73 -0
73 lines not on this page · raw message
Signature · 1 line
1.7.2.1.45.g54fbc
PATCH 161/180 x86, random: Verify RDRAND functionality and allow it to be disabled
In reply to a message not in the archive2.6.32-longterm review patch. If anyone has any objections, please let me know.
------------------
From: H. Peter Anvin <[email protected]>
commit 49d859d78c5aeb998b6936fcb5f288f78d713489 upstream.
If the CPU declares that RDRAND is available, go through a guranteed reseed sequence, and make sure that it is actually working (producing
data.) If it does not, disable the CPU feature flag.
Allow RDRAND to be disabled on the command line (as opposed to at compile time) for a user who has special requirements with regards to random numbers.
--- Documentation/kernel-parameters.txt | 5 ++ arch/x86/include/asm/archrandom.h | 2 + arch/x86/kernel/cpu/Makefile | 1 + arch/x86/kernel/cpu/common.c | 2 + arch/x86/kernel/cpu/rdrand.c | 73 +++++++++++++++++++++++++++++++++++ 5 files changed, 83 insertions(+), 0 deletions(-) create mode 100644 arch/x86/kernel/cpu/rdrand.c
Documentation/kernel-parameters.txt +5 -0
@@ -1725,6 +1725,11 @@ and is between 256 and 4096 characters. It is defined in the file noresidual [PPC] Don't use residual data on PReP machines. + nordrand [X86] Disable the direct use of the RDRAND + instruction even if it is supported by the + processor. RDRAND is still available to user + space applications. + noresume [SWSUSP] Disables resume and restores original swap space.
arch/x86/include/asm/archrandom.h +2 -0
@@ -70,4 +70,6 @@ GET_RANDOM(arch_get_random_int, unsigned int, RDRAND_INT, ASM_NOP3);#endif /* CONFIG_ARCH_RANDOM */ +extern void x86_init_rdrand (struct cpuinfo_x86 *c); +#endif /* ASM_X86_ARCHRANDOM_H */
arch/x86/kernel/cpu/Makefile +1 -0
@@ -14,6 +14,7 @@ CFLAGS_common.o := $(nostackp) obj-y := intel_cacheinfo.o addon_cpuid_features.o obj-y += proc.o capflags.o powerflags.o common.o obj-y += vmware.o hypervisor.o sched.o +obj-y += rdrand.o obj-$(CONFIG_X86_32) += bugs.o cmpxchg.o obj-$(CONFIG_X86_64) += bugs_64.o
arch/x86/kernel/cpu/common.c +2 -0
@@ -15,6 +15,7 @@#include <asm/stackprotector.h> #include <asm/perf_event.h> #include <asm/mmu_context.h> +#include <asm/archrandom.h> #include <asm/hypervisor.h> #include <asm/processor.h> #include <asm/sections.h>
@@ -815,6 +816,7 @@ static void __cpuinit identify_cpu(struct cpuinfo_x86 *c)#endif init_hypervisor (c); +x86_init_rdrand (c);/* * Clear/Set all flags overriden by options, need do it
arch/x86/kernel/cpu/rdrand.c new file +73 -0
73 lines not on this page · raw message
Signature · 1 line
1.7.2.1.45.g54fbc
PATCH 162/180 fix typo/thinko in get_random_bytes()
In reply to a message not in the archive2.6.32-longterm review patch. If anyone has any objections, please let me know.
------------------
From: Luck, Tony <[email protected]>
commit bd29e568a4cb6465f6e5ec7c1c1f3ae7d99cbec1 upstream.
If there is an architecture-specific random number generator we use it to acquire randomness one "long" at a time. We should put these random words into consecutive words in the result buffer - not just overwrite the first word again and again.
--- drivers/char/random.c | 2 +- 1 files changed, 1 insertions(+), 1 deletions(-)
drivers/char/random.c +1 -1
@@ -941,7 +941,7 @@ void get_random_bytes(void *buf, int nbytes)if (!arch_get_random_long (&v))break ; -memcpy (buf, &v, chunk); +memcpy (p, &v, chunk); p += chunk; nbytes -= chunk; }
Signature · 1 line
1.7.2.1.45.g54fbc
PATCH 163/180 random: Use arch_get_random_int instead of cycle counter if avail
In reply to a message not in the archive2.6.32-longterm review patch. If anyone has any objections, please let me know.
------------------
From: Linus Torvalds <[email protected]>
commit cf833d0b9937874b50ef2867c4e8badfd64948ce upstream.
We still don't use rdrand in /dev/random, which just seems stupid. We accept the *cycle*counter* as a random input, but we don't accept rdrand? That's just broken.
Sure, people can do things in user space (write to /dev/random, use rdrand in addition to /dev/random themselves etc etc), but that *still* seems to be a particularly stupid reason for saying "we shouldn't bother to try to do better in /dev/random".
And even if somebody really doesn't trust rdrand as a source of random bytes, it seems singularly stupid to trust the cycle counter *more*.
So I'd suggest the attached patch. I'm not going to even bother arguing that we should add more bits to the entropy estimate, because that's not the point - I don't care if /dev/random fills up slowly or not, I think it's just stupid to not use the bits we can get from rdrand and mix them into the strong randomness pool.
--- drivers/char/random.c | 8 ++++++-- 1 files changed, 6 insertions(+), 2 deletions(-)
drivers/char/random.c +6 -2
@@ -624,8 +624,8 @@ static struct timer_rand_state input_timer_state;static void add_timer_randomness (struct timer_rand_state *state,unsigned num) {struct { -cycles_t cycles;long jiffies; +unsigned cycles;unsigned num; } sample;long delta, delta2, delta3;
@@ -637,7 +637,11 @@ static void add_timer_randomness(struct timer_rand_state *state, unsigned num) goto out; sample.jiffies = jiffies; - sample.cycles =get_cycles (); + +/* Use arch random value, fall back to cycles */ +if (!arch_get_random_int (&sample.cycles)) + sample.cycles =get_cycles (); + sample.num = num;mix_pool_bytes (&input_pool, &sample,sizeof (sample));
Signature · 1 line
1.7.2.1.45.g54fbc
PATCH 164/180 random: Use arch-specific RNG to initialize the entropy store
In reply to a message not in the archive2.6.32-longterm review patch. If anyone has any objections, please let me know.
------------------
From: Theodore Ts'o <[email protected]>
commit 3e88bdff1c65145f7ba297ccec69c774afe4c785 upstream.
If there is an architecture-specific random number generator (such as RDRAND for Intel architectures), use it to initialize /dev/random's entropy stores. Even in the worst case, if RDRAND is something like AES(NSA_KEY, counter++), it won't hurt, and it will definitely help against any other adversaries.
--- drivers/char/random.c | 6 ++++++ 1 files changed, 6 insertions(+), 0 deletions(-)
drivers/char/random.c +6 -0
@@ -965,6 +965,7 @@ EXPORT_SYMBOL(get_random_bytes);*/ static void init_std_data (struct entropy_store *r) { +int i;ktime_t now;unsigned long flags;
@@ -974,6 +975,11 @@ static void init_std_data(struct entropy_store *r) now =ktime_get_real ();mix_pool_bytes (r, &now,sizeof (now)); +for (i = r->poolinfo->poolwords; i; i--) { +if (!arch_get_random_long (&flags)) +break ; +mix_pool_bytes (r, &flags,sizeof (flags)); + }mix_pool_bytes (r,utsname (),sizeof (*(utsname ()))); }
Signature · 1 line
1.7.2.1.45.g54fbc
PATCH 165/180 random: Adjust the number of loops when initializing
In reply to a message not in the archive2.6.32-longterm review patch. If anyone has any objections, please let me know.
------------------
From: H. Peter Anvin <[email protected]>
commit 2dac8e54f988ab58525505d7ef982493374433c3 upstream.
When we are initializing using arch_get_random_long() we only need to loop enough times to touch all the bytes in the buffer; using poolwords for that does twice the number of operations necessary on a 64-bit machine, since in the random number generator code "word" means 32 bits.
--- drivers/char/random.c | 2 +- 1 files changed, 1 insertions(+), 1 deletions(-)
drivers/char/random.c +1 -1
@@ -975,7 +975,7 @@ static void init_std_data(struct entropy_store *r) now =ktime_get_real ();mix_pool_bytes (r, &now,sizeof (now)); -for (i = r->poolinfo->poolwords; i; i--) { +for (i = r->poolinfo->POOLBYTES; i >0 ; i -=sizeof flags) {if (!arch_get_random_long (&flags))break ;mix_pool_bytes (r, &flags,sizeof (flags));
Signature · 1 line
1.7.2.1.45.g54fbc
PATCH 166/180 drivers/char/random.c: fix boot id uniqueness race
In reply to a message not in the archive2.6.32-longterm review patch. If anyone has any objections, please let me know.
------------------
From: Mathieu Desnoyers <[email protected]>
commit 44e4360fa3384850d65dd36fb4e6e5f2f112709b upstream.
/proc/sys/kernel/random/boot_id can be read concurrently by userspace processes. If two (or more) user-space processes concurrently read boot_id when sysctl_bootid is not yet assigned, a race can occur making boot_id differ between the reads. Because the whole point of the boot id is to be unique across a kernel execution, fix this by protecting this operation with a spinlock.
Given that this operation is not frequently used, hitting the spinlock on each call should not be an issue.
--- drivers/char/random.c | 11 ++++++++--- 1 files changed, 8 insertions(+), 3 deletions(-)
drivers/char/random.c +8 -3
@@ -1258,10 +1258,15 @@ static int proc_do_uuid(ctl_table *table, int write, uuid = table->data;if (!uuid) { uuid = tmp_uuid; - uuid[8 ] =0 ; - } -if (uuid[8 ] ==0 )generate_random_uuid (uuid); + }else { +static DEFINE_SPINLOCK (bootid_spinlock); + +spin_lock (&bootid_spinlock); +if (!uuid[8 ]) +generate_random_uuid (uuid); +spin_unlock (&bootid_spinlock); + } sprintf(buf, "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-" "%02x%02x%02x%02x%02x%02x",
Signature · 1 line
1.7.2.1.45.g54fbc
PATCH 167/180 random: make add_interrupt_randomness() do something sane
In reply to a message not in the archive2.6.32-longterm review patch. If anyone has any objections, please let me know.
------------------
From: Theodore Ts'o <[email protected]>
commit 775f4b297b780601e61787b766f306ed3e1d23eb upstream.
We've been moving away from add_interrupt_randomness() for various
reasons: it's too expensive to do on every interrupt, and flooding the CPU with interrupts could theoretically cause bogus floods of entropy from a somewhat externally controllable source.
This solves both problems by limiting the actual randomness addition to just once a second or after 64 interrupts, whicever comes first. During that time, the interrupt cycle data is buffered up in a per-cpu pool. Also, we make sure the the nonblocking pool used by urandom is initialized before we start feeding the normal input pool. This assures that /dev/urandom is returning unpredictable data as soon as possible.
(Based on an original patch by Linus, but significantly modified by tytso.)
[PG: minor adjustment required since .34 doesn't have f9e4989eb8
which renames "status" to "random" in kernel/irq/handle.c ]
--- drivers/char/random.c | 103 ++++++++++++++++++++++++++++++++++++++++-------- include/linux/random.h | 2 +- kernel/irq/handle.c | 7 +-- 3 files changed, 90 insertions(+), 22 deletions(-)
drivers/char/random.c +86 -17
@@ -127,19 +127,15 @@* * void add_input_randomness(unsigned int type, unsigned int code, * unsigned int value); -* void add_interrupt_randomness(int irq); +* void add_interrupt_randomness(int irq, int irq_flags); * void add_disk_randomness(struct gendisk *disk); * * add_input_randomness() uses the input layer interrupt timing, as well as * the event type information from the hardware. * -* add_interrupt_randomness() uses the inter-interrupt timing as random -* inputs to the entropy pool. Note that not all interrupts are good -* sources of randomness! For example, the timer interrupts is not a -* good choice, because the periodicity of the interrupts is too -* regular, and hence predictable to an attacker. Network Interface -* Controller interrupts are a better measure, since the timing of the -* NIC interrupts are more unpredictable. +* add_interrupt_randomness() uses the interrupt timing as random +* inputs to the entropy pool. Using the cycle counters and the irq source +* as inputs, it feeds the randomness roughly once a second. * * add_disk_randomness() uses what amounts to the seek time of block * layer request events, on a per-disk_devt basis, as input to the
@@ -248,6 +244,7 @@#include <linux/percpu.h> #include <linux/cryptohash.h> #include <linux/fips.h> +#include <linux/ptrace.h> #ifdef CONFIG_GENERIC_HARDIRQS # include <linux/irq.h>
@@ -256,6 +253,7 @@#include <asm/processor.h> #include <asm/uaccess.h> #include <asm/irq.h> +#include <asm/irq_regs.h> #include <asm/io.h> /*
@@ -421,7 +419,9 @@ struct entropy_store {spinlock_t lock;unsigned add_ptr;int entropy_count; +int entropy_total;int input_rotate; + unsigned int initialized:1;__u8 last_data[EXTRACT_SIZE ]; };
@@ -454,6 +454,10 @@ static struct entropy_store nonblocking_pool = { .pool = nonblocking_pool_data }; +static __u32 const twist_table[8 ] = { +0x00000000 ,0x3b6e20c8 ,0x76dc4190 ,0x4db26158 , +0xedb88320 ,0xd6d6a3e8 ,0x9b64c2b0 ,0xa00ae278 }; +/* * This function adds bytes into the entropy "pool". It does not * update the entropy estimate. The caller should call
@@ -467,9 +471,6 @@ static struct entropy_store nonblocking_pool = {static void mix_pool_bytes_extract (struct entropy_store *r,const void *in,int nbytes,__u8 out[64 ]) { -static __u32 const twist_table[8 ] = { -0x00000000 ,0x3b6e20c8 ,0x76dc4190 ,0x4db26158 , -0xedb88320 ,0xd6d6a3e8 ,0x9b64c2b0 ,0xa00ae278 };unsigned long i, j, tap1, tap2, tap3, tap4, tap5;int input_rotate;int wordmask = r->poolinfo->poolwords -1 ;
@@ -528,6 +529,36 @@ static void mix_pool_bytes(struct entropy_store *r, const void *in, int bytes)mix_pool_bytes_extract (r, in, bytes,NULL ); } +struct fast_pool { +__u32 pool[4 ]; +unsigned long last; +unsigned short count; +unsigned char rotate; +unsigned char last_timer_intr; +}; + +/* +* This is a fast mixing routine used by the interrupt randomness +* collector. It's hardcoded for an 128 bit pool and assumes that any +* locks that might be needed are taken by the caller. +*/ +static void fast_mix (struct fast_pool *f,const void *in,int nbytes) +{ +const char *bytes = in; +__u32 w; +unsigned i = f->count; +unsigned input_rotate = f->rotate; + +while (nbytes--) { + w =rol32 (*bytes++, input_rotate &31 ) ^ f->pool[i &3 ] ^ + f->pool[(i +1 ) &3 ]; + f->pool[i &3 ] = (w >>3 ) ^ twist_table[w &7 ]; + input_rotate += (i++ &3 ) ?7 :14 ; + } + f->count = i; + f->rotate = input_rotate; +} +/* * Credit (or debit) the entropy store with n bits of entropy */
@@ -551,6 +582,12 @@ static void credit_entropy_bits(struct entropy_store *r, int nbits) entropy_count = r->poolinfo->POOLBITS; r->entropy_count = entropy_count; +if (!r->initialized && nbits >0 ) { + r->entropy_total += nbits; +if (r->entropy_total >128 ) + r->initialized =1 ; + } +/* should we wake readers? */ if (r == &input_pool && entropy_count >= random_read_wakeup_thresh) {wake_up_interruptible (&random_read_wait);
@@ -700,17 +737,48 @@ void add_input_randomness(unsigned int type, unsigned int code, }EXPORT_SYMBOL_GPL (add_input_randomness); -void add_interrupt_randomness (int irq) +static DEFINE_PER_CPU(struct fast_pool, irq_randomness); + +void add_interrupt_randomness (int irq,int irq_flags) { -struct timer_rand_state *state; +struct entropy_store *r; +struct fast_pool *fast_pool = &__get_cpu_var (irq_randomness); +struct pt_regs *regs =get_irq_regs (); +unsigned long now = jiffies; +__u32 input[4 ], cycles =get_cycles (); + + input[0 ] = cycles ^ jiffies; + input[1 ] = irq; +if (regs) { +__u64 ip =instruction_pointer (regs); + input[2 ] = ip; + input[3 ] = ip >>32 ; + } - state =get_timer_rand_state (irq); +fast_mix (fast_pool, input,sizeof (input)); -if (state ==NULL ) +if ((fast_pool->count &1023 ) && + !time_after (now, fast_pool->last +HZ ))return ; -DEBUG_ENT ("irq event %d\n" , irq); -add_timer_randomness (state,0x100 + irq); + fast_pool->last = now; + + r = nonblocking_pool.initialized ? &input_pool : &nonblocking_pool; +mix_pool_bytes (r, &fast_pool->pool,sizeof (fast_pool->pool)); +/* +* If we don't have a valid cycle counter, and we see +* back-to-back timer interrupts, then skip giving credit for +* any entropy. +*/ +if (cycles ==0 ) { +if (irq_flags & __IRQF_TIMER) { +if (fast_pool->last_timer_intr) +return ; + fast_pool->last_timer_intr =1 ; + }else + fast_pool->last_timer_intr =0 ; + } +credit_entropy_bits (r,1 ); }#ifdef CONFIG_BLOCK
@@ -971,6 +1039,7 @@ static void init_std_data(struct entropy_store *r)spin_lock_irqsave (&r->lock, flags); r->entropy_count =0 ; + r->entropy_total =0 ;spin_unlock_irqrestore (&r->lock, flags); now =ktime_get_real ();
include/linux/random.h +1 -1
@@ -48,7 +48,7 @@ extern void rand_initialize_irq(int irq);extern void add_input_randomness (unsigned int type,unsigned int code,unsigned int value); -extern void add_interrupt_randomness (int irq); +extern void add_interrupt_randomness (int irq,int irq_flags);extern void get_random_bytes (void *buf,int nbytes);void generate_random_uuid (unsigned char uuid_out[16 ]);
kernel/irq/handle.c +3 -4
@@ -370,7 +370,7 @@ static void warn_no_thread(unsigned int irq, struct irqaction *action)irqreturn_t handle_IRQ_event (unsigned int irq,struct irqaction *action) {irqreturn_t ret, retval =IRQ_NONE ; -unsigned int status =0 ; +unsigned int flags =0 ;if (!(action->flags &IRQF_DISABLED ))local_irq_enable_in_hardirq ();
@@ -413,7 +413,7 @@ irqreturn_t handle_IRQ_event(unsigned int irq, struct irqaction *action)/* Fall through to add to randomness */ case IRQ_HANDLED : - status |= action->flags; + flags |= action->flags;break ;default :
@@ -424,8 +424,7 @@ irqreturn_t handle_IRQ_event(unsigned int irq, struct irqaction *action) action = action->next; }while (action); -if (status &IRQF_SAMPLE_RANDOM ) -add_interrupt_randomness (irq); +add_interrupt_randomness (irq, flags);local_irq_disable ();return retval;
Signature · 1 line
1.7.2.1.45.g54fbc
PATCH 168/180 random: use lockless techniques in the interrupt path
In reply to a message not in the archive2.6.32-longterm review patch. If anyone has any objections, please let me know.
------------------
From: Theodore Ts'o <[email protected]>
commit 902c098a3663de3fa18639efbb71b6080f0bcd3c upstream.
The real-time Linux folks don't like add_interrupt_randomness() taking a spinlock since it is called in the low-level interrupt routine. This also allows us to reduce the overhead in the fast path, for the random driver, which is the interrupt collection path.
--- drivers/char/random.c | 78 ++++++++++++++++++++++++------------------------ 1 files changed, 39 insertions(+), 39 deletions(-)
drivers/char/random.c +39 -39
@@ -418,9 +418,9 @@ struct entropy_store {/* read-write data: */ spinlock_t lock;unsigned add_ptr; +unsigned input_rotate;int entropy_count;int entropy_total; -int input_rotate; unsigned int initialized:1;__u8 last_data[EXTRACT_SIZE ]; };
@@ -468,26 +468,24 @@ static __u32 const twist_table[8] = {* it's cheap to do so and helps slightly in the expected case where * the entropy is concentrated in the low-order bits. */ -static void mix_pool_bytes_extract (struct entropy_store *r,const void *in, -int nbytes,__u8 out[64 ]) +static void __mix_pool_bytes (struct entropy_store *r,const void *in, +int nbytes,__u8 out[64 ]) {unsigned long i, j, tap1, tap2, tap3, tap4, tap5;int input_rotate;int wordmask = r->poolinfo->poolwords -1 ;const char *bytes = in;__u32 w; -unsigned long flags; -/* Taps are constant, so we can load them without holding r->lock. */ tap1 = r->poolinfo->tap1; tap2 = r->poolinfo->tap2; tap3 = r->poolinfo->tap3; tap4 = r->poolinfo->tap4; tap5 = r->poolinfo->tap5; -spin_lock_irqsave (&r->lock, flags); - input_rotate = r->input_rotate; - i = r->add_ptr; +smp_rmb (); + input_rotate =ACCESS_ONCE (r->input_rotate); + i =ACCESS_ONCE (r->add_ptr);/* mix one byte at a time to simplify size handling and churn faster */ while (nbytes--) {
@@ -514,19 +512,23 @@ static void mix_pool_bytes_extract(struct entropy_store *r, const void *in, input_rotate += i ?7 :14 ; } - r->input_rotate = input_rotate; - r->add_ptr = i; +ACCESS_ONCE (r->input_rotate) = input_rotate; +ACCESS_ONCE (r->add_ptr) = i; +smp_wmb ();if (out)for (j =0 ; j <16 ; j++) ((__u32 *)out)[j] = r->pool[(i - j) & wordmask]; - -spin_unlock_irqrestore (&r->lock, flags); } -static void mix_pool_bytes (struct entropy_store *r,const void *in,int bytes) +static void mix_pool_bytes (struct entropy_store *r,const void *in, +int nbytes,__u8 out[64 ]) { -mix_pool_bytes_extract (r, in, bytes,NULL ); +unsigned long flags; + +spin_lock_irqsave (&r->lock, flags); +__mix_pool_bytes (r, in, nbytes, out); +spin_unlock_irqrestore (&r->lock, flags); }struct fast_pool {
@@ -564,23 +566,22 @@ static void fast_mix(struct fast_pool *f, const void *in, int nbytes)*/ static void credit_entropy_bits (struct entropy_store *r,int nbits) { -unsigned long flags; -int entropy_count; +int entropy_count, orig;if (!nbits)return ; -spin_lock_irqsave (&r->lock, flags); -DEBUG_ENT ("added %d entropy credits to %s\n" , nbits, r->name); - entropy_count = r->entropy_count; +retry: + entropy_count = orig =ACCESS_ONCE (r->entropy_count); entropy_count += nbits;if (entropy_count <0 ) {DEBUG_ENT ("negative entropy/overflow\n" ); entropy_count =0 ; }else if (entropy_count > r->poolinfo->POOLBITS) entropy_count = r->poolinfo->POOLBITS; - r->entropy_count = entropy_count; +if (cmpxchg (&r->entropy_count, orig, entropy_count) != orig) + goto retry;if (!r->initialized && nbits >0 ) { r->entropy_total += nbits;
@@ -593,7 +594,6 @@ static void credit_entropy_bits(struct entropy_store *r, int nbits)wake_up_interruptible (&random_read_wait);kill_fasync (&fasync,SIGIO ,POLL_IN ); } -spin_unlock_irqrestore (&r->lock, flags); }/*********************************************************************
@@ -680,7 +680,7 @@ static void add_timer_randomness(struct timer_rand_state *state, unsigned num) sample.cycles =get_cycles (); sample.num = num; -mix_pool_bytes (&input_pool, &sample,sizeof (sample)); +mix_pool_bytes (&input_pool, &sample,sizeof (sample),NULL );/* * Calculate number of bits of randomness we probably added.
@@ -764,7 +764,7 @@ void add_interrupt_randomness(int irq, int irq_flags) fast_pool->last = now; r = nonblocking_pool.initialized ? &input_pool : &nonblocking_pool; -mix_pool_bytes (r, &fast_pool->pool,sizeof (fast_pool->pool)); +__mix_pool_bytes (r, &fast_pool->pool,sizeof (fast_pool->pool),NULL );/* * If we don't have a valid cycle counter, and we see * back-to-back timer interrupts, then skip giving credit for
@@ -829,7 +829,7 @@ static void xfer_secondary_pool(struct entropy_store *r, size_t nbytes) bytes =extract_entropy (r->pull, tmp, bytes, random_read_wakeup_thresh /8 , rsvd); -mix_pool_bytes (r, tmp, bytes); +mix_pool_bytes (r, tmp, bytes,NULL );credit_entropy_bits (r, bytes*8 ); } }
@@ -890,9 +890,11 @@ static void extract_buf(struct entropy_store *r, __u8 *out)int i;__u32 hash[5 ], workspace[SHA_WORKSPACE_WORDS ];__u8 extract[64 ]; +unsigned long flags;/* Generate a hash across the pool, 16 words (512 bits) at a time */ sha_init (hash); +spin_lock_irqsave (&r->lock, flags);for (i =0 ; i < r->poolinfo->poolwords; i +=16 )sha_transform (hash, (__u8 *)(r->pool + i), workspace);
@@ -905,7 +907,8 @@ static void extract_buf(struct entropy_store *r, __u8 *out)* brute-forcing the feedback as hard as brute-forcing the * hash. */ -mix_pool_bytes_extract (r, hash,sizeof (hash), extract); +__mix_pool_bytes (r, hash,sizeof (hash), extract); +spin_unlock_irqrestore (&r->lock, flags);/* * To avoid duplicates, we atomically extract a portion of the
@@ -928,11 +931,10 @@ static void extract_buf(struct entropy_store *r, __u8 *out) }static ssize_t extract_entropy (struct entropy_store *r,void *buf, -size_t nbytes,int min,int reserved) +size_t nbytes,int min,int reserved) {ssize_t ret =0 , i;__u8 tmp[EXTRACT_SIZE ]; -unsigned long flags;xfer_secondary_pool (r, nbytes); nbytes =account (r, nbytes, min, reserved);
@@ -941,6 +943,8 @@ static ssize_t extract_entropy(struct entropy_store *r, void *buf,extract_buf (r, tmp);if (fips_enabled) { +unsigned long flags; +spin_lock_irqsave (&r->lock, flags);if (!memcmp (tmp, r->last_data,EXTRACT_SIZE ))panic ("Hardware RNG duplicated output!\n" );
@@ -1034,22 +1038,18 @@ EXPORT_SYMBOL(get_random_bytes);static void init_std_data (struct entropy_store *r) {int i; -ktime_t now; -unsigned long flags; +ktime_t now =ktime_get_real (); +unsigned long rv; -spin_lock_irqsave (&r->lock, flags); r->entropy_count =0 ; r->entropy_total =0 ; -spin_unlock_irqrestore (&r->lock, flags); - - now =ktime_get_real (); -mix_pool_bytes (r, &now,sizeof (now)); -for (i = r->poolinfo->POOLBYTES; i >0 ; i -=sizeof flags) { -if (!arch_get_random_long (&flags)) +mix_pool_bytes (r, &now,sizeof (now),NULL ); +for (i = r->poolinfo->POOLBYTES; i >0 ; i -=sizeof (rv)) { +if (!arch_get_random_long (&rv))break ; -mix_pool_bytes (r, &flags,sizeof (flags)); +mix_pool_bytes (r, &rv,sizeof (rv),NULL ); } -mix_pool_bytes (r,utsname (),sizeof (*(utsname ()))); +mix_pool_bytes (r,utsname (),sizeof (*(utsname ())),NULL ); }static int rand_initialize (void )
@@ -1186,7 +1186,7 @@ write_pool(struct entropy_store *r, const char __user *buffer, size_t count) count -= bytes; p += bytes; -mix_pool_bytes (r, buf, bytes); +mix_pool_bytes (r, buf, bytes,NULL );cond_resched (); }
Signature · 1 line
1.7.2.1.45.g54fbc
PATCH 169/180 random: create add_device_randomness() interface
In reply to a message not in the archive2.6.32-longterm review patch. If anyone has any objections, please let me know.
------------------
From: Linus Torvalds <[email protected]>
commit a2080a67abe9e314f9e9c2cc3a4a176e8a8f8793 upstream.
Add a new interface, add_device_randomness() for adding data to the random pool that is likely to differ between two devices (or possibly even per boot). This would be things like MAC addresses or serial numbers, or the read-out of the RTC. This does *not* add any actual entropy to the pool, but it initializes the pool to different values for devices that might otherwise be identical and have very little entropy available to them (particularly common in the embedded world).
[ Modified by tytso to mix in a timestamp, since there may be some
variability caused by the time needed to detect/configure the hardware in question. ]
--- drivers/char/random.c | 28 ++++++++++++++++++++++++++++ include/linux/random.h | 1 + 2 files changed, 29 insertions(+), 0 deletions(-)
drivers/char/random.c +28 -0
@@ -125,11 +125,20 @@* The current exported interfaces for gathering environmental noise * from the devices are: * +* void add_device_randomness(const void *buf, unsigned int size); * void add_input_randomness(unsigned int type, unsigned int code, * unsigned int value); * void add_interrupt_randomness(int irq, int irq_flags); * void add_disk_randomness(struct gendisk *disk); * +* add_device_randomness() is for adding data to the random pool that +* is likely to differ between two devices (or possibly even per boot). +* This would be things like MAC addresses or serial numbers, or the +* read-out of the RTC. This does *not* add any actual entropy to the +* pool, but it initializes the pool to different values for devices +* that might otherwise be identical and have very little entropy +* available to them (particularly common in the embedded world). +* * add_input_randomness() uses the input layer interrupt timing, as well as * the event type information from the hardware. *
@@ -646,6 +655,25 @@ static void set_timer_rand_state(unsigned int irq, }#endif +/* +* Add device- or boot-specific data to the input and nonblocking +* pools to help initialize them to unique values. +* +* None of this adds any entropy, it is meant to avoid the +* problem of the nonblocking pool having similar initial state +* across largely identical devices. +*/ +void add_device_randomness (const void *buf,unsigned int size) +{ +unsigned long time =get_cycles () ^ jiffies; + +mix_pool_bytes (&input_pool, buf, size,NULL ); +mix_pool_bytes (&input_pool, &time,sizeof (time),NULL ); +mix_pool_bytes (&nonblocking_pool, buf, size,NULL ); +mix_pool_bytes (&nonblocking_pool, &time,sizeof (time),NULL ); +} +EXPORT_SYMBOL (add_device_randomness); +static struct timer_rand_state input_timer_state;/*
include/linux/random.h +1 -0
@@ -46,6 +46,7 @@ struct rand_pool_info {extern void rand_initialize_irq (int irq); +extern void add_device_randomness (const void *,unsigned int );extern void add_input_randomness (unsigned int type,unsigned int code,unsigned int value);extern void add_interrupt_randomness (int irq,int irq_flags);
Signature · 1 line
1.7.2.1.45.g54fbc
PATCH 170/180 random: use the arch-specific rng in xfer_secondary_pool
In reply to a message not in the archive2.6.32-longterm review patch. If anyone has any objections, please let me know.
------------------
From: Theodore Ts'o <[email protected]>
commit e6d4947b12e8ad947add1032dd754803c6004824 upstream.
If the CPU supports a hardware random number generator, use it in xfer_secondary_pool(), where it will significantly improve things and where we can afford it.
Also, remove the use of the arch-specific rng in add_timer_randomness(), since the call is significantly slower than get_cycles(), and we're much better off using it in xfer_secondary_pool() anyway.
--- drivers/char/random.c | 25 ++++++++++++++++--------- 1 files changed, 16 insertions(+), 9 deletions(-)
drivers/char/random.c +16 -9
@@ -254,6 +254,7 @@#include <linux/cryptohash.h> #include <linux/fips.h> #include <linux/ptrace.h> +#include <linux/kmemcheck.h> #ifdef CONFIG_GENERIC_HARDIRQS # include <linux/irq.h>
@@ -702,11 +703,7 @@ static void add_timer_randomness(struct timer_rand_state *state, unsigned num) goto out; sample.jiffies = jiffies; - -/* Use arch random value, fall back to cycles */ -if (!arch_get_random_int (&sample.cycles)) - sample.cycles =get_cycles (); - + sample.cycles =get_cycles (); sample.num = num;mix_pool_bytes (&input_pool, &sample,sizeof (sample),NULL );
@@ -838,7 +835,11 @@ static ssize_t extract_entropy(struct entropy_store *r, void *buf,*/ static void xfer_secondary_pool (struct entropy_store *r,size_t nbytes) { -__u32 tmp[OUTPUT_POOL_WORDS ]; +union { +__u32 tmp[OUTPUT_POOL_WORDS ]; +long hwrand[4 ]; + } u; +int i;if (r->pull && r->entropy_count < nbytes *8 && r->entropy_count < r->poolinfo->POOLBITS) {
@@ -849,17 +850,23 @@ static void xfer_secondary_pool(struct entropy_store *r, size_t nbytes)/* pull at least as many as BYTES as wakeup BITS */ bytes =max_t (int, bytes, random_read_wakeup_thresh /8 );/* but never more than the buffer size */ - bytes =min_t (int, bytes,sizeof (tmp)); + bytes =min_t (int, bytes,sizeof (u.tmp));DEBUG_ENT ("going to reseed %s with %d bits " "(%d of %d requested)\n" , r->name, bytes *8 , nbytes *8 , r->entropy_count); - bytes =extract_entropy (r->pull, tmp, bytes, + bytes =extract_entropy (r->pull, u.tmp, bytes, random_read_wakeup_thresh /8 , rsvd); -mix_pool_bytes (r, tmp, bytes,NULL ); +mix_pool_bytes (r, u.tmp, bytes,NULL );credit_entropy_bits (r, bytes*8 ); } +kmemcheck_mark_initialized (&u.hwrand,sizeof (u.hwrand)); +for (i =0 ; i <4 ; i++) +if (arch_get_random_long (&u.hwrand[i])) +break ; +if (i) +mix_pool_bytes (r, &u.hwrand,sizeof (u.hwrand),0 ); }/*
Signature · 1 line
1.7.2.1.45.g54fbc
PATCH 171/180 random: add new get_random_bytes_arch() function
In reply to a message not in the archive2.6.32-longterm review patch. If anyone has any objections, please let me know.
------------------
From: Theodore Ts'o <[email protected]>
commit c2557a303ab6712bb6e09447df828c557c710ac9 upstream.
Create a new function, get_random_bytes_arch() which will use the architecture-specific hardware random number generator if it is present. Change get_random_bytes() to not use the HW RNG, even if it is avaiable.
The reason for this is that the hw random number generator is fast (if it is present), but it requires that we trust the hardware manufacturer to have not put in a back door. (For example, an increasing counter encrypted by an AES key known to the NSA.)
It's unlikely that Intel (for example) was paid off by the US Government to do this, but it's impossible for them to prove otherwise
--- especially since Bull Mountain is documented to use AES as a
whitener. Hence, the output of an evil, trojan-horse version of RDRAND is statistically indistinguishable from an RDRAND implemented to the specifications claimed by Intel. Short of using a tunnelling electronic microscope to reverse engineer an Ivy Bridge chip and disassembling and analyzing the CPU microcode, there's no way for us to tell for sure.
Since users of get_random_bytes() in the Linux kernel need to be able to support hardware systems where the HW RNG is not present, most time-sensitive users of this interface have already created their own cryptographic RNG interface which uses get_random_bytes() as a seed. So it's much better to use the HW RNG to improve the existing random number generator, by mixing in any entropy returned by the HW RNG into /dev/random's entropy pool, but to always _use_ /dev/random's entropy pool.
This way we get almost of the benefits of the HW RNG without any potential liabilities. The only benefits we forgo is the speed/performance enhancements --- and generic kernel code can't depend on depend on get_random_bytes() having the speed of a HW RNG anyway.
For those places that really want access to the arch-specific HW RNG, if it is available, we provide get_random_bytes_arch().
--- drivers/char/random.c | 27 +++++++++++++++++++++++---- include/linux/random.h | 1 + 2 files changed, 24 insertions(+), 4 deletions(-)
drivers/char/random.c +23 -4
@@ -1038,11 +1038,28 @@ static ssize_t extract_entropy_user(struct entropy_store *r, void __user *buf,/* * This function is the exported kernel interface. It returns some -* number of good random numbers, suitable for seeding TCP sequence -* numbers, etc. +* number of good random numbers, suitable for key generation, seeding +* TCP sequence numbers, etc. It does not use the hw random number +* generator, if available; use get_random_bytes_arch() for that. */ void get_random_bytes (void *buf,int nbytes) { +extract_entropy (&nonblocking_pool, buf, nbytes,0 ,0 ); +} +EXPORT_SYMBOL (get_random_bytes); + +/* +* This function will use the architecture-specific hardware random +* number generator if it is available. The arch-specific hw RNG will +* almost certainly be faster than what we can do in software, but it +* is impossible to verify that it is implemented securely (as +* opposed, to, say, the AES encryption of a sequence number using a +* key known by the NSA). So it's useful if we need the speed, but +* only if we're willing to trust the hardware manufacturer not to +* have put in a back door. +*/ +void get_random_bytes_arch (void *buf,int nbytes) +{char *p = buf;while (nbytes) {
@@ -1057,9 +1074,11 @@ void get_random_bytes(void *buf, int nbytes) nbytes -= chunk; } -extract_entropy (&nonblocking_pool, p, nbytes,0 ,0 ); +if (nbytes) +extract_entropy (&nonblocking_pool, p, nbytes,0 ,0 ); } -EXPORT_SYMBOL (get_random_bytes); +EXPORT_SYMBOL (get_random_bytes_arch); +/* * init_std_data - initialize pool with system data
include/linux/random.h +1 -0
@@ -52,6 +52,7 @@ extern void add_input_randomness(unsigned int type, unsigned int code,extern void add_interrupt_randomness (int irq,int irq_flags);extern void get_random_bytes (void *buf,int nbytes); +extern void get_random_bytes_arch (void *buf,int nbytes);void generate_random_uuid (unsigned char uuid_out[16 ]);#ifndef MODULE
Signature · 1 line
1.7.2.1.45.g54fbc
PATCH 172/180 random: mix in architectural randomness in extract_buf()
In reply to a message not in the archive2.6.32-longterm review patch. If anyone has any objections, please let me know.
------------------
From: H. Peter Anvin <[email protected]>
commit d2e7c96af1e54b507ae2a6a7dd2baf588417a7e5 upstream.
Mix in any architectural randomness in extract_buf() instead of xfer_secondary_buf(). This allows us to mix in more architectural randomness, and it also makes xfer_secondary_buf() faster, moving a tiny bit of additional CPU overhead to process which is extracting the randomness.
[ Commit description modified by tytso to remove an extended
advertisement for the RDRAND instruction. ]
--- drivers/char/random.c | 56 ++++++++++++++++++++++++++++--------------------- 1 files changed, 32 insertions(+), 24 deletions(-)
drivers/char/random.c +32 -24
@@ -274,6 +274,8 @@#define SEC_XFER_SIZE 512#define EXTRACT_SIZE 10 +#define LONGS (x) (((x) + sizeof(unsigned long) - 1)/sizeof(unsigned long)) +/* * The minimum number of bits of entropy before we wake up a read on * /dev/random. Should be enough to do a significant reseed.
@@ -835,11 +837,7 @@ static ssize_t extract_entropy(struct entropy_store *r, void *buf,*/ static void xfer_secondary_pool (struct entropy_store *r,size_t nbytes) { -union { -__u32 tmp[OUTPUT_POOL_WORDS ]; -long hwrand[4 ]; - } u; -int i; +__u32 tmp[OUTPUT_POOL_WORDS ];if (r->pull && r->entropy_count < nbytes *8 && r->entropy_count < r->poolinfo->POOLBITS) {
@@ -850,23 +848,17 @@ static void xfer_secondary_pool(struct entropy_store *r, size_t nbytes)/* pull at least as many as BYTES as wakeup BITS */ bytes =max_t (int, bytes, random_read_wakeup_thresh /8 );/* but never more than the buffer size */ - bytes =min_t (int, bytes,sizeof (u.tmp)); + bytes =min_t (int, bytes,sizeof (tmp));DEBUG_ENT ("going to reseed %s with %d bits " "(%d of %d requested)\n" , r->name, bytes *8 , nbytes *8 , r->entropy_count); - bytes =extract_entropy (r->pull, u.tmp, bytes, + bytes =extract_entropy (r->pull, tmp, bytes, random_read_wakeup_thresh /8 , rsvd); -mix_pool_bytes (r, u.tmp, bytes,NULL ); +mix_pool_bytes (r, tmp, bytes,NULL );credit_entropy_bits (r, bytes*8 ); } -kmemcheck_mark_initialized (&u.hwrand,sizeof (u.hwrand)); -for (i =0 ; i <4 ; i++) -if (arch_get_random_long (&u.hwrand[i])) -break ; -if (i) -mix_pool_bytes (r, &u.hwrand,sizeof (u.hwrand),0 ); }/*
@@ -923,15 +915,19 @@ static size_t account(struct entropy_store *r, size_t nbytes, int min,static void extract_buf (struct entropy_store *r,__u8 *out) {int i; -__u32 hash[5 ], workspace[SHA_WORKSPACE_WORDS ]; +union { +__u32 w[5 ]; +unsigned long l[LONGS (EXTRACT_SIZE )]; + } hash; +__u32 workspace[SHA_WORKSPACE_WORDS ];__u8 extract[64 ];unsigned long flags;/* Generate a hash across the pool, 16 words (512 bits) at a time */ -sha_init (hash); +sha_init (hash.w);spin_lock_irqsave (&r->lock, flags);for (i =0 ; i < r->poolinfo->poolwords; i +=16 ) -sha_transform (hash, (__u8 *)(r->pool + i), workspace); +sha_transform (hash.w, (__u8 *)(r->pool + i), workspace);/* * We mix the hash back into the pool to prevent backtracking
@@ -942,14 +938,14 @@ static void extract_buf(struct entropy_store *r, __u8 *out)* brute-forcing the feedback as hard as brute-forcing the * hash. */ -__mix_pool_bytes (r, hash,sizeof (hash), extract); +__mix_pool_bytes (r, hash.w,sizeof (hash.w), extract);spin_unlock_irqrestore (&r->lock, flags);/* * To avoid duplicates, we atomically extract a portion of the * pool while mixing, and hash one final time. */ -sha_transform (hash, extract, workspace); +sha_transform (hash.w, extract, workspace);memset (extract,0 ,sizeof (extract));memset (workspace,0 ,sizeof (workspace));
@@ -958,11 +954,23 @@ static void extract_buf(struct entropy_store *r, __u8 *out)* pattern, we fold it in half. Thus, we always feed back * twice as much data as we output. */ - hash[0 ] ^= hash[3 ]; - hash[1 ] ^= hash[4 ]; - hash[2 ] ^=rol32 (hash[2 ],16 ); -memcpy (out, hash,EXTRACT_SIZE ); -memset (hash,0 ,sizeof (hash)); + hash.w[0 ] ^= hash.w[3 ]; + hash.w[1 ] ^= hash.w[4 ]; + hash.w[2 ] ^=rol32 (hash.w[2 ],16 ); + +/* +* If we have a architectural hardware random number +* generator, mix that in, too. +*/ +for (i =0 ; i <LONGS (EXTRACT_SIZE ); i++) { +unsigned long v; +if (!arch_get_random_long (&v)) +break ; + hash.l[i] ^= v; + } + +memcpy (out, &hash,EXTRACT_SIZE ); +memset (&hash,0 ,sizeof (hash)); } static ssize_t extract_entropy(struct entropy_store *r, void *buf,
Signature · 1 line
1.7.2.1.45.g54fbc
PATCH 173/180 MAINTAINERS: Theodore Tso is taking over the random driver
In reply to a message not in the archive2.6.32-longterm review patch. If anyone has any objections, please let me know.
------------------
From: Theodore Ts'o <[email protected]>
commit 330e0a01d54c2b8606c56816f99af6ebc58ec92c upstream.
Matt Mackall stepped down as the /dev/random driver maintainer last year, so Theodore Ts'o is taking back the /dev/random driver.
--- MAINTAINERS | 2 +- 1 files changed, 1 insertions(+), 1 deletions(-)
MAINTAINERS +1 -1
@@ -4379,7 +4379,7 @@ F: Documentation/blockdev/ramdisk.txt F: drivers/block/brd.c RANDOM NUMBER DRIVER -M: Matt Mackall <[email protected]> +M: Theodore Ts'o" <[email protected]> S: Maintained F: drivers/char/random.c
Signature · 1 line
1.7.2.1.45.g54fbc
PATCH 174/180 usb: feed USB device information to the /dev/random driver
In reply to a message not in the archive2.6.32-longterm review patch. If anyone has any objections, please let me know.
------------------
From: Theodore Ts'o <[email protected]>
commit b04b3156a20d395a7faa8eed98698d1e17a36000 upstream.
Send the USB device's serial, product, and manufacturer strings to the /dev/random driver to help seed its pools.
--- drivers/usb/core/hub.c | 9 +++++++++ 1 files changed, 9 insertions(+), 0 deletions(-)
drivers/usb/core/hub.c +9 -0
@@ -23,6 +23,7 @@#include <linux/mutex.h> #include <linux/freezer.h> #include <linux/usb/quirks.h> +#include <linux/random.h> #include <asm/uaccess.h> #include <asm/byteorder.h>
@@ -1831,6 +1832,14 @@ int usb_new_device(struct usb_device *udev)/* Tell the world! */ announce_device (udev); +if (udev->serial) +add_device_randomness (udev->serial,strlen (udev->serial)); +if (udev->product) +add_device_randomness (udev->product,strlen (udev->product)); +if (udev->manufacturer) +add_device_randomness (udev->manufacturer, +strlen (udev->manufacturer)); +/* Register the device. The device driver is responsible * for configuring the device and invoking the add-device * notifier chain (used by usbfs and possibly others).
Signature · 1 line
1.7.2.1.45.g54fbc
PATCH 175/180 net: feed /dev/random with the MAC address when registering a device
In reply to a message not in the archive2.6.32-longterm review patch. If anyone has any objections, please let me know.
------------------
From: Theodore Ts'o <[email protected]>
commit 7bf2357524408b97fec58344caf7397f8140c3fd upstream.
--- net/core/dev.c | 3 +++ net/core/rtnetlink.c | 1 + 2 files changed, 4 insertions(+), 0 deletions(-)
net/core/dev.c +3 -0
@@ -1133,6 +1133,7 @@ int dev_open(struct net_device *dev)/* * ... and announce new interface. */ +add_device_randomness (dev->dev_addr, dev->addr_len);call_netdevice_notifiers (NETDEV_UP , dev); }
@@ -4268,6 +4269,7 @@ int dev_set_mac_address(struct net_device *dev, struct sockaddr *sa) err = ops->ndo_set_mac_address (dev, sa);if (!err)call_netdevice_notifiers (NETDEV_CHANGEADDR , dev); +add_device_randomness (dev->dev_addr, dev->addr_len);return err; }EXPORT_SYMBOL (dev_set_mac_address);
@@ -4871,6 +4873,7 @@ int register_netdevice(struct net_device *dev)dev_init_scheduler (dev);dev_hold (dev);list_netdevice (dev); +add_device_randomness (dev->dev_addr, dev->addr_len);/* Notify protocols, that a new device appeared. */ ret =call_netdevice_notifiers (NETDEV_REGISTER , dev);
net/core/rtnetlink.c +1 -0
@@ -817,6 +817,7 @@ static int do_setlink(struct net_device *dev, struct ifinfomsg *ifm, goto errout; send_addr_notify =1 ; modified =1 ; +add_device_randomness (dev->dev_addr, dev->addr_len); }if (tb[IFLA_MTU ]) {
Signature · 1 line
1.7.2.1.45.g54fbc
PATCH 176/180 random: remove rand_initialize_irq()
In reply to a message not in the archive2.6.32-longterm review patch. If anyone has any objections, please let me know.
------------------
From: Theodore Ts'o <[email protected]>
commit c5857ccf293968348e5eb4ebedc68074de3dcda6 upstream.
With the new interrupt sampling system, we are no longer using the timer_rand_state structure in the irq descriptor, so we can stop initializing it now.
[ Merged in fixes from Sedat to find some last missing references to
rand_initialize_irq() ]
--- arch/ia64/kernel/irq_ia64.c | 1 - drivers/char/random.c | 55 ------------------------------------------- include/linux/irq.h | 1 - include/linux/random.h | 2 - kernel/irq/manage.c | 17 ------------- 5 files changed, 0 insertions(+), 76 deletions(-)
arch/ia64/kernel/irq_ia64.c +0 -1
@@ -24,7 +24,6 @@#include <linux/kernel_stat.h> #include <linux/slab.h> #include <linux/ptrace.h> -#include <linux/random.h> /* for rand_initialize_irq() */ #include <linux/signal.h> #include <linux/smp.h> #include <linux/threads.h>
drivers/char/random.c +0 -55
67 lines not on this page · raw message
include/linux/irq.h +0 -1
@@ -174,7 +174,6 @@ struct irq_2_iommu;*/ struct irq_desc {unsigned int irq; -struct timer_rand_state *timer_rand_state;unsigned int *kstat_irqs;#ifdef CONFIG_INTR_REMAP struct irq_2_iommu *irq_2_iommu;
include/linux/random.h +0 -2
@@ -44,8 +44,6 @@ struct rand_pool_info {#ifdef __KERNEL__ -extern void rand_initialize_irq (int irq); -extern void add_device_randomness (const void *,unsigned int );extern void add_input_randomness (unsigned int type,unsigned int code,unsigned int value);
kernel/irq/manage.c +0 -17
@@ -633,22 +633,6 @@ __setup_irq(unsigned int irq, struct irq_desc *desc, struct irqaction *new)if (desc->chip == &no_irq_chip)return -ENOSYS ; -/* -* Some drivers like serial.c use request_irq() heavily, -* so we have to be careful not to interfere with a -* running system. -*/ -if (new->flags &IRQF_SAMPLE_RANDOM ) { -/* -* This function might sleep, we want to call it first, -* outside of the atomic block. -* Yes, this might clear the entropy pool if the wrong -* driver is attempted to be loaded, without actually -* installing a new handler, but is this really a problem, -* only the sysadmin is able to do this. -*/ -rand_initialize_irq (irq); - }/* Oneshot interrupts are not allowed with shared */ if ((new->flags &IRQF_ONESHOT ) && (new->flags &IRQF_SHARED ))
@@ -1021,7 +1005,6 @@ EXPORT_SYMBOL(free_irq);* * IRQF_SHARED Interrupt is shared * IRQF_DISABLED Disable local interrupts while processing -* IRQF_SAMPLE_RANDOM The interrupt can be used for entropy * IRQF_TRIGGER_* Specify active edge(s) or level * */
Signature · 1 line
1.7.2.1.45.g54fbc
PATCH 177/180 random: Add comment to random_initialize()
In reply to a message not in the archive2.6.32-longterm review patch. If anyone has any objections, please let me know.
------------------
From: Tony Luck <[email protected]>
commit cbc96b7594b5691d61eba2db8b2ea723645be9ca upstream.
Many platforms have per-machine instance data (serial numbers, asset tags, etc.) squirreled away in areas that are accessed during early system bringup. Mixing this data into the random pools has a very high value in providing better random data, so we should allow (and even encourage) architecture code to call add_device_randomness() from the setup_arch() paths.
However, this limits our options for internal structure of the random driver since random_initialize() is not called until long after setup_arch().
Add a big fat comment to rand_initialize() spelling out this requirement.
--- drivers/char/random.c | 10 ++++++++++ 1 files changed, 10 insertions(+), 0 deletions(-)
drivers/char/random.c +10 -0
@@ -1077,6 +1077,16 @@ static void init_std_data(struct entropy_store *r)mix_pool_bytes (r,utsname (),sizeof (*(utsname ())),NULL ); } +/* +* Note that setup_arch() may call add_device_randomness() +* long before we get here. This allows seeding of the pools +* with some platform dependent data very early in the boot +* process. But it limits our options here. We must use +* statically allocated structures that already have all +* initializations complete at compile time. We should also +* take care not to overwrite the precious per platform data +* we were given. +*/ static int rand_initialize (void ) {init_std_data (&input_pool);
Signature · 1 line
1.7.2.1.45.g54fbc
PATCH 178/180 rtc: wm831x: Feed the write counter into device_add_randomness()
In reply to a message not in the archive2.6.32-longterm review patch. If anyone has any objections, please let me know.
------------------
From: Mark Brown <[email protected]>
commit 9dccf55f4cb011a7552a8a2749a580662f5ed8ed upstream.
The tamper evident features of the RTC include the "write counter" which is a pseudo-random number regenerated whenever we set the RTC. Since this value is unpredictable it should provide some useful seeding to the random number generator.
Only do this on boot since the goal is to seed the pool rather than add useful entropy.
--- drivers/rtc/rtc-wm831x.c | 24 +++++++++++++++++++++++- 1 files changed, 23 insertions(+), 1 deletions(-)
drivers/rtc/rtc-wm831x.c +23 -1
@@ -23,7 +23,7 @@#include <linux/mfd/wm831x/core.h> #include <linux/delay.h> #include <linux/platform_device.h> - +#include <linux/random.h> /* * R16416 (0x4020) - RTC Write Counter
@@ -95,6 +95,26 @@ struct wm831x_rtc { unsigned int alarm_enabled:1; }; +static void wm831x_rtc_add_randomness (struct wm831x *wm831x) +{ +int ret; +u16 reg; + +/* +* The write counter contains a pseudo-random number which is +* regenerated every time we set the RTC so it should be a +* useful per-system source of entropy. +*/ + ret =wm831x_reg_read (wm831x,WM831X_RTC_WRITE_COUNTER ); +if (ret >=0 ) { + reg = ret; +add_device_randomness (®,sizeof (reg)); + }else { +dev_warn (wm831x->dev,"Failed to read RTC write counter: %d\n" , + ret); + } +} +/* * Read current time and date in RTC */
@@ -464,6 +484,8 @@ static int wm831x_rtc_probe(struct platform_device *pdev) alm_irq, ret); } +wm831x_rtc_add_randomness (wm831x); +return 0 ; err:
Signature · 1 line
1.7.2.1.45.g54fbc
PATCH 179/180 mfd: wm831x: Feed the device UUID into device_add_randomness()
In reply to a message not in the archive2.6.32-longterm review patch. If anyone has any objections, please let me know.
------------------
From: Mark Brown <[email protected]>
commit 27130f0cc3ab97560384da437e4621fc4e94f21c upstream.
wm831x devices contain a unique ID value. Feed this into the newly added device_add_randomness() to add some per device seed data to the pool.
--- drivers/mfd/wm831x-otp.c | 8 ++++++++ 1 files changed, 8 insertions(+), 0 deletions(-)
drivers/mfd/wm831x-otp.c +8 -0
@@ -18,6 +18,7 @@#include <linux/bcd.h> #include <linux/delay.h> #include <linux/mfd/core.h> +#include <linux/random.h> #include <linux/mfd/wm831x/core.h> #include <linux/mfd/wm831x/otp.h>
@@ -66,6 +67,7 @@ static DEVICE_ATTR(unique_id, 0444, wm831x_unique_id_show, NULL);int wm831x_otp_init (struct wm831x *wm831x) { +char uuid[WM831X_UNIQUE_ID_LEN ];int ret; ret =device_create_file (wm831x->dev, &dev_attr_unique_id);
@@ -73,6 +75,12 @@ int wm831x_otp_init(struct wm831x *wm831x)dev_err (wm831x->dev,"Unique ID attribute not created: %d\n" , ret); + ret =wm831x_unique_id_read (wm831x, uuid); +if (ret ==0 ) +add_device_randomness (uuid,sizeof (uuid)); +else +dev_err (wm831x->dev,"Failed to read UUID: %d\n" , ret); +return ret; }
Signature · 1 line
1.7.2.1.45.g54fbc
PATCH 180/180 dmi: Feed DMI table to /dev/random driver
In reply to a message not in the archive2.6.32-longterm review patch. If anyone has any objections, please let me know.
------------------
From: Tony Luck <[email protected]>
commit d114a33387472555188f142ed8e98acdb8181c6d upstream.
Send the entire DMI (SMBIOS) table to the /dev/random driver to help seed its pools.
--- drivers/firmware/dmi_scan.c | 3 +++ 1 files changed, 3 insertions(+), 0 deletions(-)
drivers/firmware/dmi_scan.c +3 -0
@@ -6,6 +6,7 @@#include <linux/efi.h> #include <linux/bootmem.h> #include <linux/slab.h> +#include <linux/random.h> #include <asm/dmi.h> /*
@@ -111,6 +112,8 @@ static int __init dmi_walk_early(void (*decode)(const struct dmi_header *,dmi_table (buf, dmi_len, dmi_num, decode,NULL ); +add_device_randomness (buf, dmi_len); +dmi_iounmap (buf, dmi_len);return 0 ; }
Signature · 1 line
1.7.2.1.45.g54fbc