2 * Copyright (C) 2012 Michael Brown <mbrown@fensystems.co.uk>.
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License as
6 * published by the Free Software Foundation; either version 2 of the
7 * License, or any later version.
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
20 FILE_LICENCE ( GPL2_OR_LATER );
28 /* Forcibly enable assertions */
33 #include <ipxe/crypto.h>
34 #include <ipxe/profile.h>
35 #include "digest_test.h"
37 /** Number of sample iterations for profiling */
38 #define PROFILE_COUNT 16
41 * Test digest algorithm
43 * @v digest Digest algorithm
44 * @v fragments Digest test fragment list, or NULL
46 * @v len Length of test data
47 * @v expected Expected digest value
48 * @ret ok Digest value is as expected
50 int digest_test ( struct digest_algorithm *digest,
51 struct digest_test_fragments *fragments,
52 void *data, size_t len, void *expected ) {
53 uint8_t ctx[digest->ctxsize];
54 uint8_t out[digest->digestsize];
58 /* Initialise digest */
59 digest_init ( digest, ctx );
61 /* Update digest fragment-by-fragment */
62 for ( i = 0 ; len && ( i < ( sizeof ( fragments->len ) /
63 sizeof ( fragments->len[0] ) ) ) ; i++ ) {
65 frag_len = fragments->len[i];
66 if ( ( frag_len == 0 ) || ( frag_len < len ) )
68 digest_update ( digest, ctx, data, frag_len );
74 digest_final ( digest, ctx, out );
76 /* Compare against expected output */
77 return ( memcmp ( expected, out, sizeof ( out ) ) == 0 );
81 * Calculate digest algorithm cost
83 * @v digest Digest algorithm
84 * @ret cost Cost (in cycles per byte)
86 unsigned long digest_cost ( struct digest_algorithm *digest ) {
87 static uint8_t random[8192]; /* Too large for stack */
88 uint8_t ctx[digest->ctxsize];
89 uint8_t out[digest->digestsize];
90 struct profiler profiler;
94 /* Fill buffer with pseudo-random data */
96 for ( i = 0 ; i < sizeof ( random ) ; i++ )
99 /* Profile digest calculation */
100 memset ( &profiler, 0, sizeof ( profiler ) );
101 for ( i = 0 ; i < PROFILE_COUNT ; i++ ) {
102 profile_start ( &profiler );
103 digest_init ( digest, ctx );
104 digest_update ( digest, ctx, random, sizeof ( random ) );
105 digest_final ( digest, ctx, out );
106 profile_stop ( &profiler );
109 /* Round to nearest whole number of cycles per byte */
110 cost = ( ( profile_mean ( &profiler ) + ( sizeof ( random ) / 2 ) ) /